@downcity/city 1.1.39 → 1.1.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -9
- package/bin/cli/Index.js +2 -0
- package/bin/cli/Index.js.map +1 -1
- package/bin/cli/agent/AgentChat.d.ts +2 -1
- package/bin/cli/agent/AgentChat.d.ts.map +1 -1
- package/bin/cli/agent/AgentChat.js +93 -214
- package/bin/cli/agent/AgentChat.js.map +1 -1
- package/bin/cli/agent/AgentChatTypes.d.ts +8 -12
- package/bin/cli/agent/AgentChatTypes.d.ts.map +1 -1
- package/bin/cli/agent/AgentHistory.js +2 -2
- package/bin/cli/agent/AgentHistory.js.map +1 -1
- package/bin/cli/agent/AgentManager.d.ts.map +1 -1
- package/bin/cli/agent/AgentManager.js +26 -27
- package/bin/cli/agent/AgentManager.js.map +1 -1
- package/bin/cli/agent/AgentManagerTypes.d.ts +2 -2
- package/bin/cli/agent/AgentManagerTypes.d.ts.map +1 -1
- package/bin/cli/agent/AgentReset.js +4 -4
- package/bin/cli/agent/AgentReset.js.map +1 -1
- package/bin/cli/agent/AgentSelection.js +6 -6
- package/bin/cli/agent/AgentSelection.js.map +1 -1
- package/bin/cli/agent/AgentSelectionTypes.d.ts +1 -1
- package/bin/cli/agent/AgentSelectionTypes.d.ts.map +1 -1
- package/bin/cli/agent/Init.js +10 -10
- package/bin/cli/agent/Init.js.map +1 -1
- package/bin/cli/agent/Restart.js +2 -2
- package/bin/cli/agent/Restart.js.map +1 -1
- package/bin/cli/agent/Run.d.ts +1 -1
- package/bin/cli/agent/Run.d.ts.map +1 -1
- package/bin/cli/agent/Run.js +37 -17
- package/bin/cli/agent/Run.js.map +1 -1
- package/bin/cli/agent/Start.js +2 -2
- package/bin/cli/agent/Start.js.map +1 -1
- package/bin/cli/agent/Stop.js +2 -2
- package/bin/cli/agent/Stop.js.map +1 -1
- package/bin/cli/control-plane/ControlPlaneProcess.js +5 -5
- package/bin/cli/control-plane/ControlPlaneProcess.js.map +1 -1
- package/bin/cli/model/ModelCreateCommand.js +1 -1
- package/bin/cli/model/ModelCreateCommand.js.map +1 -1
- package/bin/cli/model/ModelManageCommand.d.ts.map +1 -1
- package/bin/cli/model/ModelManageCommand.js +5 -3
- package/bin/cli/model/ModelManageCommand.js.map +1 -1
- package/bin/cli/model/ModelManager.js +3 -3
- package/bin/cli/model/ModelManager.js.map +1 -1
- package/bin/cli/model/ModelSupport.d.ts +0 -1
- package/bin/cli/model/ModelSupport.d.ts.map +1 -1
- package/bin/cli/model/ModelSupport.js +2 -11
- package/bin/cli/model/ModelSupport.js.map +1 -1
- package/bin/cli/shared/CliReporterTypes.d.ts +1 -1
- package/bin/cli/shared/Config.js +2 -2
- package/bin/cli/shared/Config.js.map +1 -1
- package/bin/cli/shared/Env.d.ts +1 -1
- package/bin/cli/shared/Env.d.ts.map +1 -1
- package/bin/cli/shared/Env.js +18 -149
- package/bin/cli/shared/Env.js.map +1 -1
- package/bin/cli/shared/IndexAgentCommand.d.ts.map +1 -1
- package/bin/cli/shared/IndexAgentCommand.js +3 -3
- package/bin/cli/shared/IndexAgentCommand.js.map +1 -1
- package/bin/cli/shared/IndexSupport.d.ts +3 -3
- package/bin/cli/shared/IndexSupport.d.ts.map +1 -1
- package/bin/cli/shared/IndexSupport.js +14 -8
- package/bin/cli/shared/IndexSupport.js.map +1 -1
- package/bin/cli/shared/ManagedPluginActionCommands.d.ts.map +1 -1
- package/bin/cli/shared/ManagedPluginActionCommands.js +5 -4
- package/bin/cli/shared/ManagedPluginActionCommands.js.map +1 -1
- package/bin/cli/shared/ManagedPluginRemote.d.ts.map +1 -1
- package/bin/cli/shared/ManagedPluginRemote.js +4 -4
- package/bin/cli/shared/ManagedPluginRemote.js.map +1 -1
- package/bin/cli/shared/PluginTargetSupport.d.ts +2 -2
- package/bin/cli/shared/PluginTargetSupport.d.ts.map +1 -1
- package/bin/cli/shared/PluginTargetSupport.js +19 -19
- package/bin/cli/shared/PluginTargetSupport.js.map +1 -1
- package/bin/cli/shared/Plugins.js +10 -10
- package/bin/cli/shared/Plugins.js.map +1 -1
- package/bin/cli/shared/PublicHostEnv.d.ts +1 -1
- package/bin/cli/shared/PublicHostEnv.js +2 -2
- package/bin/cli/shared/PublicHostEnv.js.map +1 -1
- package/bin/cli/shared/Terminal.d.ts +13 -0
- package/bin/cli/shared/Terminal.d.ts.map +1 -0
- package/bin/cli/shared/Terminal.js +22 -0
- package/bin/cli/shared/Terminal.js.map +1 -0
- package/bin/config/DowncitySchema.d.ts.map +1 -1
- package/bin/config/DowncitySchema.js +3 -111
- package/bin/config/DowncitySchema.js.map +1 -1
- package/bin/config/Paths.d.ts +0 -56
- package/bin/config/Paths.d.ts.map +1 -1
- package/bin/config/Paths.js +9 -51
- package/bin/config/Paths.js.map +1 -1
- package/bin/control/ControlGateway.js +1 -1
- package/bin/control/ControlGateway.js.map +1 -1
- package/bin/control/EnvApiRoutes.d.ts +1 -1
- package/bin/control/EnvApiRoutes.d.ts.map +1 -1
- package/bin/control/EnvApiRoutes.js +7 -79
- package/bin/control/EnvApiRoutes.js.map +1 -1
- package/bin/control/PlatformApiRoutes.d.ts +2 -2
- package/bin/control/PlatformApiRoutes.d.ts.map +1 -1
- package/bin/control/PlatformApiRoutes.js +2 -2
- package/bin/control/PlatformApiRoutes.js.map +1 -1
- package/bin/control/gateway/AgentActions.d.ts +2 -2
- package/bin/control/gateway/AgentActions.d.ts.map +1 -1
- package/bin/control/gateway/AgentActions.js +7 -7
- package/bin/control/gateway/AgentActions.js.map +1 -1
- package/bin/control/gateway/AgentCatalog.d.ts +3 -6
- package/bin/control/gateway/AgentCatalog.d.ts.map +1 -1
- package/bin/control/gateway/AgentCatalog.js +16 -18
- package/bin/control/gateway/AgentCatalog.js.map +1 -1
- package/bin/control/instant/InstantSessionRunner.d.ts.map +1 -1
- package/bin/control/instant/InstantSessionRunner.js +3 -1
- package/bin/control/instant/InstantSessionRunner.js.map +1 -1
- package/bin/env/ProcessEnv.d.ts +24 -0
- package/bin/env/ProcessEnv.d.ts.map +1 -0
- package/bin/env/ProcessEnv.js +41 -0
- package/bin/env/ProcessEnv.js.map +1 -0
- package/bin/http/auth/AuthEnv.d.ts +1 -1
- package/bin/http/auth/AuthEnv.js +1 -1
- package/bin/model/runtime/CreateRuntimeModel.d.ts +8 -0
- package/bin/model/runtime/CreateRuntimeModel.d.ts.map +1 -1
- package/bin/model/runtime/CreateRuntimeModel.js +43 -37
- package/bin/model/runtime/CreateRuntimeModel.js.map +1 -1
- package/bin/model/service/ModelPoolService.d.ts +1 -1
- package/bin/model/service/ModelPoolService.d.ts.map +1 -1
- package/bin/model/service/ModelPoolService.js +8 -6
- package/bin/model/service/ModelPoolService.js.map +1 -1
- package/bin/platform/store/StoreEnvRepository.d.ts +5 -49
- package/bin/platform/store/StoreEnvRepository.d.ts.map +1 -1
- package/bin/platform/store/StoreEnvRepository.js +31 -178
- package/bin/platform/store/StoreEnvRepository.js.map +1 -1
- package/bin/platform/store/StoreSchema.js +3 -44
- package/bin/platform/store/StoreSchema.js.map +1 -1
- package/bin/platform/store/index.d.ts +9 -45
- package/bin/platform/store/index.d.ts.map +1 -1
- package/bin/platform/store/index.js +12 -62
- package/bin/platform/store/index.js.map +1 -1
- package/bin/platform/store/schema.d.ts +2 -2
- package/bin/platform/store/schema.js +2 -2
- package/bin/process/daemon/Api.d.ts +1 -1
- package/bin/process/daemon/CliArgs.d.ts +1 -0
- package/bin/process/daemon/CliArgs.d.ts.map +1 -1
- package/bin/process/daemon/CliArgs.js +20 -1
- package/bin/process/daemon/CliArgs.js.map +1 -1
- package/bin/process/daemon/Client.d.ts +18 -2
- package/bin/process/daemon/Client.d.ts.map +1 -1
- package/bin/process/daemon/Client.js +70 -20
- package/bin/process/daemon/Client.js.map +1 -1
- package/bin/process/daemon/Manager.d.ts.map +1 -1
- package/bin/process/daemon/Manager.js +2 -1
- package/bin/process/daemon/Manager.js.map +1 -1
- package/bin/terminal/admin/auth-error.d.ts +34 -0
- package/bin/terminal/admin/auth-error.d.ts.map +1 -0
- package/bin/terminal/admin/auth-error.js +51 -0
- package/bin/terminal/admin/auth-error.js.map +1 -0
- package/bin/terminal/admin/commands/accounts.d.ts +6 -0
- package/bin/terminal/admin/commands/accounts.d.ts.map +1 -0
- package/bin/terminal/admin/commands/accounts.js +44 -0
- package/bin/terminal/admin/commands/accounts.js.map +1 -0
- package/bin/terminal/admin/commands/balance.d.ts +6 -0
- package/bin/terminal/admin/commands/balance.d.ts.map +1 -0
- package/bin/terminal/admin/commands/balance.js +153 -0
- package/bin/terminal/admin/commands/balance.js.map +1 -0
- package/bin/terminal/admin/commands/config.d.ts +10 -0
- package/bin/terminal/admin/commands/config.d.ts.map +1 -0
- package/bin/terminal/admin/commands/config.js +11 -0
- package/bin/terminal/admin/commands/config.js.map +1 -0
- package/bin/terminal/admin/commands/custom.d.ts +6 -0
- package/bin/terminal/admin/commands/custom.d.ts.map +1 -0
- package/bin/terminal/admin/commands/custom.js +47 -0
- package/bin/terminal/admin/commands/custom.js.map +1 -0
- package/bin/terminal/admin/commands/instruction.d.ts +9 -0
- package/bin/terminal/admin/commands/instruction.d.ts.map +1 -0
- package/bin/terminal/admin/commands/instruction.js +10 -0
- package/bin/terminal/admin/commands/instruction.js.map +1 -0
- package/bin/terminal/admin/commands/models.d.ts +14 -0
- package/bin/terminal/admin/commands/models.d.ts.map +1 -0
- package/bin/terminal/admin/commands/models.js +61 -0
- package/bin/terminal/admin/commands/models.js.map +1 -0
- package/bin/terminal/admin/commands/payment.d.ts +6 -0
- package/bin/terminal/admin/commands/payment.d.ts.map +1 -0
- package/bin/terminal/admin/commands/payment.js +59 -0
- package/bin/terminal/admin/commands/payment.js.map +1 -0
- package/bin/terminal/admin/commands/products.d.ts +6 -0
- package/bin/terminal/admin/commands/products.d.ts.map +1 -0
- package/bin/terminal/admin/commands/products.js +80 -0
- package/bin/terminal/admin/commands/products.js.map +1 -0
- package/bin/terminal/admin/commands/service-env.d.ts +11 -0
- package/bin/terminal/admin/commands/service-env.d.ts.map +1 -0
- package/bin/terminal/admin/commands/service-env.js +248 -0
- package/bin/terminal/admin/commands/service-env.js.map +1 -0
- package/bin/terminal/admin/commands/usage.d.ts +6 -0
- package/bin/terminal/admin/commands/usage.d.ts.map +1 -0
- package/bin/terminal/admin/commands/usage.js +44 -0
- package/bin/terminal/admin/commands/usage.js.map +1 -0
- package/bin/terminal/admin/loop.d.ts +6 -0
- package/bin/terminal/admin/loop.d.ts.map +1 -0
- package/bin/terminal/admin/loop.js +70 -0
- package/bin/terminal/admin/loop.js.map +1 -0
- package/bin/terminal/agent/pi-agent.d.ts +15 -0
- package/bin/terminal/agent/pi-agent.d.ts.map +1 -0
- package/bin/terminal/agent/pi-agent.js +136 -0
- package/bin/terminal/agent/pi-agent.js.map +1 -0
- package/bin/terminal/app.d.ts +13 -0
- package/bin/terminal/app.d.ts.map +1 -0
- package/bin/terminal/app.js +123 -0
- package/bin/terminal/app.js.map +1 -0
- package/bin/terminal/auth/admin.d.ts +8 -0
- package/bin/terminal/auth/admin.d.ts.map +1 -0
- package/bin/terminal/auth/admin.js +18 -0
- package/bin/terminal/auth/admin.js.map +1 -0
- package/bin/terminal/auth/mode-select.d.ts +11 -0
- package/bin/terminal/auth/mode-select.d.ts.map +1 -0
- package/bin/terminal/auth/mode-select.js +33 -0
- package/bin/terminal/auth/mode-select.js.map +1 -0
- package/bin/terminal/auth/server-switch.d.ts +22 -0
- package/bin/terminal/auth/server-switch.d.ts.map +1 -0
- package/bin/terminal/auth/server-switch.js +241 -0
- package/bin/terminal/auth/server-switch.js.map +1 -0
- package/bin/terminal/auth/user.d.ts +19 -0
- package/bin/terminal/auth/user.d.ts.map +1 -0
- package/bin/terminal/auth/user.js +261 -0
- package/bin/terminal/auth/user.js.map +1 -0
- package/bin/terminal/core/browser.d.ts +12 -0
- package/bin/terminal/core/browser.d.ts.map +1 -0
- package/bin/terminal/core/browser.js +29 -0
- package/bin/terminal/core/browser.js.map +1 -0
- package/bin/terminal/core/env.d.ts +15 -0
- package/bin/terminal/core/env.d.ts.map +1 -0
- package/bin/terminal/core/env.js +67 -0
- package/bin/terminal/core/env.js.map +1 -0
- package/bin/terminal/core/session.d.ts +97 -0
- package/bin/terminal/core/session.d.ts.map +1 -0
- package/bin/terminal/core/session.js +342 -0
- package/bin/terminal/core/session.js.map +1 -0
- package/bin/terminal/core/stripe.d.ts +26 -0
- package/bin/terminal/core/stripe.d.ts.map +1 -0
- package/bin/terminal/core/stripe.js +22 -0
- package/bin/terminal/core/stripe.js.map +1 -0
- package/bin/terminal/core/ui.d.ts +29 -0
- package/bin/terminal/core/ui.d.ts.map +1 -0
- package/bin/terminal/core/ui.js +60 -0
- package/bin/terminal/core/ui.js.map +1 -0
- package/bin/terminal/core/update.d.ts +20 -0
- package/bin/terminal/core/update.d.ts.map +1 -0
- package/bin/terminal/core/update.js +193 -0
- package/bin/terminal/core/update.js.map +1 -0
- package/bin/terminal/user/balance.d.ts +31 -0
- package/bin/terminal/user/balance.d.ts.map +1 -0
- package/bin/terminal/user/balance.js +131 -0
- package/bin/terminal/user/balance.js.map +1 -0
- package/bin/terminal/user/chat.d.ts +12 -0
- package/bin/terminal/user/chat.d.ts.map +1 -0
- package/bin/terminal/user/chat.js +70 -0
- package/bin/terminal/user/chat.js.map +1 -0
- package/bin/terminal/user/loop.d.ts +13 -0
- package/bin/terminal/user/loop.d.ts.map +1 -0
- package/bin/terminal/user/loop.js +93 -0
- package/bin/terminal/user/loop.js.map +1 -0
- package/bin/terminal/user/models.d.ts +10 -0
- package/bin/terminal/user/models.d.ts.map +1 -0
- package/bin/terminal/user/models.js +39 -0
- package/bin/terminal/user/models.js.map +1 -0
- package/bin/utils/storage.d.ts +0 -1
- package/bin/utils/storage.d.ts.map +1 -1
- package/bin/utils/storage.js +0 -6
- package/bin/utils/storage.js.map +1 -1
- package/package.json +7 -3
- package/public/app.js +3 -3
- package/src/cli/Index.ts +2 -0
- package/src/cli/agent/AgentChat.ts +113 -289
- package/src/cli/agent/AgentChatTypes.ts +8 -12
- package/src/cli/agent/AgentHistory.ts +2 -2
- package/src/cli/agent/AgentManager.ts +27 -28
- package/src/cli/agent/AgentManagerTypes.ts +2 -2
- package/src/cli/agent/AgentReset.ts +4 -4
- package/src/cli/agent/AgentSelection.ts +6 -6
- package/src/cli/agent/AgentSelectionTypes.ts +1 -1
- package/src/cli/agent/Init.ts +13 -13
- package/src/cli/agent/Restart.ts +2 -2
- package/src/cli/agent/Run.ts +38 -17
- package/src/cli/agent/Start.ts +2 -2
- package/src/cli/agent/Stop.ts +2 -2
- package/src/cli/control-plane/ControlPlaneProcess.ts +5 -5
- package/src/cli/model/ModelCreateCommand.ts +1 -1
- package/src/cli/model/ModelManageCommand.ts +5 -3
- package/src/cli/model/ModelManager.ts +3 -3
- package/src/cli/model/ModelSupport.ts +2 -10
- package/src/cli/shared/CliReporterTypes.ts +1 -1
- package/src/cli/shared/Config.ts +2 -2
- package/src/cli/shared/Env.ts +22 -230
- package/src/cli/shared/IndexAgentCommand.ts +3 -4
- package/src/cli/shared/IndexSupport.ts +16 -10
- package/src/cli/shared/ManagedPluginActionCommands.ts +4 -4
- package/src/cli/shared/ManagedPluginRemote.ts +4 -4
- package/src/cli/shared/PluginTargetSupport.ts +19 -19
- package/src/cli/shared/Plugins.ts +10 -10
- package/src/cli/shared/PublicHostEnv.ts +2 -2
- package/src/cli/shared/Terminal.ts +24 -0
- package/src/config/DowncitySchema.ts +3 -113
- package/src/config/Paths.ts +9 -90
- package/src/control/ControlGateway.ts +3 -3
- package/src/control/EnvApiRoutes.ts +7 -91
- package/src/control/PlatformApiRoutes.ts +6 -6
- package/src/control/gateway/AgentActions.ts +10 -10
- package/src/control/gateway/AgentCatalog.ts +17 -21
- package/src/control/instant/InstantSessionRunner.ts +3 -1
- package/src/env/ProcessEnv.ts +43 -0
- package/src/http/auth/AuthEnv.ts +1 -1
- package/src/model/runtime/CreateRuntimeModel.ts +54 -37
- package/src/model/service/ModelPoolService.ts +13 -11
- package/src/platform/store/StoreEnvRepository.ts +31 -234
- package/src/platform/store/StoreSchema.ts +3 -49
- package/src/platform/store/index.ts +11 -80
- package/src/platform/store/schema.ts +2 -2
- package/src/process/daemon/Api.ts +1 -1
- package/src/process/daemon/CliArgs.ts +24 -1
- package/src/process/daemon/Client.ts +90 -22
- package/src/process/daemon/Manager.ts +2 -1
- package/src/terminal/admin/auth-error.ts +62 -0
- package/src/terminal/admin/commands/accounts.ts +44 -0
- package/src/terminal/admin/commands/balance.ts +160 -0
- package/src/terminal/admin/commands/config.ts +13 -0
- package/src/terminal/admin/commands/custom.ts +46 -0
- package/src/terminal/admin/commands/instruction.ts +12 -0
- package/src/terminal/admin/commands/models.ts +64 -0
- package/src/terminal/admin/commands/payment.ts +94 -0
- package/src/terminal/admin/commands/products.ts +72 -0
- package/src/terminal/admin/commands/service-env.ts +256 -0
- package/src/terminal/admin/commands/usage.ts +44 -0
- package/src/terminal/admin/loop.ts +69 -0
- package/src/terminal/agent/pi-agent.ts +180 -0
- package/src/terminal/app.ts +120 -0
- package/src/terminal/auth/admin.ts +21 -0
- package/src/terminal/auth/mode-select.ts +38 -0
- package/src/terminal/auth/server-switch.ts +275 -0
- package/src/terminal/auth/user.ts +351 -0
- package/src/terminal/core/browser.ts +31 -0
- package/src/terminal/core/env.ts +71 -0
- package/src/terminal/core/session.ts +450 -0
- package/src/terminal/core/stripe.ts +37 -0
- package/src/terminal/core/ui.ts +84 -0
- package/src/terminal/core/update.ts +230 -0
- package/src/terminal/user/balance.ts +215 -0
- package/src/terminal/user/chat.ts +80 -0
- package/src/terminal/user/loop.ts +112 -0
- package/src/terminal/user/models.ts +43 -0
- package/src/utils/storage.ts +0 -7
- package/bin/process/rpc/Client.d.ts +0 -13
- package/bin/process/rpc/Client.d.ts.map +0 -1
- package/bin/process/rpc/Client.js +0 -98
- package/bin/process/rpc/Client.js.map +0 -1
- package/bin/process/rpc/Paths.d.ts +0 -14
- package/bin/process/rpc/Paths.d.ts.map +0 -1
- package/bin/process/rpc/Paths.js +0 -36
- package/bin/process/rpc/Paths.js.map +0 -1
- package/src/process/rpc/Client.ts +0 -113
- package/src/process/rpc/Paths.ts +0 -43
package/public/app.js
CHANGED
|
@@ -419,6 +419,6 @@ Error generating stack: `+s.message+`
|
|
|
419
419
|
animation-duration: 1ms;
|
|
420
420
|
}
|
|
421
421
|
}
|
|
422
|
-
`})}function gz(e){var s;if(e.zones.length===0)return e.activeZoneId;const n=(Math.max(0,e.zones.findIndex(r=>r.id===e.activeZoneId))+e.direction+e.zones.length)%e.zones.length;return((s=e.zones[n])==null?void 0:s.id)||e.activeZoneId}function mz(e){const{board:t,loading:n,selectedAgentId:s,onRefresh:r,onSelectAgent:a,className:i}=e,l=oz({board:t,selectedAgentId:s}),u=c.useRef(null),d=c.useRef(null),[f,g]=c.useState("clusters"),[m,h]=c.useState(!0),[x,y]=c.useState("cruise"),[w,b]=c.useState(!1),[p,v]=c.useState(null),S=c.useRef(l==null?void 0:l.id),[j,C]=c.useState(()=>l?Fs(l):"engaged");c.useEffect(()=>{if(!(l!=null&&l.id)){S.current=void 0;return}l.id!==S.current&&(S.current=l.id,C(Fs(l)))},[l]),c.useEffect(()=>{if(!p)return;const k=window.setTimeout(()=>v(null),620);return()=>window.clearTimeout(k)},[p]),c.useEffect(()=>{const k=()=>{b(document.fullscreenElement===u.current)};return document.addEventListener("fullscreenchange",k),()=>document.removeEventListener("fullscreenchange",k)},[]);const A=_l(j),M=c.useMemo(()=>((t==null?void 0:t.agents)||[]).filter(k=>Fs(k)===j),[j,t]),O=c.useMemo(()=>((t==null?void 0:t.agents)||[]).filter(k=>Fs(k)===j),[j,t]),P=c.useMemo(()=>t?MO({board:t,activeZoneId:j,selectedAgentId:l==null?void 0:l.id}):null,[j,t,l==null?void 0:l.id]),$=c.useMemo(()=>P?f==="clusters"?P.actors.map((k,D)=>{const B=P.corridors.find(Q=>Q.id===`corridor-${k.id}`);return{id:k.id,anchor:k.overviewAnchor,swayX:6+D%3*2.5,swayY:4+D%4*1.7,phase:D*.9,speed:.8+D%5*.08,mode:"route",route:(B==null?void 0:B.points)||k.overviewRoute,dwellRatio:B==null?void 0:B.dwellRatio,snapSize:B==null?void 0:B.snapSize}}):P.actors.filter(k=>k.zoneId===j&&k.focusedAnchor).map((k,D)=>{var Z;const B=P.patrols.find(te=>te.id===k.focusedRouteId),Q=k.focusedAnchor||{x:$t/2,y:Pt/2};return{id:k.id,anchor:Q,swayX:9+D%3*2.2,swayY:6+D%4*1.6,phase:D*.82,speed:.95+D%5*.1,mode:"route",route:(B==null?void 0:B.points)||((Z=P.patrols[D%Math.max(P.patrols.length,1)])==null?void 0:Z.points)||[Q],dwellRatio:B==null?void 0:B.dwellRatio,snapSize:B==null?void 0:B.snapSize}}):[],[j,P,f]),z=rz({nodes:$,flowMode:x}),N=iz({viewportRef:d,isFullscreen:w}),H=c.useCallback((k,D)=>{v(B=>({key:((B==null?void 0:B.key)||0)+1,label:k,mode:D}))},[]),R=c.useCallback(k=>{H(_l(k).title,"enter"),C(k),g("agents"),h(!0);const D=az({board:t,zoneId:k});D&&(a==null||a(D.id))},[t,a,H]),I=c.useCallback(k=>{const D=((t==null?void 0:t.agents)||[]).find(Q=>Q.id===k);if(!D)return;const B=Fs(D);(f==="clusters"||B!==j)&&H(_l(B).title,"enter"),C(B),g("agents"),h(!0),a==null||a(k)},[j,t,a,f,H]),T=c.useCallback(()=>{H("World Atlas","world"),g("clusters")},[H]),E=c.useCallback(k=>{if(P){if(k.key==="ArrowLeft"||k.key==="ArrowRight"){k.preventDefault();const D=gz({zones:P.zones,activeZoneId:j,direction:k.key==="ArrowRight"?1:-1});C(D);return}if(k.key==="Enter"&&f==="clusters"){k.preventDefault(),R(j);return}k.key==="Escape"&&f==="agents"&&(k.preventDefault(),T())}},[j,T,P,R,f]),q=c.useCallback(async()=>{const k=u.current;if(k){if(document.fullscreenElement===k){await document.exitFullscreen();return}document.fullscreenElement&&await document.exitFullscreen(),await k.requestFullscreen()}},[]);return!t||!P?o.jsx("div",{className:Pe("grid min-h-72 place-items-center border-2 border-dashed border-border/70 bg-[linear-gradient(145deg,rgba(247,244,236,0.84),rgba(255,255,255,0.95))] text-sm text-muted-foreground",i),style:{clipPath:xs},children:n?"正在生成 workboard game world...":"当前没有可展示的 workboard game world。"}):o.jsxs("section",{className:Pe("min-h-full",i),children:[o.jsx(fz,{}),o.jsxs("section",{ref:u,tabIndex:0,onKeyDown:E,className:Pe("relative overflow-hidden bg-[linear-gradient(145deg,rgba(236,232,218,0.96),rgba(255,252,247,0.98)_42%,rgba(217,231,224,0.76))] outline-none focus-visible:ring-2 focus-visible:ring-foreground/30",w?"h-[100dvh] rounded-none":"border-2 border-border/70 p-2 shadow-[0_8px_0_rgba(17,17,19,0.12)]"),style:w?void 0:{clipPath:xs},children:[o.jsx("div",{className:"pointer-events-none absolute inset-0 z-10 bg-[linear-gradient(rgba(17,17,19,0.04)_1px,transparent_1px),linear-gradient(90deg,rgba(17,17,19,0.04)_1px,transparent_1px)] bg-[size:18px_18px] opacity-40"}),o.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-10 h-16 bg-[linear-gradient(180deg,transparent,rgba(17,17,19,0.08),transparent)]",style:{animation:"workboard-world-scan 4.5s steps(6, end) infinite"}}),o.jsx(cz,{board:t,stageLevel:f,activeZone:A,selected:l,flowMode:x,loading:n,isFullscreen:w,zones:P.zones,onSelectZone:R,onBackToAtlas:T,onToggleFlowMode:()=>y(k=>k==="cruise"?"turbo":"cruise"),onRefresh:r,onToggleFullscreen:q}),o.jsxs("div",{ref:d,className:Pe("z-20 grid w-full place-items-center",w?"absolute inset-0 overflow-hidden":"relative overflow-auto border-2 border-border/70 bg-[linear-gradient(145deg,rgba(251,250,247,0.96),rgba(245,248,245,0.88))]"),style:w?void 0:{minHeight:720,clipPath:xs},children:[o.jsx(lz,{scale:N,children:f==="clusters"?o.jsx(hO,{board:t,gameMap:P,activeZoneId:j,selectedAgentId:l==null?void 0:l.id,flowMode:x,motionFrames:z,onSelectZone:R,onSelectAgent:k=>I(k)}):o.jsx(tz,{zone:A,items:M,gameMap:P,selectedAgentId:l==null?void 0:l.id,motionFrames:z,flowMode:x,onSelectAgent:I})}),o.jsx(dz,{portal:p}),o.jsx(vO,{selected:l,activeZone:A,selectedPeers:O,stageLevel:f,collapsed:m,onToggleCollapsed:()=>h(k=>!k),onSelectAgent:I})]})]})]})}const _g=768;function hz(){const[e,t]=c.useState(void 0);return c.useEffect(()=>{const n=window.matchMedia(`(max-width: ${_g-1}px)`),s=()=>{t(window.innerWidth<_g)};return n.addEventListener("change",s),t(window.innerWidth<_g),()=>n.removeEventListener("change",s)},[]),!!e}function Me(...e){return aw(pp(e))}const pz="sidebar_state",xz=60*60*24*7,bz="16rem",yz="18rem",vz="3rem",wz="b",Mj=c.createContext(null);function xx(){const e=c.useContext(Mj);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}function Sz({defaultOpen:e=!0,open:t,onOpenChange:n,className:s,style:r,children:a,...i}){const l=hz(),[u,d]=c.useState(!1),[f,g]=c.useState(e),m=t??f,h=c.useCallback(b=>{const p=typeof b=="function"?b(m):b;n?n(p):g(p),document.cookie=`${pz}=${p}; path=/; max-age=${xz}`},[n,m]),x=c.useCallback(()=>l?d(b=>!b):h(b=>!b),[l,h,d]);c.useEffect(()=>{const b=p=>{p.key===wz&&(p.metaKey||p.ctrlKey)&&(p.preventDefault(),x())};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[x]);const y=m?"expanded":"collapsed",w=c.useMemo(()=>({state:y,open:m,setOpen:h,isMobile:l,openMobile:u,setOpenMobile:d,toggleSidebar:x}),[y,m,h,l,u,d,x]);return o.jsx(Mj.Provider,{value:w,children:o.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":bz,"--sidebar-width-icon":vz,...r},className:Me("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",s),...i,children:a})})}function jz({side:e="left",variant:t="sidebar",collapsible:n="offcanvas",className:s,children:r,dir:a,...i}){const{isMobile:l,state:u,openMobile:d,setOpenMobile:f}=xx();return n==="none"?o.jsx("div",{"data-slot":"sidebar",className:Me("flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",s),...i,children:r}):l?o.jsx(b6,{open:d,onOpenChange:f,...i,children:o.jsxs(w6,{dir:a,"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"w-(--sidebar-width) bg-sidebar/98 p-0 text-sidebar-foreground backdrop-blur-sm [&>button]:hidden",style:{"--sidebar-width":yz},side:e,children:[o.jsxs(S6,{className:"sr-only",children:[o.jsx(j6,{children:"Sidebar"}),o.jsx(C6,{children:"Displays the mobile sidebar."})]}),o.jsx("div",{className:"flex h-full w-full flex-col",children:r})]})}):o.jsxs("div",{className:"group peer hidden text-sidebar-foreground md:block","data-state":u,"data-collapsible":u==="collapsed"?n:"","data-variant":t,"data-side":e,"data-slot":"sidebar",children:[o.jsx("div",{"data-slot":"sidebar-gap",className:Me("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",t==="floating"||t==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),o.jsx("div",{"data-slot":"sidebar-container","data-side":e,className:Me("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",t==="floating"||t==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",s),...i,children:o.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:"flex size-full flex-col rounded-[20px] bg-sidebar/98 shadow-[0_1px_0_rgba(17,17,19,0.02),0_8px_24px_rgba(17,17,19,0.02)] backdrop-blur-sm group-data-[variant=floating]:rounded-[20px]",children:r})})]})}function Cz({className:e,onClick:t,...n}){const{toggleSidebar:s}=xx();return o.jsxs(be,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon-sm",className:Me(e),onClick:r=>{t==null||t(r),s()},...n,children:[o.jsx(C5,{}),o.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function kz({className:e,...t}){return o.jsx("main",{"data-slot":"sidebar-inset",className:Me("relative flex w-full flex-1 flex-col bg-secondary/70 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-[24px] md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",e),...t})}function Nz({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:Me("flex flex-col gap-2 p-2",e),...t})}function Tz({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-footer","data-sidebar":"footer",className:Me("flex flex-col gap-2 p-2",e),...t})}function Az({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:Me("no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t})}function ll({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-group","data-sidebar":"group",className:Me("relative flex w-full min-w-0 flex-col p-2",e),...t})}function cl({className:e,render:t,...n}){return Cp({defaultTagName:"div",props:zr({className:Me("flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",e)},n),render:t,state:{slot:"sidebar-group-label",sidebar:"group-label"}})}function ul({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-group-content","data-sidebar":"group-content",className:Me("w-full text-sm",e),...t})}function Ia({className:e,...t}){return o.jsx("ul",{"data-slot":"sidebar-menu","data-sidebar":"menu",className:Me("flex w-full min-w-0 flex-col gap-0",e),...t})}function Us({className:e,...t}){return o.jsx("li",{"data-slot":"sidebar-menu-item","data-sidebar":"menu-item",className:Me("group/menu-item relative",e),...t})}const Ez=rf("peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:p-0!"}},defaultVariants:{variant:"default",size:"default"}});function mr({render:e,isActive:t=!1,variant:n="default",size:s="default",tooltip:r,className:a,...i}){const{isMobile:l,state:u}=xx(),d=Cp({defaultTagName:"button",props:zr({className:Me(Ez({variant:n,size:s}),a)},i),render:r?o.jsx(Wr,{render:e}):e,state:{slot:"sidebar-menu-button",sidebar:"menu-button",size:s,active:t}});return r?(typeof r=="string"&&(r={children:r}),o.jsxs(Qr,{children:[d,o.jsx(eo,{side:"right",align:"center",hidden:u!=="collapsed"||l,...r})]})):d}function bx(e){const t=String(e||"").trim().toLowerCase();return t==="telegram"?"Telegram":t==="feishu"?"Feishu":t==="qq"?"QQ (dev)":t==="consoleui"?"Console UI":t||"-"}const Mz=new Set(["telegram","qq","feishu","consoleui"]);function Rj(e){return String(e||"").trim().toLowerCase()}function f0(e){const t=Rj(e);return t?t.startsWith("api:")?"api":t.startsWith("consoleui-")||t==="local_ui"?"consoleui":"other":"other"}function ma(e){if(typeof e=="string")return f0(e);const t=Rj(e.channel);return Mz.has(t)?t:t==="api"?"api":t&&t!=="other"?t:f0(e.sessionId)}function Oj(e){const t=ma(e);return t==="api"?"api":t==="other"?"other":"chat"}function Rz(e){return[...e].sort((t,n)=>{const s=Number(t.updatedAt||0),r=Number(n.updatedAt||0);return s!==r?r-s:t.sessionId.localeCompare(n.sessionId)})}function zj(e){const t=Rz(e),n={chat:[],api:[],other:[]};for(const r of t){const a=Oj(r);n[a].push(r)}return[{key:"chat",title:"chat:*",items:n.chat},{key:"api",title:"api:*",items:n.api},{key:"other",title:"other",items:n.other}].filter(r=>r.items.length>0)}function Oz(e,t){const n=String(t||"").trim().toLowerCase();return n?e.filter(s=>{const r=String(s.sessionId||"").toLowerCase(),a=String(s.chatId||"").toLowerCase(),i=String(s.chatTitle||"").toLowerCase(),l=String(s.lastRole||"").toLowerCase(),u=String(s.lastText||"").toLowerCase();return r.includes(n)||a.includes(n)||i.includes(n)||l.includes(n)||u.includes(n)}):e}const yx={globalOverview:{view:"globalOverview",scope:"global",title:"Overview",path:"/global/overview"},globalWorkboard:{view:"globalWorkboard",scope:"global",title:"Workboard",path:"/global/workboard"},globalApiKeys:{view:"globalApiKeys",scope:"global",title:"API Keys",path:"/global/api-keys"},globalEnv:{view:"globalEnv",scope:"global",title:"Env",path:"/global/env"},globalModel:{view:"globalModel",scope:"global",title:"Model",path:"/global/model"},globalChannelAccounts:{view:"globalChannelAccounts",scope:"global",title:"Channel Accounts",path:"/global/channel-accounts"},globalCommand:{view:"globalCommand",scope:"global",title:"Command",path:"/global/command"},globalAgents:{view:"globalAgents",scope:"global",title:"Agents",path:"/global/agents"},globalPlugins:{view:"globalPlugins",scope:"global",title:"Plugins",path:"/global/plugins"},agentOverview:{view:"agentOverview",scope:"agent",title:"Overview",path:"/agent/overview"},agentAuthorization:{view:"agentAuthorization",scope:"agent",title:"Authorization",path:"/agent/authorization"},agentPlugins:{view:"agentPlugins",scope:"agent",title:"Plugins",path:"/agent/plugins"},agentSkills:{view:"agentSkills",scope:"agent",title:"Skills",path:"/agent/skills"},agentServices:{view:"agentServices",scope:"agent",title:"Services",path:"/agent/services"},agentCommand:{view:"agentCommand",scope:"agent",title:"Command",path:"/agent/command"},agentTasks:{view:"agentTasks",scope:"agent",title:"Tasks",path:"/agent/tasks"},agentLogs:{view:"agentLogs",scope:"agent",title:"Logs",path:"/agent/logs"},contextOverview:{view:"contextOverview",scope:"context",title:"Overview",path:"/context/overview"}},zz={global:"Global",agent:"Agent",context:"Session"},Ij=["globalOverview","globalWorkboard","globalApiKeys","globalCommand","globalEnv","globalModel","globalChannelAccounts","globalAgents","globalPlugins","agentOverview","agentAuthorization","agentPlugins","agentSkills","agentServices","agentCommand","agentTasks","agentLogs","contextOverview"];function g0(e){return Ij.map(t=>yx[t]).filter(t=>t.scope===e)}function Iz(e){if(e==="contextWorkspace")return"Session / Workspace";const t=yx[e];return`${zz[t.scope]} / ${t.title}`}function Dz(){return Ij.reduce((e,t)=>(e[t]=yx[t].path,e),{})}const m0={globalOverview:o.jsx(Xc,{}),globalWorkboard:o.jsx(Gm,{}),globalApiKeys:o.jsx(qm,{}),globalEnv:o.jsx(qm,{}),globalModel:o.jsx(py,{}),globalChannelAccounts:o.jsx(zp,{}),globalCommand:o.jsx(Vm,{}),globalAgents:o.jsx(Xc,{}),globalPlugins:o.jsx(hy,{}),agentOverview:o.jsx(Xc,{}),agentAuthorization:o.jsx(Tw,{}),agentPlugins:o.jsx(hy,{}),agentSkills:o.jsx(Aw,{}),agentServices:o.jsx(py,{}),agentCommand:o.jsx(Vm,{}),agentTasks:o.jsx(Gm,{}),agentLogs:o.jsx(B5,{}),contextOverview:o.jsx(Xc,{})};function _z(e,t){if(!e)return t;if(e.running===!0)return!0;if(e.running===!1)return!1;if(e.enabled===!0)return!0;if(e.enabled===!1)return!1;const n=String(e.linkState||"").trim().toLowerCase();return["connected","disconnected","error"].includes(n)?!0:t}function Lz(e){return e.running===!0?!0:String(e.status||"").trim().toLowerCase()==="running"}function h0(e){return e.active?o.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center text-sidebar-foreground/60","aria-label":e.label,title:e.label,children:o.jsx(nt,{className:"size-3 animate-spin"})}):o.jsx("span",{"aria-hidden":"true",className:"inline-flex h-4 w-4 shrink-0"})}function Bz({activeView:e,agents:t,selectedAgentId:n,routePathname:s,routeAgentId:r,sessions:a,selectedSessionId:i,tasks:l,selectedTaskTitle:u,selectedChatChannel:d,chatChannels:f,onViewChange:g,onAgentChange:m,onAgentEnter:h,onSessionOpen:x,onTaskOpen:y,onChannelOpen:w,topbarStatus:b,topbarError:p,loading:v,onRefresh:S,...j}){var ge;const C=zj(a),A=c.useMemo(()=>C.find(U=>U.key==="chat")??null,[C]),M=c.useMemo(()=>C.filter(U=>U.key!=="chat"),[C]),O=c.useMemo(()=>[...(A==null?void 0:A.items)||[],...M.flatMap(U=>U.items)],[A,M]),P=c.useMemo(()=>{const U={},ce=Se=>{const Fe=String(Se||"").trim().toLowerCase();Fe&&(U[Fe]||(U[Fe]=[]))};for(const Se of O){const Fe=ma(Se);ce(Fe),U[Fe].push(Se)}for(const Se of f)ce(String(Se.channel||""));const F=["telegram","qq","feishu","consoleui","other"],K=F.filter(Se=>Object.prototype.hasOwnProperty.call(U,Se)),he=Object.keys(U).filter(Se=>!F.includes(Se)).sort((Se,Fe)=>Se.localeCompare(Fe));return[...K,...he].map(Se=>({channel:Se,items:U[Se]||[]}))},[f,O]),$=c.useMemo(()=>g0("global"),[]),z=c.useMemo(()=>$.filter(U=>U.view!=="globalAgents"),[$]),N=c.useMemo(()=>g0("agent"),[]),R=["globalOverview","globalWorkboard","globalApiKeys","globalCommand","globalEnv","globalModel","globalChannelAccounts","globalAgents","globalPlugins"].includes(e)?"agent-list":"agent-detail",[I,T]=c.useState("forward"),[E,q]=c.useState(""),[k,D]=c.useState({}),B=c.useRef(R),Q=c.useMemo(()=>{if(e!=="globalOverview")return!1;const U=s.split("/").filter(Boolean);return U.length>=3&&U[0]==="global"&&U[1]==="agent"},[e,s]),Z=c.useMemo(()=>{const U=s.split("/").filter(Boolean);return U.length>=2&&U[0]==="global"&&U[1]==="overview"},[s]),te=t.find(U=>U.id===n)??null,ie="rounded-[12px] text-sidebar-foreground/82 hover:bg-sidebar-accent hover:text-sidebar-foreground data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-foreground h-9 px-2.5 text-[13px]",oe="h-9 px-2.5 opacity-60 data-[slot=sidebar-menu-button]:cursor-default",pe="grid w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)_1.5rem] items-center gap-2",_="relative py-0.5",Y="absolute inset-y-0 left-1 z-10 my-auto h-6 w-6 rounded-[10px] text-sidebar-foreground/60 transition-colors hover:bg-sidebar-accent hover:text-sidebar-foreground active:translate-y-0",le=Me(ie,"h-8 w-full rounded-[12px] px-2.5 pl-8 text-[11px] font-medium uppercase tracking-[0.08em]","data-[active=true]:bg-sidebar-accent/75","hover:bg-sidebar-accent/35"),ne="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2",ue="inline-flex h-2 w-2 rounded-full",ae="min-w-0 overflow-hidden transition-[max-height,opacity] duration-200 ease-out",xe="min-w-0 pl-4",ee="min-w-0 gap-0 pl-1.5",W=Me(ie,"h-7 w-full min-w-0 rounded-[12px] px-2 text-[10px]","data-[active=true]:bg-sidebar-accent/75","hover:bg-sidebar-accent/45"),X="grid w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)_1rem] items-center gap-1.5",G="inline-flex size-4 items-center justify-center text-muted-foreground",L="min-w-0 truncate text-[10px] font-medium",J=String(d||"").trim().toLowerCase(),me=c.useMemo(()=>{const U=new Map;for(const ce of f){const F=String(ce.channel||"").trim().toLowerCase();F&&U.set(F,ce)}return U},[f]);return c.useEffect(()=>{B.current!==R&&(T(R==="agent-detail"?"forward":"back"),B.current=R)},[R]),c.useEffect(()=>{D({})},[n]),o.jsxs(jz,{collapsible:"offcanvas",className:"bg-transparent",...j,children:[o.jsx(Nz,{children:o.jsx("div",{className:"px-3 pb-2 pt-3",children:o.jsxs("div",{className:"flex h-9 max-w-full items-center gap-2 text-sidebar-foreground",children:[o.jsx(be,{size:"sm",variant:"ghost",className:Me("h-8 w-8 rounded-[11px] p-0 text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground","opacity-100"),onClick:()=>{R==="agent-detail"&&g("globalOverview")},"aria-label":R==="agent-detail"?"返回":"DOWNCITY",title:R==="agent-detail"?"返回":"DOWNCITY",children:R==="agent-detail"?o.jsx(Cw,{className:"size-4"}):o.jsx("img",{src:"/image.png",alt:"DOWNCITY",className:"size-4 shrink-0 object-cover"})}),o.jsx("span",{className:Me("inline-flex items-center gap-1.5 truncate","text-[0.92rem] font-medium tracking-[-0.03em]"),children:o.jsx("span",{children:R==="agent-detail"?(te==null?void 0:te.name)||"Agent":"DOWNCITY"})}),o.jsx("div",{className:"ml-auto",children:o.jsx(be,{type:"button",variant:"ghost",size:"icon",className:Me("size-8 rounded-[11px]",p?"text-destructive hover:bg-destructive/10":"text-sidebar-foreground/60 hover:bg-sidebar-accent hover:text-sidebar-foreground"),onClick:S,disabled:v,"aria-label":v?"刷新中":"刷新",title:b,children:o.jsx(xc,{className:Me("size-4",v&&"animate-spin")})})})]})})}),o.jsx(Az,{className:"relative gap-1.5 overflow-hidden",children:o.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:[o.jsxs("div",{className:Me("absolute inset-0 overflow-y-auto transition-all duration-200 ease-out",R==="agent-list"?"translate-x-0 opacity-100":I==="forward"?"-translate-x-6 opacity-0":"translate-x-6 opacity-0",R==="agent-list"?"pointer-events-auto":"pointer-events-none"),children:[o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Console"}),o.jsx(ul,{children:o.jsx(Ia,{children:z.map(U=>o.jsx(Us,{children:o.jsx(mr,{tooltip:U.title,isActive:U.view==="globalOverview"?e==="globalOverview"&&Z:e===U.view,onClick:()=>g(U.view),className:ie,children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:m0[U.view]}),o.jsx("span",{className:"truncate",children:U.title}),o.jsx("span",{})]})})},U.view))})})]}),o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Agents"}),o.jsx(ul,{children:o.jsxs(Ia,{children:[t.length===0?o.jsx(Us,{children:o.jsx(mr,{render:o.jsx("button",{type:"button",disabled:!0}),className:oe,children:o.jsx("span",{className:"text-xs text-muted-foreground",children:"无运行中的 agent"})})}):null,t.map(U=>{const ce=Q&&U.id===r,F=U.running===!0;return o.jsx(Us,{children:o.jsx(mr,{tooltip:U.id,isActive:ce,onMouseEnter:()=>q(U.id),onMouseLeave:()=>q(K=>K===U.id?"":K),onClick:()=>m(U.id),onDoubleClick:()=>h(U.id),className:Me(ie,!F&&"opacity-55"),children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(zp,{className:"size-4 shrink-0"})}),o.jsx("span",{className:"min-w-0",children:o.jsx("span",{className:"truncate",children:U.name||"unknown-agent"})}),F?o.jsxs("span",{className:"relative inline-flex h-6 w-6 items-center justify-center",children:[o.jsx("span",{className:Me("inline-flex h-2 w-2 shrink-0 rounded-full bg-emerald-500",E===U.id?"opacity-0":"opacity-100")}),o.jsx("span",{role:"button",tabIndex:0,className:Me("absolute inset-0 inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-[10px] p-0 text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground",E===U.id?"opacity-100":"pointer-events-none opacity-0"),"aria-label":"进入 Agent",title:"进入 Agent",onClick:K=>{K.stopPropagation(),h(U.id)},onKeyDown:K=>{K.key!=="Enter"&&K.key!==" "||(K.preventDefault(),K.stopPropagation(),h(U.id))},children:o.jsx(Fm,{className:"size-4"})})]}):o.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 justify-self-center rounded-full bg-muted-foreground/60"})]})})},U.id)})]})})]})]}),o.jsxs("div",{className:Me("absolute inset-0 overflow-y-auto transition-all duration-200 ease-out",R==="agent-detail"?"translate-x-0 opacity-100":I==="forward"?"translate-x-6 opacity-0":"-translate-x-6 opacity-0",R==="agent-detail"?"pointer-events-auto":"pointer-events-none"),children:[o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Agent"}),o.jsx(ul,{children:o.jsx(Ia,{children:N.filter(U=>U.view!=="agentTasks"&&U.view!=="agentServices"&&U.view!=="agentCommand").map(U=>o.jsx(Us,{children:o.jsx(mr,{tooltip:U.title,isActive:e===U.view,onClick:()=>g(U.view),className:ie,children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:m0[U.view]}),o.jsx("span",{className:"truncate",children:U.title}),o.jsx("span",{})]})})},U.view))})})]}),o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Chat"}),o.jsx(ul,{children:o.jsxs(Ia,{children:[O.length===0?o.jsx(Us,{children:o.jsx(mr,{render:o.jsx("button",{type:"button",disabled:!0}),className:oe,children:o.jsx("span",{className:"text-xs text-muted-foreground",children:"暂无聊天会话"})})}):null,P.map(U=>{const ce=me.get(U.channel),F=_z(ce,U.items.length>0),K=F&&U.items.length>0,he=K?!!k[U.channel]:!0,Te=String((ce==null?void 0:ce.linkState)||(ce==null?void 0:ce.statusText)||(U.channel==="consoleui"?"connected":"unknown")).trim().toLowerCase(),Se=F?Te==="connected"?"bg-emerald-500":Te==="disconnected"||Te==="error"||Te==="failed"?"bg-destructive":"bg-muted-foreground/60":"bg-muted-foreground/45",Fe=e==="contextOverview"&&J===U.channel;return o.jsxs(c.Fragment,{children:[o.jsxs(Us,{className:_,children:[o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Me(Y,!K&&"cursor-default opacity-35 hover:bg-transparent hover:text-sidebar-foreground/60"),disabled:!K,onClick:Ae=>{Ae.preventDefault(),Ae.stopPropagation(),K&&D(Re=>({...Re,[U.channel]:!Re[U.channel]}))},"aria-label":`${he?"展开":"收起"} ${U.channel}`,title:`${he?"展开":"收起"} ${U.channel}`,children:o.jsx(Fm,{className:Me("size-3.5 shrink-0 transform-gpu transition-transform duration-200 ease-out",he?"rotate-0":"rotate-90")})}),o.jsx(mr,{tooltip:`${U.channel} · ${Te}`,isActive:Fe,className:Me(le,!F&&"text-muted-foreground/55 hover:bg-sidebar-accent/20 hover:text-muted-foreground/70"),onClick:()=>{w(U.channel)},children:o.jsxs("span",{className:ne,children:[o.jsx("span",{className:"truncate",children:bx(U.channel)}),o.jsx("span",{className:Me(ue,Se),"aria-label":`link state: ${Te}`,title:Te})]})})]}),o.jsx(Us,{className:Me(ae,he?"pointer-events-none max-h-0 opacity-0":"max-h-[28rem] opacity-100"),children:o.jsx("div",{className:xe,children:o.jsx(Ia,{className:ee,children:U.items.map(Ae=>{const Re=String(Ae.sessionId||"").trim();if(!Re)return null;const Ye=String(Ae.chatTitle||"").trim(),yt=String(Ae.chatId||"").trim(),De=Ye&&(!yt||Ye!==yt)?Ye:"",ot=De||yt||Re,_e=e==="contextWorkspace"&&i===Re,Je=Ae.executing===!0;return o.jsx(Us,{className:"min-w-0",children:o.jsx(mr,{tooltip:De?`${De} · ${Re}`:Re,isActive:_e,onClick:()=>x(Re),className:W,children:o.jsxs("span",{className:X,children:[o.jsx("span",{className:G,children:o.jsx(b5,{className:"h-2.5 w-2.5"})}),o.jsx("span",{className:L,children:ot}),o.jsx(h0,{active:Je,label:"会话执行中"})]})})},Re)})})})})]},`chat-group:${U.channel}`)})]})})]}),o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Tasks"}),o.jsx(ul,{children:o.jsxs(Ia,{children:[l.length===0?o.jsx(Us,{children:o.jsx(mr,{render:o.jsx("button",{type:"button",disabled:!0}),className:oe,children:o.jsx("span",{className:"text-xs text-muted-foreground",children:"暂无任务"})})}):null,l.map(U=>{const ce=String(U.title||"").trim();if(!ce)return null;const F=Lz(U);return o.jsx(Us,{children:o.jsx(mr,{tooltip:ce,isActive:e==="agentTasks"&&u===ce,onClick:()=>y(ce),className:ie,children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(Gm,{className:"size-4"})}),o.jsx("span",{className:"truncate",children:ce}),o.jsx(h0,{active:F,label:"任务执行中"})]})})},`task:${ce}`)})]})})]})]})]})}),o.jsx(Tz,{className:"px-3 pb-3 pt-1",children:o.jsxs(yj,{children:[o.jsxs(vj,{render:o.jsx("button",{type:"button",className:Me(ie,"flex w-full items-center justify-start gap-2 text-sidebar-foreground/82")}),children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(Z5,{className:"size-4"})}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:((ge=j.user)==null?void 0:ge.username)||"admin"}),o.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 rounded-full bg-emerald-500"})]}),o.jsx(wj,{side:"top",align:"start",className:"w-48 p-1.5",children:o.jsx("div",{className:"space-y-0.5",children:o.jsxs("button",{type:"button",onClick:j.onLogout,className:"flex w-full items-center gap-2 rounded-[10px] px-2.5 py-2 text-[13px] text-sidebar-foreground/82 hover:bg-sidebar-accent hover:text-sidebar-foreground transition-colors",children:[o.jsx(m5,{className:"size-4"}),o.jsx("span",{children:"清除 Token"})]})})})]})})]})}function wt(e){const{title:t,description:n,actions:s,children:r,className:a,bodyClassName:i}=e;return o.jsxs("section",{className:Me("space-y-3 rounded-[22px] bg-background px-4 py-4 shadow-[0_1px_0_rgba(17,17,19,0.03)] ring-1 ring-border/70",a),children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("div",{className:"min-w-0",children:o.jsx("div",{className:"flex h-8 items-center text-xs uppercase tracking-[0.12em] text-muted-foreground",children:t})}),s?o.jsx("div",{className:Me("flex shrink-0 items-center gap-2","[&_[data-slot=button]]:h-8","[&_[data-slot=input]]:h-8","[&_[data-slot=badge]]:h-8","[&_[data-slot=button]]:rounded-[11px]","[&_[data-slot=input]]:rounded-[11px]","[&_[data-slot=badge]]:rounded-[999px]"),children:s}):null]}),o.jsx("div",{className:Me("space-y-3",i),children:r})]})}function Pz(e){const{tokens:t,loading:n,onCreateToken:s,onDeleteToken:r,onClearLatestIssuedToken:a,latestIssuedToken:i,formatTime:l}=e,[u,d]=c.useState(!1),[f,g]=c.useState(""),[m,h]=c.useState(!1),[x,y]=c.useState(""),[w,b]=c.useState(!1),p=c.useMemo(()=>t.length,[t]),v=c.useCallback(async()=>{if(f.trim())try{h(!0),await s({name:f.trim()}),g("")}finally{h(!1)}},[s,f]),S=c.useCallback(async C=>{try{y(C),await r({tokenId:C})}finally{y("")}},[r]);c.useEffect(()=>{i&&(d(!0),b(!1))},[i]);const j=c.useCallback(async()=>{if(i!=null&&i.token)try{await navigator.clipboard.writeText(i.token),b(!0),setTimeout(()=>b(!1),2e3)}catch{}},[i]);return o.jsxs(o.Fragment,{children:[o.jsx(wt,{title:"API Keys",description:`${t.length} total · ${p} active`,actions:o.jsxs(be,{type:"button",size:"sm",className:"h-8 rounded-[11px]",onClick:()=>d(!0),disabled:n,children:[o.jsx(fa,{className:"mr-1 size-4"}),"新建"]}),children:t.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary py-6 text-center text-sm text-muted-foreground",children:"暂无 API Key"}):o.jsx("div",{className:"space-y-1",children:t.map(C=>o.jsxs("div",{className:"group flex items-center gap-3 rounded-[12px] px-3 py-2.5 hover:bg-secondary",children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(qm,{className:"size-3.5"})}),o.jsx("span",{className:"truncate text-sm",children:C.name}),o.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:l(C.createdAt)}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"size-8 rounded-[10px] text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(C.id),disabled:x===C.id,children:x===C.id?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(er,{className:"size-4"})})]},C.id))})}),o.jsx($n,{open:u,onOpenChange:d,children:o.jsxs(Un,{className:"w-[min(92vw,400px)]",children:[o.jsx(Hn,{children:o.jsx(Fn,{children:i?"API Key 已创建":"新建 API Key"})}),i?o.jsxs("div",{className:"space-y-4 px-4 py-2",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"请保存此 API Key,它只会显示一次"}),o.jsxs("div",{className:"relative",children:[o.jsx("code",{className:"block break-all rounded-[12px] bg-secondary px-3 py-3 pr-10 text-xs",children:i.token}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"absolute right-1 top-1/2 size-7 -translate-y-1/2 rounded-[8px]",onClick:j,children:w?o.jsx(Ws,{className:"size-4 text-emerald-500"}):o.jsx(t5,{className:"size-4"})})]})]}):o.jsx("div",{className:"space-y-4 px-4 py-2",children:o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{className:"text-xs",children:"名称"}),o.jsx(lt,{value:f,onChange:C=>g(C.target.value),placeholder:"API Key 名称",onKeyDown:C=>C.key==="Enter"&&v(),autoFocus:!0})]})}),o.jsx(rs,{className:"gap-2",children:i?o.jsx(be,{size:"sm",onClick:()=>{a(),d(!1)},children:"完成"}):o.jsxs(o.Fragment,{children:[o.jsx(be,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"取消"}),o.jsxs(be,{size:"sm",disabled:!f.trim()||m,onClick:()=>void v(),children:[m&&o.jsx(nt,{className:"mr-2 size-4 animate-spin"}),"创建"]})]})})]})})]})}function lu(e){return o.jsx("div",{className:"min-w-0 truncate text-sm text-foreground",title:e.value,children:e.value||"-"})}function $z(e){if(e.executionMode==="api"||!e.executionMode)return{executionType:"api",agentType:"kimi"};if(e.executionMode==="local")return{executionType:"local",agentType:"kimi"};const t=String(e.agentType||"").trim();return t==="claude"||t==="codex"?{executionType:"acp",agentType:t}:{executionType:"acp",agentType:"kimi"}}function Uz(e){return e.executionMode==="api"?String(e.modelId||"").trim()||"-":e.executionMode==="local"?`local ${String(e.localModel||"-").trim()||"-"}`:`acp ${String(e.agentType||"-").trim()||"-"}`}function Hz(e,t){const n=new Set,s=String(t||"").trim();s&&n.add(s);for(const r of e){const a=String(r||"").trim();a&&n.add(a)}return Array.from(n)}function Fz(e){var z;const{agent:t,model:n,onStart:s,onLoadLocalModels:r,onUpdateExecution:a}=e,[i,l]=c.useState(!1);if(!t)return o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"未选择 Agent"});const u=Uz(t),d=Array.isArray(n==null?void 0:n.availableModels)?n.availableModels:[],f=String((n==null?void 0:n.agentPrimaryModelId)||(n==null?void 0:n.primaryModelId)||t.modelId||"").trim(),g=String(((z=d[0])==null?void 0:z.id)||"").trim(),m=f||g,h=String(t.localModel||"").trim(),x=$z({executionMode:t.executionMode,agentType:t.agentType}),[y,w]=c.useState(x.executionType),[b,p]=c.useState(x.agentType),[v,S]=c.useState(h),[j,C]=c.useState([]),[A,M]=c.useState(!1),O=String(t.projectRoot||t.id||"").trim()||"-",P=t.stoppedAt?new Date(t.stoppedAt).toLocaleString("zh-CN",{hour12:!1}):"-";c.useEffect(()=>{w(x.executionType),p(x.agentType)},[x]),c.useEffect(()=>{S(h)},[h]),c.useEffect(()=>{let N=!1;return(async()=>{try{M(!0);const H=await r(t.projectRoot||t.id);if(N)return;C(H)}finally{N||M(!1)}})(),()=>{N=!0}},[t.id,t.projectRoot,r]);const $=c.useMemo(()=>Hz(j,v||h),[h,j,v]);return o.jsxs("section",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 px-1 py-1",children:[o.jsx("div",{className:"min-w-0",children:o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("img",{src:"/image.png",alt:"bot",className:"mt-0.5 size-8 shrink-0 rounded-[4px] object-cover"}),o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx("div",{className:"truncate text-xl font-semibold leading-none text-foreground/74",children:t.name||"Unknown Agent"}),o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:O})]})]})}),o.jsx(be,{size:"icon-sm",variant:"secondary",disabled:i,title:i?"启动中":"启动","aria-label":i?"启动中":"启动",onClick:async()=>{try{l(!0),await Promise.resolve(s(t.id))}finally{l(!1)}},children:i?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(sa,{className:"size-4"})})]}),o.jsxs("section",{className:"rounded-[18px] bg-secondary/72 px-3.5 py-3 space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium w-full"}),children:o.jsx("span",{className:"truncate",children:y==="api"?"API":y==="local"?"Local":"ACP"})}),o.jsxs(wn,{className:"max-h-72 min-w-[18rem]",children:[o.jsx(bt,{onClick:()=>{w("api"),m&&(x.executionType==="api"&&m===f||a({executionMode:"api",modelId:m}))},children:"API"}),o.jsx(bt,{onClick:()=>{w("local");const N=String(v||h||$[0]||"").trim();N&&(x.executionType==="local"&&N===h||a({executionMode:"local",localModel:N}))},children:"Local"}),o.jsx(bt,{onClick:()=>{w("acp");const N=b||x.agentType||"kimi";x.executionType==="acp"&&x.agentType===N||a({executionMode:"acp",agentType:N})},children:"ACP"})]})]}),y==="api"?o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium w-full"}),children:o.jsx("span",{className:"truncate",children:m||"选择 execution.modelId"})}),o.jsx(wn,{className:"max-h-72 min-w-[18rem]",children:d.length===0?o.jsx(bt,{disabled:!0,children:"无可选模型"}):d.map(N=>{const H=String(N.id||"").trim();return H?o.jsx(bt,{onClick:()=>{H===f&&x.executionType==="api"||a({executionMode:"api",modelId:H})},children:`${H} · ${N.providerType||"-"}${N.isPaused?" · paused":""}`},H):null})})]}):y==="local"?o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("select",{value:v,className:"flex h-9 flex-1 rounded-[12px] border border-input bg-background px-3 font-mono text-[12px] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",onChange:N=>S(N.target.value),disabled:A||$.length===0,children:[$.length===0?o.jsx("option",{value:"",children:A?"正在读取本地模型":"没有发现本地 GGUF 模型"}):null,$.map(N=>o.jsx("option",{value:N,children:N},N))]}),o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 rounded-[12px] bg-background px-3 text-xs",disabled:!String(v||"").trim()||A,onClick:()=>{const N=String(v||"").trim();N&&(x.executionType==="local"&&N===h||a({executionMode:"local",localModel:N}))},children:"应用"})]}):y==="acp"?o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium w-full"}),children:o.jsx("span",{className:"truncate",children:`ACP · ${b}`})}),o.jsx(wn,{className:"max-h-72 min-w-[18rem]",children:["kimi","claude","codex"].map(N=>o.jsx(bt,{onClick:()=>{p(N),!(x.executionType==="acp"&&x.agentType===N)&&a({executionMode:"acp",agentType:N})},children:`ACP · ${N}`},N))})]}):o.jsx("div",{className:"text-xs text-muted-foreground",children:u})]}),o.jsxs("div",{className:"space-y-1 text-sm",children:[o.jsx(lu,{value:O}),o.jsx(lu,{value:String(t.host||"-")}),o.jsx(lu,{value:t.port?String(t.port):"-"}),o.jsx(lu,{value:P})]}),o.jsxs("div",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[o.jsx("span",{className:"size-1.5 rounded-full bg-muted-foreground/45"}),o.jsx("span",{children:"stopped"})]})]})]})}const Dj=c.createContext(null),Da={confirmText:"确认",cancelText:"取消",confirmVariant:"default"};function qz(e){const{children:t}=e,[n,s]=c.useState(null),r=c.useCallback(h=>{s(x=>x&&(x.resolve(h),null))},[]);c.useEffect(()=>()=>{s(h=>(h&&h.resolve(!1),null))},[]);const a=c.useCallback(h=>{const x=String(h.title||"").trim(),y={...h,title:x||"请确认操作",confirmText:String(h.confirmText||"").trim()||Da.confirmText,cancelText:String(h.cancelText||"").trim()||Da.cancelText,confirmVariant:h.confirmVariant||Da.confirmVariant};return new Promise(w=>{s(b=>(b&&b.resolve(!1),{options:y,resolve:w}))})},[]),i=c.useMemo(()=>({confirm:a}),[a]),l=n==null?void 0:n.options,u=!!n,d=String((l==null?void 0:l.confirmText)||Da.confirmText),f=String((l==null?void 0:l.cancelText)||Da.cancelText),g=(l==null?void 0:l.confirmVariant)||Da.confirmVariant,m=String((l==null?void 0:l.description)||"").trim();return o.jsxs(Dj.Provider,{value:i,children:[t,o.jsx($n,{open:u,onOpenChange:h=>{h||r(!1)},children:o.jsxs(Un,{showCloseButton:!1,className:"w-[min(92vw,30rem)] p-0",children:[o.jsxs(Hn,{className:"px-4 py-4",children:[o.jsx(Fn,{children:(l==null?void 0:l.title)||"请确认操作"}),m?o.jsx(os,{children:m}):null]}),o.jsxs(rs,{className:"bg-secondary px-4 py-3",children:[o.jsx(be,{type:"button",variant:"outline",onClick:()=>{r(!1)},children:f}),o.jsx(be,{type:"button",variant:g,onClick:()=>{r(!0)},children:d})]})]})})]})}function Ls(){const e=c.useContext(Dj);if(!e)throw new Error("useConfirmDialog must be used within <ConfirmDialogProvider>.");return e.confirm}const p0="role",_j=new Set(["default"]),x0=["default","member","admin"];function Mt(e){return String(e||"").trim()}function Lj(e){return Mt(e).toLowerCase().replace(/\s+/g,"-")}function vx(e){const t=e&&typeof e=="object"?e:{},n={};for(const[s,r]of Object.entries(t)){const a=Lj((r==null?void 0:r.roleId)||s);a&&(n[a]={roleId:a,name:Mt(r==null?void 0:r.name)||a,...Mt(r==null?void 0:r.description)?{description:Mt(r==null?void 0:r.description)}:{},permissions:[...new Set(((r==null?void 0:r.permissions)||[]).filter(Boolean))]})}return n}function Gz(e){return(Array.isArray(e==null?void 0:e.channels)?e.channels:[]).map(t=>Mt(t).toLowerCase()).filter(Boolean).filter((t,n,s)=>s.indexOf(t)===n)}function Vz(e){const t=(Array.isArray(e==null?void 0:e.permissions)?e.permissions:[]).map(r=>Mt(r)).filter(Boolean).filter((r,a,i)=>i.indexOf(r)===a),n=e!=null&&e.permissionLabels&&typeof e.permissionLabels=="object"?e.permissionLabels:{},s=e!=null&&e.permissionMeta&&typeof e.permissionMeta=="object"?e.permissionMeta:{};return t.map(r=>{const a=s[r];return{permission:r,name:Mt(a==null?void 0:a.name)||Mt(n[r])||r,description:Mt(a==null?void 0:a.description)}})}function Lg(e,t){return{roles:vx(e==null?void 0:e.roles),channels:t.reduce((n,s)=>(n[s]=JSON.parse(JSON.stringify(((e==null?void 0:e.channels)||{})[s]||{})),n),{})}}function zd(e,t){return e.channels[t]||{}}function Yz(e,t,n){return{...e,channels:{...e.channels,[t]:{...zd(e,t),...n}}}}function Kz(e){return Object.values(vx(e.roles)).sort((t,n)=>{const s=x0.indexOf(t.roleId),r=x0.indexOf(n.roleId);return s>=0||r>=0?s===-1?1:r===-1?-1:s-r:t.name.localeCompare(n.name)})}function Bj(e,t){var s;return Mt((s=t==null?void 0:t.userRoles)==null?void 0:s[e.userId])||Mt(t==null?void 0:t.defaultUserRoleId)||"default"}function Xz(e,t){var s;return Mt((s=t==null?void 0:t.userRoles)==null?void 0:s[e.userId])||void 0}function b0(e,t){return Array.isArray(e==null?void 0:e.permissions)&&e.permissions.includes(t)}function Zz(e){const t=Mt(e.chatType).toLowerCase();return t!==""&&t!=="private"&&t!=="p2p"&&t!=="c2c"}function dh(e,t){return t.includes(e)}function y0(e,t){const n=t.reduce((s,r)=>{const a=zd(e,r);return s[r]={defaultUserRoleId:Mt(a.defaultUserRoleId)||"default",userRoles:{...a.userRoles||{}}},s},{});return{roles:vx(e.roles),channels:n}}function Jz(e){var s;let t=0,n=0;for(const r of e.authorizationChannels)(Mt((s=e.channels[r])==null?void 0:s.defaultUserRoleId)||"default")===e.roleId&&(n+=1);for(const r of e.users){const a=Mt(r.channel).toLowerCase();if(!dh(a,e.authorizationChannels))continue;const i=e.channels[a];Bj(r,i)===e.roleId&&(t+=1)}return{users:t,defaults:n}}function Qz(e){return e==="telegram"?"border-sky-500/20 bg-sky-500/8 text-sky-700":e==="feishu"?"border-blue-500/20 bg-blue-500/8 text-blue-700":e==="consoleui"?"border-zinc-500/20 bg-zinc-500/8 text-zinc-700":"border-emerald-500/20 bg-emerald-500/8 text-emerald-700"}function Wz(e,t){return t?e.map(s=>Mt(s).toLowerCase()).join(" ").includes(t):!0}function fh(e){return!_j.has(e)}function eI(e,t){var n;return((n=t.find(s=>s.roleId===e))==null?void 0:n.name)||e}function tI(e,t){if(!fh(t))return e;const n={...e.roles};delete n[t];const s=Object.fromEntries(Object.entries(e.channels).map(([r,a])=>{const i=a||{},l=Object.fromEntries(Object.entries(i.userRoles||{}).filter(([,u])=>u!==t));return[r,{...i,defaultUserRoleId:Mt(i.defaultUserRoleId)===t?"default":Mt(i.defaultUserRoleId)||"default",userRoles:l}]}));return{roles:n,channels:s}}function nI(e,t){const n=Lj(e);if(n&&!t.some(r=>r.roleId===n))return n;let s=t.length+1;for(;t.some(r=>r.roleId===`${p0}-${s}`);)s+=1;return`${p0}-${s}`}function cu(e){return o.jsxs("div",{className:Me("inline-flex min-w-[7.5rem] items-center gap-2 rounded-full border px-3 py-1.5",e.tone==="success"?"border-emerald-500/20 bg-emerald-500/8 text-emerald-700":"border-border/70 bg-secondary/60 text-foreground"),children:[e.icon?o.jsx("span",{className:"text-muted-foreground",children:e.icon}):null,o.jsx("span",{className:"text-[10px] uppercase tracking-[0.12em] text-muted-foreground",children:e.label}),o.jsx("span",{className:"ml-auto text-sm font-semibold",children:e.value})]})}function v0(e){return o.jsx("span",{className:Me("inline-flex h-5 items-center rounded-full border px-2 text-[10px]",Qz(e.channel)),children:e.channel})}function sI(e){const{authorization:t,selectedAgent:n,formatTime:s,onRefresh:r,onSaveConfig:a,onRunAction:i}=e,l=Ls(),u=c.useMemo(()=>t==null?void 0:t.catalog,[t==null?void 0:t.catalog]),d=c.useMemo(()=>Gz(u),[u]),f=c.useMemo(()=>Vz(u),[u]),[g,m]=c.useState(()=>Lg(void 0,[])),[h,x]=c.useState(!1),[y,w]=c.useState(!1),[b,p]=c.useState("roles"),[v,S]=c.useState(""),[j,C]=c.useState("all"),[A,M]=c.useState("");c.useEffect(()=>{m(Lg(t==null?void 0:t.config,d))},[t==null?void 0:t.config,d]);const O=c.useMemo(()=>Array.isArray(t==null?void 0:t.users)?t.users:[],[t==null?void 0:t.users]),P=c.useMemo(()=>Array.isArray(t==null?void 0:t.chats)?t.chats:[],[t==null?void 0:t.chats]),$=c.useMemo(()=>Kz(g),[g]),z=c.useMemo(()=>y0(g,d),[d,g]),N=c.useMemo(()=>y0(Lg(t==null?void 0:t.config,d),d),[t==null?void 0:t.config,d]),H=c.useMemo(()=>JSON.stringify(z)!==JSON.stringify(N),[z,N]),R=c.useMemo(()=>P.filter(Zz).length,[P]),I=c.useMemo(()=>{const k=Mt(A).toLowerCase();return O.filter(D=>{const B=Mt(D.channel).toLowerCase();return!dh(B,d)||j!=="all"&&B!==j?!1:Wz([D.username,D.userId,D.lastChatId,D.lastChatTitle,D.lastChatType],k)})},[d,j,O,A]),T=c.useCallback(async()=>{try{x(!0),await a(z)}finally{x(!1)}},[z,a]),E=c.useCallback(()=>{const k=nI(v,$);m(D=>({...D,roles:{...D.roles,[k]:{roleId:k,name:Mt(v)||"New Role",description:"",permissions:[]}}})),S("")},[v,$]),q=c.useCallback(async k=>{!fh(k.roleId)||!await l({title:`删除角色 ${k.name}`,description:"删除后会回退到 default。",confirmText:"删除",confirmVariant:"destructive"})||m(B=>tI(B,k.roleId))},[l]);return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Authorization",description:Mt((n==null?void 0:n.name)||(n==null?void 0:n.id)||"未选择"),bodyClassName:"space-y-2.5",actions:o.jsxs(o.Fragment,{children:[o.jsxs(be,{type:"button",size:"sm",variant:"ghost",className:"rounded-[10px]",onClick:()=>void r(),children:[o.jsx(xc,{className:"mr-1 size-4"}),"Refresh"]}),o.jsx(be,{type:"button",size:"sm",className:"rounded-[10px]",disabled:h||!H,onClick:()=>void T(),children:h?"Saving":"Save"})]}),children:o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(cu,{label:"Roles",value:$.length,icon:o.jsx(Tw,{className:"size-3.5"})}),o.jsx(cu,{label:"Users",value:O.length,icon:o.jsx(Q5,{className:"size-3.5"})}),o.jsx(cu,{label:"Groups",value:R,icon:o.jsx(v5,{className:"size-3.5"})}),o.jsx(cu,{label:"Draft",value:H?"Pending":"Synced",tone:H?"default":"success",icon:o.jsx(q5,{className:"size-3.5"})}),o.jsxs(be,{type:"button",size:"sm",className:"ml-auto rounded-[10px]",onClick:()=>{p("roles"),w(!0)},children:[o.jsx(pd,{className:"mr-1 size-4"}),"Policy"]})]})}),o.jsxs(wt,{title:"Directory",description:"Users",bodyClassName:"space-y-2.5",children:[o.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between",children:[o.jsxs("div",{className:"relative min-w-[14rem]",children:[o.jsx(Wl,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{className:"h-9 rounded-[12px] bg-secondary/70 pl-9",value:A,onChange:k=>M(k.target.value),placeholder:"search user / chat / id"})]}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:["all",...d].map(k=>o.jsx(be,{type:"button",size:"sm",variant:"ghost",className:Me("rounded-[10px]",k===j?"bg-secondary":""),onClick:()=>C(k),children:k},`channel-filter:${k}`))})]}),o.jsx(x6,{className:"bg-border/70"}),I.length===0?o.jsx("div",{className:"rounded-[12px] bg-secondary/40 px-3 py-5 text-sm text-muted-foreground",children:"没有匹配的用户。"}):o.jsx("div",{className:"space-y-1.5",children:I.map(k=>{const D=Mt(k.channel).toLowerCase();if(!dh(D,d))return null;const B=zd(g,D),Q=Bj(k,B),Z=Xz(k,B),te=$.find(se=>se.roleId===Q);return o.jsx("article",{className:"rounded-[12px] border border-border/60 bg-secondary/25 px-3 py-2",children:o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0 flex-1 space-y-0.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:k.username||k.userId}),o.jsx(v0,{channel:D}),o.jsx(An,{variant:"secondary",className:"h-5 rounded-full px-1.5 text-[10px]",children:Z?"custom":"default"}),b0(te,"agent.manage")?o.jsx(An,{className:"h-5 rounded-full bg-emerald-600 px-1.5 text-[10px] text-white",children:"admin"}):null]}),o.jsx("div",{className:"font-mono text-[11px] text-muted-foreground",children:k.userId}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:`${k.lastChatTitle||k.lastChatId||"-"} · ${k.lastChatType||"-"} · ${s(k.lastSeenAt)}`})]}),o.jsx("select",{className:"h-9 min-w-[10.5rem] rounded-[10px] border border-transparent bg-background/90 px-3 text-sm outline-none transition focus-visible:ring-3 focus-visible:ring-ring/30",value:Q,onChange:se=>{i({action:"setUserRole",channel:D,userId:k.userId,roleId:se.target.value})},children:$.map(se=>o.jsx("option",{value:se.roleId,children:se.name},`${D}:user:${k.userId}:${se.roleId}`))})]})},`${k.channel}:${k.userId}`)})})]}),o.jsx($n,{open:y,onOpenChange:w,children:o.jsxs(Un,{className:"w-[min(96vw,920px)] p-0",children:[o.jsxs(Hn,{className:"border-b border-border/70 bg-secondary/35 px-4 py-3",children:[o.jsx(Fn,{children:"Policy"}),o.jsx(os,{className:"sr-only",children:"Authorization policy editor"})]}),o.jsxs(k6,{value:b,onValueChange:k=>p(k),className:"gap-0",children:[o.jsx("div",{className:"border-b border-border/70 px-4 py-2",children:o.jsxs(T6,{className:"rounded-[10px] bg-secondary/70 p-0.5",children:[o.jsx(e0,{value:"roles",className:"rounded-[8px] px-2.5 text-xs",children:"Roles"}),o.jsx(e0,{value:"defaults",className:"rounded-[8px] px-2.5 text-xs",children:"Defaults"})]})}),o.jsx(t0,{value:"roles",className:"max-h-[72vh] overflow-y-auto p-4",children:o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx(lt,{value:v,onChange:k=>S(k.target.value),placeholder:"new role id",className:"h-9 rounded-[12px] bg-secondary/70"}),o.jsx(be,{type:"button",size:"sm",className:"rounded-[10px] px-3",onClick:E,children:o.jsx(fa,{className:"size-4"})})]}),o.jsx(Jr,{children:o.jsx("div",{className:"space-y-2",children:$.map(k=>{const D=Jz({roleId:k.roleId,channels:g.channels,authorizationChannels:d,users:O});return o.jsxs("article",{className:"rounded-[12px] border border-border/70 bg-background/85 px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(lt,{value:k.name,className:"h-8 min-w-[10rem] flex-1 rounded-[10px] bg-secondary/60",onChange:B=>{const Q=B.target.value;m(Z=>({...Z,roles:{...Z.roles,[k.roleId]:{...Z.roles[k.roleId]||k,name:Q}}}))}}),o.jsx(An,{variant:"outline",className:"bg-background/90 font-mono text-[10px]",children:k.roleId}),o.jsx(An,{variant:"secondary",className:"bg-secondary text-[10px] text-muted-foreground",children:`${D.users}/${D.defaults}`}),_j.has(k.roleId)?o.jsx(An,{variant:"outline",className:"h-5 rounded-full px-1.5 text-[10px]",children:"reserved"}):null,o.jsx(be,{type:"button",variant:"ghost",size:"sm",className:"ml-auto rounded-[8px] px-2 text-destructive hover:bg-destructive/8 hover:text-destructive",disabled:!fh(k.roleId),onClick:()=>void q(k),children:o.jsx(er,{className:"size-4"})})]}),o.jsx("div",{className:"mt-2",children:o.jsx(lt,{value:k.description||"",className:"h-8 rounded-[10px] bg-secondary/60",onChange:B=>{const Q=B.target.value;m(Z=>({...Z,roles:{...Z.roles,[k.roleId]:{...Z.roles[k.roleId]||k,description:Q}}}))},placeholder:"description"})}),o.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:f.map(B=>{const Q=b0(k,B.permission);return o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:Me("inline-flex h-7 items-center rounded-[9px] border px-2 text-[11px] font-medium transition",Q?"border-foreground/10 bg-foreground text-background":"border-border/70 bg-background text-muted-foreground hover:bg-secondary/45 hover:text-foreground"),onClick:()=>{m(Z=>{const te=Z.roles[k.roleId]||k,se=new Set(te.permissions||[]);return se.has(B.permission)?se.delete(B.permission):se.add(B.permission),{...Z,roles:{...Z.roles,[k.roleId]:{...te,permissions:[...se]}}}})},children:B.name})}),B.description?o.jsx(eo,{children:B.description}):null]},`${k.roleId}:${B.permission}`)})})]},`role-card:${k.roleId}`)})})})]})}),o.jsx(t0,{value:"defaults",className:"max-h-[72vh] overflow-y-auto p-4",children:o.jsx("div",{className:"space-y-1.5",children:d.map(k=>{const D=zd(g,k),B=Mt(D.defaultUserRoleId)||"default",Q=$.find(Z=>Z.roleId===B);return o.jsx("article",{className:"rounded-[12px] border border-border/70 bg-secondary/28 px-3 py-2",children:o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(v0,{channel:k}),o.jsx("div",{className:"text-sm font-medium text-foreground",children:(Q==null?void 0:Q.name)||eI(B,$)})]}),o.jsx("select",{className:"h-8 min-w-[12rem] rounded-[10px] border border-transparent bg-background/90 px-3 text-sm outline-none transition focus-visible:ring-3 focus-visible:ring-ring/30",value:B,onChange:Z=>{m(te=>Yz(te,k,{defaultUserRoleId:Z.target.value}))},children:$.map(Z=>o.jsx("option",{value:Z.roleId,children:Z.name},`${k}:default-user:${Z.roleId}`))})]})},`channel-default:${k}`)})})})]}),o.jsx(rs,{className:"border-t border-border/70 bg-background px-4 py-3",children:o.jsx(be,{type:"button",variant:"outline",onClick:()=>w(!1),children:"Close"})})]})})]})}const Vn="h-8 w-8 rounded-[11px] bg-transparent text-muted-foreground hover:bg-foreground/8 hover:text-foreground",Ro="h-8 w-8 rounded-[11px] bg-transparent text-destructive hover:bg-foreground/8 hover:text-destructive",rI=new Set(["init","start","stop","console","agent","service","plugin","chat","skill","task","memory","asr","tts"]),gh=[{label:"Console",items:[{label:"Version",command:"-v",description:"查看 CLI 版本"},{label:"Start DC",command:"start",description:"启动 console 与 console ui"},{label:"Stop DC",command:"stop",description:"停止 console(含 agent)"},{label:"Console Status",command:"console status",description:"查看 console 与托管 agent 状态"},{label:"Console Agents",command:"console agents",description:"查看 console 托管 agent 列表"},{label:"UI Status",command:"console ui status",description:"查看 console UI 运行状态"},{label:"UI Restart",command:"console ui restart",description:"重启 console UI"}]},{label:"Agent",items:[{label:"Agent Create",command:"agent create .",description:"初始化当前目录为 agent 项目"},{label:"Agent Status",command:"agent status",description:"查看当前项目 agent 状态"},{label:"Agent Start",command:"agent start",description:"启动当前项目 agent"},{label:"Agent Foreground",command:"agent start --foreground",description:"以前台模式运行当前 agent"},{label:"Agent Restart",command:"agent restart",description:"重启当前项目 agent"},{label:"Agent Doctor",command:"agent doctor",description:"诊断并修复 daemon 状态文件"},{label:"Agent Doctor Fix",command:"agent doctor --fix",description:"自动清理僵尸 pid/meta"}]},{label:"Config & Model",items:[{label:"Config Get",command:"console config get",description:"读取当前 downcity.json 配置"},{label:"Config Primary",command:"console config get model.primary",description:"读取当前项目主模型绑定"},{label:"Config Alias",command:"console config alias --print",description:"打印 alias city 配置片段"},{label:"Model List",command:"console model list",description:"列出 provider 与模型池"},{label:"Model Create",command:"console model create",description:"交互式创建 provider 或 model"},{label:"Model Discover",command:"console model discover <providerId>",description:"探测 provider 可用模型"},{label:"Model Use",command:"console model use <modelId>",description:"绑定当前项目 model.primary"},{label:"Model Test",command:"console model test provider <providerId>",description:"测试 provider 连通性"}]},{label:"Service",items:[{label:"Service List",command:"service list",description:"列出 service 运行状态"},{label:"Service Chat",command:"service status chat",description:"查看 chat service 状态"},{label:"Service Task",command:"service status task",description:"查看 task service 状态"},{label:"Service Memory",command:"service status memory",description:"查看 memory service 状态"},{label:"Service Restart",command:"service restart chat",description:"重启 chat service"},{label:"Task Reload",command:"service command task reload",description:"触发 task scheduler 重载"}]},{label:"Chat",items:[{label:"Chat Status",command:"chat status",description:"查看 chat 渠道连接状态"},{label:"Chat Test",command:"chat test",description:"测试 chat 渠道连通性"},{label:"Chat Reconnect",command:"chat reconnect",description:"重连 chat 渠道"},{label:"Chat Context",command:"chat context",description:"查看当前会话上下文快照"},{label:"Chat History",command:"chat history --limit 30",description:"读取最近聊天历史"},{label:"Chat Send",command:'chat send --text "hello from city"',description:"向当前 chatKey 发送消息"}]},{label:"Task & Memory",items:[{label:"Task List",command:"task list",description:"列出任务定义"},{label:"Task Enabled",command:"task list --status enabled",description:"仅查看启用任务"},{label:"Task Run",command:'task run "<taskTitle>"',description:"手动执行指定任务"},{label:"Task Enable",command:'task enable "<taskTitle>"',description:"启用指定任务"},{label:"Task Disable",command:'task disable "<taskTitle>"',description:"禁用指定任务"},{label:"Memory Status",command:"memory status",description:"查看 memory backend 状态"},{label:"Memory Index",command:"memory index --force",description:"重建 memory 索引"},{label:"Memory Search",command:'memory search "<query>"',description:"检索记忆片段"}]},{label:"Skill / ASR / TTS",items:[{label:"Skill List",command:"skill list",description:"列出当前已学会 skills"},{label:"Skill Find",command:'skill find "<query>"',description:"查找缺失技能"},{label:"Skill Lookup",command:'skill lookup "<skillName>"',description:"读取技能 SKILL.md 内容"},{label:"ASR Models",command:"asr models",description:"列出内置语音识别模型目录"},{label:"Plugin List",command:"plugin list",description:"列出当前 agent 的 plugins"},{label:"ASR Status",command:"asr status",description:"查看 asr plugin 配置"},{label:"ASR On",command:"asr on SenseVoiceSmall",description:"启用 asr 并安装默认模型"},{label:"ASR Use",command:"asr use SenseVoiceSmall",description:"切换 active 语音识别模型"},{label:"ASR Off",command:"asr off",description:"关闭 asr plugin"},{label:"TTS Status",command:"tts status",description:"查看 tts plugin 配置"},{label:"TTS On",command:"tts on",description:"启用 tts plugin"},{label:"TTS Synthesize",command:'tts synthesize "hello from city"',description:"生成可发送的语音文件"}]}],oI=gh.flatMap(e=>e.items.map(t=>t.command));function w0(e){const{selectedAgentId:t,selectedAgentName:n,agents:s=[],onSelectAgent:r,persistSelectionInUrl:a=!0,onExecute:i}=e,l=Ls(),[u,d]=c.useState(""),[f,g]=c.useState(""),[m,h]=c.useState(!1),[x,y]=c.useState([]),[w,b]=c.useState([]),[p,v]=c.useState(""),S=c.useRef(null),j=c.useRef(null),C=c.useRef(-1),A=c.useRef(""),M=c.useCallback(()=>{var te,se;const D=s.map(ie=>({id:String(ie.id||"").trim(),running:ie.running===!0})).filter(ie=>ie.id);if(D.length===0)return"";const B=(()=>{var oe;if(!a||typeof window>"u")return"";const ie=String(new URLSearchParams(window.location.search).get("agent")||"").trim();return ie&&((oe=D.find(pe=>pe.id===ie))==null?void 0:oe.id)||""})();if(B)return B;const Q=String(t||"").trim();if(Q&&D.some(ie=>ie.id===Q))return Q;const Z=((te=D.find(ie=>ie.running))==null?void 0:te.id)||"";return Z||((se=D[0])==null?void 0:se.id)||""},[s,a,t]);c.useEffect(()=>{const D=M();d(B=>B&&s.some(Q=>String(Q.id||"").trim()===B)?B:D)},[s,M]),c.useEffect(()=>{if(!a||typeof window>"u")return;const D=new URL(window.location.href),B=String(D.searchParams.get("agent")||"").trim();if(!u){if(!B)return;D.searchParams.delete("agent"),window.history.replaceState({},"",`${D.pathname}${D.search}${D.hash}`);return}B!==u&&(D.searchParams.set("agent",u),window.history.replaceState({},"",`${D.pathname}${D.search}${D.hash}`))},[u,a]);const O=c.useMemo(()=>s.find(D=>String(D.id||"")===u)??null,[u,s]),P=String((O==null?void 0:O.name)||n||u||"agent").trim()||"agent",$=c.useCallback(D=>{const B=String(D||"").trim();if(!B)return"";if(/^(?:city|downcity)(?:\s|$)/i.test(B))return B;const Q=String(B.split(/\s+/,1)[0]||"").trim().toLowerCase();return Q?Q.startsWith("-")||rI.has(Q)?`city ${B}`:B:""},[]),z=c.useCallback(D=>D.timedOut?{label:"timeout",badgeClassName:"bg-amber-500/12 text-amber-700 dark:text-amber-300",rowClassName:"border-amber-500/35"}:!!String(D.stderr||"").trim()||Number(D.exitCode??0)!==0?{label:"error",badgeClassName:"bg-destructive/10 text-destructive",rowClassName:"border-destructive/40"}:{label:"success",badgeClassName:"bg-emerald-500/12 text-emerald-700 dark:text-emerald-300",rowClassName:"border-emerald-500/35"},[]),N=c.useCallback(D=>{const B=String(D||"").trim();B&&(b(Q=>{const te=[...Q.filter(se=>se!==B),B];return te.length<=120?te:te.slice(te.length-120)}),C.current=-1,A.current="")},[]),H=c.useCallback(D=>{C.current=-1,A.current="",g(D)},[]),R=c.useCallback(D=>{if(w.length!==0){if(D==="up"){C.current===-1?(A.current=f,C.current=w.length-1):C.current=Math.max(0,C.current-1),g(w[C.current]||"");return}if(C.current!==-1){if(C.current>=w.length-1){C.current=-1,g(A.current);return}C.current+=1,g(w[C.current]||"")}}},[f,w]),I=c.useMemo(()=>{const D=[],B=new Set;for(let Q=w.length-1;Q>=0;Q-=1){const Z=String(w[Q]||"").trim();!Z||B.has(Z)||(B.add(Z),D.push(Z))}for(const Q of[...oI,"clear","cls"]){const Z=String(Q||"").trim();!Z||B.has(Z)||(B.add(Z),D.push(Z))}return D},[w]),T=c.useMemo(()=>{const D=String(f||"");if(!D.trim())return"";const B=D.toLowerCase();return I.find(Z=>{const te=Z.toLowerCase();return te===B?!1:te.startsWith(B)})||""},[f,I]),E=c.useMemo(()=>T?T.slice(f.length):"",[f,T]),q=c.useCallback(D=>{var ie,oe;if(!T||!E)return!1;if(D==="full")return g(T),!0;const B=((ie=E.match(/^\s*/))==null?void 0:ie[0])||"",Q=E.slice(B.length);if(!Q)return g(T),!0;const Z=Q.match(/^[^\s]+/),te=Z?Z[0]:Q,se=((oe=Q.slice(te.length).match(/^\s*/))==null?void 0:oe[0])||"";return g(pe=>`${pe}${B}${te}${se}`),!0},[T,E]),k=c.useCallback(async D=>{const B=String(D||"").trim(),Q=B.toLowerCase();if(Q==="clear"||Q==="cls"){y([]),v(""),g("");return}const Z=$(D);if(!(!Z||m||!u)){N(B),h(!0),v("");try{const te=await i({command:Z,timeoutMs:45e3,agentId:u});y(se=>[...se,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,result:te}]),g("")}catch(te){v(te instanceof Error?te.message:String(te))}finally{h(!1)}}},[u,i,N,$,m]);return c.useEffect(()=>{var D;(D=S.current)==null||D.scrollTo({top:S.current.scrollHeight,behavior:"smooth"})},[x.length,m]),o.jsxs(wt,{title:"Command",description:"在当前 agent 上直接执行命令,输出按会话顺序保留。",className:"flex h-full min-h-0 flex-1 flex-col overflow-hidden",bodyClassName:"flex min-h-0 flex-1 flex-col",actions:o.jsxs(o.Fragment,{children:[s.length>0?o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{variant:"outline",size:"sm",className:"h-8 gap-2 rounded-[11px] px-2.5 text-[12px] font-normal"}),children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",O!=null&&O.running?"bg-emerald-500":"bg-muted-foreground/40")}),o.jsx("span",{className:"max-w-[12rem] truncate",children:P}),o.jsx(XA,{className:"size-3.5 text-muted-foreground"})]}),o.jsx(wn,{align:"start",className:"w-56",children:o.jsxs(ih,{children:[o.jsx(lh,{className:"text-[11px] uppercase tracking-[0.1em] text-muted-foreground",children:"选择 agent"}),o.jsx(Md,{}),s.map(D=>{const B=String(D.id||"").trim();if(!B)return null;const Q=B===u;return o.jsxs(bt,{onClick:()=>{d(B),r==null||r(B)},className:"justify-between gap-2 text-[12px]",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2 truncate",children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",D.running?"bg-emerald-500":"bg-muted-foreground/40")}),o.jsx("span",{className:"truncate",children:D.name||B})]}),Q?o.jsx(Ws,{className:"size-3.5 shrink-0 text-primary"}):null]},B)})]})})]}):o.jsxs("div",{className:"inline-flex h-8 items-center gap-2 rounded-[11px] border border-border bg-transparent px-2.5 text-[12px] text-muted-foreground",children:[o.jsx("span",{className:"inline-flex size-1.5 rounded-full bg-muted-foreground/40"}),"未选择 agent"]}),o.jsx(be,{size:"icon",variant:"ghost",onClick:()=>{(async()=>await l({title:"清空输出",description:"确认清空当前命令输出记录吗?",confirmText:"清空",confirmVariant:"destructive"})&&y([]))()},disabled:m||x.length===0,className:Ro,"aria-label":"清空输出",title:"清空输出",children:o.jsx(er,{className:"size-4"})})]}),children:[o.jsx("div",{className:"min-h-0 flex-1 rounded-[20px] bg-secondary p-2",children:o.jsxs("div",{ref:S,className:"h-full overflow-auto rounded-[18px] px-3 py-3 font-mono text-[12px] leading-relaxed text-foreground/92",children:[x.length===0?o.jsxs("div",{className:"text-muted-foreground",children:[`# 当前 agent: ${P}`,o.jsx("br",{}),"# 输入命令并执行,输出会记录在这里"]}):x.map(D=>{const B=`exit=${String(D.result.exitCode??"-")} · ${D.result.durationMs}ms${D.result.timedOut?" · timeout":""}`,Q=z(D.result);return o.jsxs("div",{className:`mb-4 border-l-2 pl-3 last:mb-0 ${Q.rowClassName}`,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-foreground",children:`$ ${D.result.command}`}),o.jsx("span",{className:`inline-flex rounded-[10px] px-1.5 py-0.5 text-[10px] leading-none ${Q.badgeClassName}`,children:Q.label})]}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:`${D.result.cwd} · ${B}`}),D.result.stdout?o.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words text-foreground/95",children:D.result.stdout}):null,D.result.stderr?o.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words rounded-[10px] bg-destructive/6 px-2 py-1 text-destructive",children:D.result.stderr}):null]},D.id)}),m?o.jsx("div",{className:"text-primary/80",children:`$ ${$(f)||"(running...)"}`}):null]})}),o.jsxs("div",{className:"space-y-2 rounded-[20px] bg-secondary px-3 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(yn,{children:[o.jsx(vn,{disabled:m||!u,className:`inline-flex shrink-0 items-center justify-center disabled:pointer-events-none disabled:opacity-50 ${Vn}`,"aria-label":"常用命令",title:"常用命令",children:o.jsx(Vm,{className:"size-4"})}),o.jsx(wn,{align:"start",className:"w-[24rem]",children:gh.map((D,B)=>o.jsxs(c.Fragment,{children:[o.jsxs(ih,{children:[o.jsx(lh,{className:"text-[11px] uppercase tracking-[0.1em] text-muted-foreground",children:D.label}),D.items.map(Q=>o.jsx(bt,{onClick:()=>{H(Q.command),requestAnimationFrame(()=>{var Z;return(Z=j.current)==null?void 0:Z.focus()})},className:"items-start py-2",children:o.jsxs("span",{className:"grid min-w-0 gap-0.5",children:[o.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:Q.label}),o.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:Q.command}),o.jsx("span",{className:"truncate text-[11px] text-muted-foreground/90",children:Q.description})]})},`${D.label}:${Q.command}`))]}),B<gh.length-1?o.jsx(Md,{}):null]},D.label))})]}),o.jsxs("div",{className:"relative flex h-9 flex-1 items-center rounded-[14px] bg-background px-3",children:[o.jsx("span",{className:"mr-2 font-mono text-xs text-muted-foreground",children:"$"}),o.jsxs("div",{className:"relative flex-1",children:[E?o.jsxs("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 z-0 flex h-8 items-center overflow-hidden font-mono text-[12px]",children:[o.jsx("span",{className:"invisible whitespace-pre",children:f}),o.jsx("span",{className:"whitespace-pre text-muted-foreground/45",children:E})]}):null,o.jsx("input",{ref:j,value:f,onChange:D=>H(D.target.value),onKeyDown:D=>{if(D.key==="Enter"){D.preventDefault(),k(f);return}if(D.key==="Tab"){q("full")&&D.preventDefault();return}if(D.key==="ArrowRight"&&(D.ctrlKey||D.metaKey)){q("word")&&D.preventDefault();return}if(D.key==="ArrowUp"){D.preventDefault(),R("up");return}D.key==="ArrowDown"&&(D.preventDefault(),R("down"))},placeholder:"输入命令后按回车执行(CITY 命令可省略 city)",className:"relative z-10 h-8 w-full bg-transparent font-mono text-[12px] text-foreground outline-none placeholder:text-muted-foreground/80"})]})]}),o.jsx(be,{size:"sm",variant:"secondary",disabled:m||!u||!String(f||"").trim(),onClick:()=>void k(f),className:"h-9 px-3",children:"执行"})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-[11px] text-muted-foreground/80",children:[o.jsx("span",{children:"Tab 接受预测 · Ctrl/⌘ + → 接受下一个词 · ↑/↓ 浏览历史命令"}),u?null:o.jsx("span",{className:"text-destructive",children:"请先选择 agent"}),p?o.jsx("span",{className:"text-destructive",children:p}):null]})]})]})}function aI(e){const{checking:t,bootstrapRequired:n,submitting:s,errorMessage:r,onSubmit:a}=e,[i,l]=c.useState(""),u=c.useCallback(async d=>{d.preventDefault(),await a({token:i})},[a,i]);return o.jsx("div",{className:"flex min-h-screen w-full items-center justify-center bg-secondary/30 px-4",children:o.jsxs("section",{className:"w-full max-w-sm rounded-[22px] bg-background px-6 py-6 shadow-[0_1px_0_rgba(17,17,19,0.03)] ring-1 ring-border/70",children:[o.jsxs("div",{className:"mb-6",children:[o.jsx("h1",{className:"text-base font-medium text-foreground",children:t?"检查中":n?"先创建 Token":"输入 Token"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t?"验证访问权限...":n?"请先在本机终端执行 city token create":"Console UI Bearer Token"})]}),t?o.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-muted-foreground",children:[o.jsx(nt,{className:"h-4 w-4 animate-spin"}),o.jsx("span",{children:"检查认证状态"})]}):o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("label",{htmlFor:"token",className:"text-xs text-muted-foreground",children:"Bearer Token"}),o.jsx("textarea",{id:"token",value:i,onChange:d=>l(d.target.value),className:"min-h-[108px] w-full rounded-[11px] border border-input bg-transparent px-3 py-2 text-sm outline-none transition-colors focus:border-ring",disabled:s,placeholder:"支持直接粘贴 Bearer xxx 或纯 token"}),o.jsx("div",{className:"rounded-[11px] bg-secondary/50 px-3 py-2 text-xs leading-5 text-muted-foreground",children:"如何获取:在当前机器的终端执行 `city token create my-token`,或直接运行 `city token`。"})]}),n&&o.jsx("div",{className:"rounded-[11px] bg-secondary/70 px-3 py-2 text-xs text-muted-foreground",children:"先在当前机器的终端执行 `city token create my-token`,拿到 token 后再粘贴到这里。"}),r&&o.jsx("div",{className:"rounded-[11px] bg-destructive/10 px-3 py-2 text-xs text-destructive",children:r}),o.jsx(be,{type:"submit",className:"w-full",disabled:s||!i.trim(),children:s?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-2 h-4 w-4 animate-spin"}),"验证中..."]}):"进入 Console"})]})]})})}function S0(e){return e.required!==!0?null:o.jsx("span",{className:"text-destructive",children:"*"})}function Pj(e){const{field:t,value:n,onChange:s}=e;if(t.type==="select"){const r=Array.isArray(t.options)?t.options:[],a=String(n??""),i=r.find(l=>l.value===a)||r[0]||null;return o.jsxs("div",{className:"space-y-2",children:[o.jsxs(qt,{className:"text-xs text-muted-foreground",children:[t.label," ",S0(t)]}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3",disabled:t.disabled===!0}),children:[o.jsx("span",{children:(i==null?void 0:i.label)||t.placeholder||"请选择"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:r.map(l=>o.jsxs(bt,{onClick:()=>s(l.value),children:[a===l.value?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:l.label})]},`${t.key}:${l.value}`))})]}),t.description?o.jsx("div",{className:"text-[11px] leading-5 text-muted-foreground",children:t.description}):null]})}if(t.type==="boolean"){const r=n===!0;return o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:t.label}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsx("button",{type:"button",className:`h-10 rounded-[12px] border px-3 text-sm font-medium transition ${r?"border-border bg-background text-foreground":"border-transparent bg-transparent text-muted-foreground hover:border-border/60 hover:bg-background/70 hover:text-foreground"}`,disabled:t.disabled===!0,onClick:()=>s(!0),children:t.trueLabel||"是"}),o.jsx("button",{type:"button",className:`h-10 rounded-[12px] border px-3 text-sm font-medium transition ${r?"border-transparent bg-transparent text-muted-foreground hover:border-border/60 hover:bg-background/70 hover:text-foreground":"border-border bg-background text-foreground"}`,disabled:t.disabled===!0,onClick:()=>s(!1),children:t.falseLabel||"否"})]}),t.description?o.jsx("div",{className:"text-[11px] leading-5 text-muted-foreground",children:t.description}):null]})}return o.jsxs("div",{className:"space-y-2",children:[o.jsxs(qt,{className:"text-xs text-muted-foreground",children:[t.label," ",S0(t)]}),o.jsx(lt,{type:t.type==="secret"?"password":t.type==="number"?"number":"text",placeholder:t.placeholder,className:"h-10 rounded-[12px]",value:String(n??""),disabled:t.disabled===!0,onChange:r=>s(r.target.value)}),t.description?o.jsx("div",{className:"text-[11px] leading-5 text-muted-foreground",children:t.description}):null]})}const iI=[{label:"Telegram",value:"telegram"},{label:"Feishu",value:"feishu"},{label:"QQ (dev)",value:"qq"}];function lI(e){const t=String(e||"").trim();if(!t)return"-";const n=Date.parse(t);return!Number.isFinite(n)||Number.isNaN(n)?"-":new Date(n).toLocaleString("zh-CN",{hour12:!1})}function j0(){return{id:"",channel:"telegram",name:"",identity:"",owner:"",creator:"",domain:"",sandbox:!1,botToken:"",appId:"",appSecret:""}}function Xt(e){return String(e||"").trim()}function C0(e){return e.channel==="telegram"?Xt(e.botToken).length>0:Xt(e.appId).length>0&&Xt(e.appSecret).length>0}function cI(e){const{form:t,probeStatus:n}=e,s=[];return Xt(t.channel)||s.push("请选择 channel"),n!=="passed"&&s.push(n==="failed"?"测试未通过,请修复凭据后重试":"请先测试凭据并通过"),(!Xt(t.id)||!Xt(t.name))&&s.push("当前账户基础信息缺失,无法确认"),s}function k0(e){return String(e.channel||"").trim().toLowerCase()==="telegram"?e.hasBotToken===!0:e.hasAppId===!0&&e.hasAppSecret===!0}function Bg(e){return bx(e)}function uI(e){if(String(e.channel||"").trim().toLowerCase()==="telegram")return e.hasBotToken===!0?"token ready":"token missing";const n=e.hasAppId===!0,s=e.hasAppSecret===!0;return n&&s?"appId/appSecret ready":n||s?"credentials incomplete":"credentials missing"}function dI(e){return e==="telegram"?[{key:"botToken",label:"botToken",type:"secret",placeholder:"botToken",required:!0}]:e==="feishu"?[{key:"appId",label:"appId",type:"string",placeholder:"appId",required:!0},{key:"appSecret",label:"appSecret",type:"secret",placeholder:"appSecret",required:!0},{key:"domain",label:"domain",type:"string",placeholder:"domain(可选)"}]:e==="qq"?[{key:"appId",label:"appId",type:"string",placeholder:"appId",required:!0},{key:"appSecret",label:"appSecret",type:"secret",placeholder:"appSecret",required:!0},{key:"sandbox",label:"运行环境",type:"boolean",trueLabel:"测试环境",falseLabel:"生产环境",description:"QQ channel 当前为 dev 版本,建议优先在测试环境验证。"}]:[]}function fI(e){const t=[],n=String(e.identity||"").trim(),s=String(e.owner||"").trim(),r=String(e.creator||"").trim(),a=String(e.domain||"").trim(),i=String(e.channel||"").trim().toLowerCase();return n&&t.push(`Bot: ${n}`),s&&t.push(`Owner: ${s}`),r&&t.push(`Creator: ${r}`),i==="feishu"&&a&&t.push(`Domain: ${a}`),i==="qq"&&t.push(`Sandbox: ${e.sandbox===!0?"on":"off"}`),t.push(`Creds: ${uI(e)}`),t.join(" · ")}function gI(e){const{items:t,loading:n,onUpsert:s,onProbe:r,onRemove:a}=e,i=Ls(),[l,u]=c.useState(!1),[d,f]=c.useState(""),[g,m]=c.useState(j0),[h,x]=c.useState(""),[y,w]=c.useState({}),[b,p]=c.useState("idle"),[v,S]=c.useState(""),j=!!h,A=c.useMemo(()=>cI({form:g,probeStatus:b}),[g,b]).length===0,M=c.useCallback(E=>!!y[E],[y]),O=c.useCallback(async(E,q)=>{w(k=>({...k,[E]:!0}));try{await q()}finally{w(k=>({...k,[E]:!1}))}},[]),P=t.filter(E=>k0(E)).length,$=c.useMemo(()=>dI(g.channel),[g.channel]),z=c.useMemo(()=>{const E=d.trim().toLowerCase();return E?t.filter(q=>{const k=String(q.id||"").toLowerCase(),D=String(q.name||"").toLowerCase(),B=String(q.channel||"").toLowerCase();return k.includes(E)||D.includes(E)||B.includes(E)}):t},[t,d]),N=()=>{x(""),m(j0()),p("idle"),S(""),u(!0)},H=E=>{x(String(E.id||"").trim()),m({id:String(E.id||"").trim(),channel:String(E.channel||"telegram").trim().toLowerCase()||"telegram",name:String(E.name||"").trim(),identity:String(E.identity||"").trim(),owner:String(E.owner||"").trim(),creator:String(E.creator||"").trim(),domain:String(E.domain||"").trim(),sandbox:E.sandbox===!0,botToken:"",appId:"",appSecret:""}),p("idle"),S(""),u(!0)},R=()=>{u(!1)},I=async()=>{if(!C0(g))return;p("idle"),S("");const E=await r({channel:g.channel,botToken:Xt(g.botToken)||void 0,appId:Xt(g.appId)||void 0,appSecret:Xt(g.appSecret)||void 0,domain:Xt(g.domain)||void 0,sandbox:g.sandbox});if(!E){p("failed"),S("测试失败");return}p("passed"),S(String(E.message||"").trim()||"测试通过"),m(q=>({...q,id:j?q.id:String(E.accountId||"").trim()||q.id,name:String(E.name||"").trim()||q.name,identity:q.identity.trim()||String(E.identity||"").trim(),owner:q.owner.trim()||String(E.owner||"").trim(),creator:q.creator.trim()||String(E.creator||"").trim()}))},T=async()=>{A&&(await Promise.resolve(s({id:Xt(g.id),channel:Xt(g.channel),name:Xt(g.name),identity:Xt(g.identity)||void 0,owner:Xt(g.owner)||void 0,creator:Xt(g.creator)||void 0,domain:Xt(g.domain)||void 0,sandbox:g.sandbox,botToken:Xt(g.botToken)||void 0,appId:Xt(g.appId)||void 0,appSecret:Xt(g.appSecret)||void 0})),u(!1))};return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Channel Accounts",description:`已配置 ${t.length} 个,凭据完整 ${P} 个`,actions:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:`ready ${P}/${t.length}`}),o.jsx(lt,{value:d,onChange:E=>f(E.target.value),placeholder:"搜索账号",className:"w-[220px]"}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:N,disabled:n,"aria-label":"新建账号",title:"新建账号",children:o.jsx(fa,{className:"size-4"})})]}),children:z.length===0?o.jsx("div",{className:"rounded-[20px] bg-secondary/85 py-6 text-center text-sm text-muted-foreground",children:"暂无 channel account"}):o.jsx("div",{className:"space-y-2.5",children:z.map(E=>{const q=String(E.id||"").trim();if(!q)return null;const k=k0(E),D=fI(E),B=`${q}${D?` · ${D}`:""}`;return o.jsxs("div",{className:"group flex items-center gap-3 rounded-[18px] bg-transparent px-3.5 py-3 transition-colors hover:bg-secondary",children:[o.jsx("div",{className:`h-2.5 w-2.5 shrink-0 rounded-full ${k?"bg-emerald-500":"bg-zinc-400"}`}),o.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:E.name||q}),o.jsx(An,{variant:"secondary",className:"h-5 rounded-[10px] border-border/60 bg-secondary px-1.5 text-[11px] font-medium text-muted-foreground",children:Bg(E.channel||"")})]}),o.jsx("div",{className:"truncate text-xs text-muted-foreground/90",title:B,children:B})]}),o.jsx("div",{className:"hidden text-xs text-muted-foreground md:block",children:lI(E.updatedAt)}),o.jsxs("div",{className:"inline-flex items-center gap-1",children:[o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:()=>H(E),title:"编辑","aria-label":"编辑",children:o.jsx(hd,{className:"size-3.5"})}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Ro,onClick:()=>{(async()=>await i({title:"删除 Channel Account",description:`确认删除账号「${E.name||q}」吗?该操作不可恢复。`,confirmText:"删除",confirmVariant:"destructive"})&&await O(`bot:remove:${q}`,async()=>{await Promise.resolve(a(q))}))()},disabled:M(`bot:remove:${q}`),title:"删除","aria-label":"删除",children:M(`bot:remove:${q}`)?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(er,{className:"size-3.5"})})]})]},q)})})}),o.jsx($n,{open:l,onOpenChange:E=>E?u(!0):R(),children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:j?"编辑 Channel Account":"新建 Channel Account"}),o.jsx(os,{children:"填写必要凭据,先测试,通过后确认。"})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-4 overflow-y-auto px-4 pb-2",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Channel"}),j?o.jsx("div",{className:"rounded-[16px] bg-secondary px-3 py-2.5 text-sm text-foreground",children:Bg(g.channel)}):o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:Bg(g.channel)}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:iI.map(E=>o.jsxs(bt,{onClick:()=>{const q=String(E.value||"").trim()||"telegram";m(k=>({...k,channel:q,id:"",name:"",identity:"",owner:"",creator:"",botToken:"",appId:"",appSecret:"",domain:"",sandbox:!1})),p("idle"),S("")},children:[g.channel===E.value?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:E.label})]},E.value))})]})]}),o.jsxs("div",{className:"space-y-2.5 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Credentials"}),o.jsx("div",{className:`grid gap-2 ${g.channel==="telegram"?"":"md:grid-cols-2"}`,children:$.map(E=>{const q=E.key==="sandbox"?g.sandbox:String(g[E.key]||""),k=E.key==="sandbox"||E.key==="domain";return o.jsx("div",{className:k?"md:col-span-2":"",children:o.jsx(Pj,{field:E,value:q,onChange:D=>{m(B=>({...B,[E.key]:D})),p("idle"),S("")}})},`${g.channel}:${E.key}`)})})]})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:R,children:"取消"}),o.jsxs(be,{size:"sm",variant:"secondary",className:"h-9 rounded-[12px] px-4",disabled:!C0(g)||M("bot:probe")||M("bot:confirm"),onClick:()=>{O("bot:probe",async()=>{await I()})},children:[M("bot:probe")?o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}):o.jsx(Aw,{className:"mr-1 size-3.5"}),"测试"]}),o.jsxs(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!A||M("bot:confirm"),onClick:()=>{O("bot:confirm",async()=>{await T()})},children:[M("bot:confirm")?o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}):null,"下一步:确认"]})]})]})})]})}function mI(e){const t=String(e||"").trim();if(!t)return"-";const n=Date.parse(t);return!Number.isFinite(n)||Number.isNaN(n)?"-":new Date(n).toLocaleString("zh-CN",{hour12:!1})}function to(e){return String(e||"").trim().toUpperCase()}function hI(e){return/^[A-Z_][A-Z0-9_]*$/.test(to(e))}function pI(e){const t=String(e||"").split(/\r?\n/),n=new Set;let s=0,r=0;for(const a of t){const i=String(a||"").trim();if(!i||i.startsWith("#"))continue;s+=1;const u=i.replace(/^export\s+/,"").match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);if(!u){r+=1;continue}n.add(to(u[1]))}return s===0||r>0?[]:[...n]}function xI(e){return e==="clipboard"?{title:"剪贴板导入",description:"读取当前剪贴板中的 .env 文本,预览后确认导入。"}:{title:"手动输入",description:"手动填写单个 key 和 value,适合补充或精确编辑。"}}function uu(e){return e?"rounded-[12px] border border-border bg-background text-foreground":"rounded-[12px] border border-transparent bg-transparent text-muted-foreground hover:border-border/60 hover:bg-background/70 hover:text-foreground"}function bI(e){const{title:t,description:n,emptyText:s,items:r,loading:a,writable:i=!0,agentOptions:l=[],onUpsert:u,onImport:d,onRemove:f}=e,g=Ls(),[m,h]=c.useState(""),[x,y]=c.useState(""),[w,b]=c.useState(""),[p,v]=c.useState("global"),[S,j]=c.useState(""),[C,A]=c.useState(""),[M,O]=c.useState("global"),[P,$]=c.useState(""),[z,N]=c.useState(!1),[H,R]=c.useState("manual"),[I,T]=c.useState(""),[E,q]=c.useState([]),[k,D]=c.useState(!1),B=to(m),Q=l.length>0,Z=Q&&p==="agent",te=!!C,se=i&&E.length>0&&(!Z||!!String(S||"").trim()),ie=i&&B.length>0&&hI(B)&&(!Z||!!String(S||"").trim()),oe=xI(H),pe=c.useMemo(()=>{const W=new Map;for(const X of l){const G=String(X.id||"").trim();G&&W.set(G,String(X.name||X.id||"").trim()||G)}return W},[l]),_=c.useCallback(()=>{h(""),y(""),b(""),v("global"),j(""),A(""),O("global"),R("manual"),T(""),q([]),D(!1)},[]),Y=c.useCallback(()=>{(async()=>{var X;if(D(!1),T(""),q([]),typeof navigator>"u"||!((X=navigator.clipboard)!=null&&X.readText)){D(!0);return}$("clipboard:read");try{const G=await navigator.clipboard.readText(),L=pI(G);T(G),q(L)}catch{T(""),q([])}finally{D(!0),$("")}})()},[]),le=c.useCallback(()=>{i&&(_(),N(!0),d&&Y())},[Y,d,_,i]),ne=c.useCallback(W=>{i&&(A(String(W.key||"").trim()),O(W.scope||"global"),h(String(W.key||"").trim()),y(String(W.value??"")),b(String(W.description??"")),v(W.scope||"global"),j(String(W.agentId||"").trim()),N(!0))},[i]),ue=c.useCallback(async()=>{if(!ie||!u)return;const W=to(m);$(`save:${W}`);try{await Promise.resolve(u({scope:p,agentId:S||void 0,key:W,description:String(w||"").trim(),value:String(x??"")})),_(),N(!1)}finally{$("")}},[ie,S,w,m,p,x,u,_]),ae=c.useCallback(async()=>{if(!(!se||!d)){$("import:submit");try{await Promise.resolve(d({scope:p,agentId:S||void 0,raw:I})),_(),N(!1)}finally{$("")}}},[se,I,S,p,d,_]),xe=c.useCallback(async W=>{if(!f)return;const X=to(W.key),G=String(W.agentId||"").trim(),L=W.scope||"global";if(await g({title:"删除 Env",description:`确认删除环境变量「${X}」吗?该操作不可恢复。`,confirmText:"删除",confirmVariant:"destructive"})){$(`remove:${L}:${G}:${X}`);try{await Promise.resolve(f({scope:L,agentId:G||void 0,key:X})),X===to(C)&&_()}finally{$("")}}},[g,C,f,_]),ee=r.filter(W=>String(W.value??"").length>0).length;return o.jsxs(wt,{title:t,description:`${n} 共 ${r.length} 个条目,非空值 ${ee} 个。`,actions:i?o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx(be,{type:"button",size:"icon",className:"h-8 w-8 rounded-[12px]",onClick:le,disabled:a,"aria-label":"新建 Env"}),children:o.jsx(fa,{className:"size-4"})}),o.jsx(eo,{children:"新建 Env"})]})}):null,children:[r.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary py-6 text-center text-sm text-muted-foreground",children:s}):o.jsx("div",{className:"space-y-2",children:r.map(W=>{const X=to(W.key),G=String(W.value??""),L=String(W.description||"").trim(),J=G?`${"*".repeat(Math.min(G.length,12))} (${G.length})`:"(empty)",me=W.scope||"global",ge=String(W.agentId||"").trim(),U=P===`remove:${me}:${ge}:${X}`,ce=ge?pe.get(ge)||ge:"",F=me==="agent"?"Agent":"Global",K=[ce,J].filter(Boolean).join(" · ");return o.jsx("article",{className:"rounded-[16px] bg-transparent px-3.5 py-2 transition-colors hover:bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"truncate text-sm",children:[o.jsx("span",{className:"font-mono font-semibold text-foreground",children:X}),o.jsx("span",{className:"ml-2 inline-flex h-5 items-center rounded-full bg-secondary px-2 text-[10px] font-medium text-muted-foreground align-middle",children:F}),K?o.jsx("span",{className:"ml-2 truncate font-mono text-xs text-muted-foreground",children:K}):null]}),L?o.jsx("div",{className:"mt-1 truncate text-xs text-muted-foreground",children:L}):null]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx("span",{className:"hidden text-[11px] text-muted-foreground md:inline",children:mI(W.updatedAt)}),i?o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:()=>ne(W),title:"编辑","aria-label":"编辑",children:o.jsx(hd,{className:"size-3.5"})}):null,i?o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Ro,onClick:()=>{xe({scope:me,agentId:ge,key:X})},disabled:U,title:"删除","aria-label":"删除",children:U?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(er,{className:"size-3.5"})}):null]})]})},`${String(W.scope||"global")}:${String(W.agentId||"")}:${X}`)})}),o.jsx($n,{open:z,onOpenChange:W=>{N(W),W||_()},children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:C?"编辑 Env":"新建 Env"}),o.jsx(os,{className:"text-xs leading-5",children:C?"更新当前环境变量。":`${oe.title}。${oe.description}`})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-3 overflow-y-auto px-4 pb-2",children:[te?null:o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("button",{type:"button",className:`${uu(H==="manual")} px-3 py-3 text-left transition`,onClick:()=>R("manual"),children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[o.jsx(u5,{className:"size-4"}),"手动输入"]}),o.jsx("div",{className:"mt-1 text-[11px] leading-5 text-muted-foreground",children:"单条创建"})]}),o.jsxs("button",{type:"button",className:`${uu(H==="clipboard")} px-3 py-3 text-left transition`,onClick:()=>{R("clipboard"),!k&&d&&Y()},disabled:!d,children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[o.jsx(JA,{className:"size-4"}),"剪贴板导入"]}),o.jsx("div",{className:"mt-1 text-[11px] leading-5 text-muted-foreground",children:"批量导入"})]})]}),Q?o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"范围"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"scope help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"Global 为共享,Agent 为单个 agent 私有"})]})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsx("button",{type:"button",className:`${uu(p==="global")} h-10 px-3 text-sm font-medium transition`,onClick:()=>v("global"),disabled:!!C&&M!=="global",children:"Global"}),o.jsx("button",{type:"button",className:`${uu(p==="agent")} h-10 px-3 text-sm font-medium transition`,onClick:()=>v("agent"),disabled:!!C&&M!=="agent",children:"Agent"})]})]}):null,Z?o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Agent"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"agent help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"写入所选 agent 的私有 env"})]})})]}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:pe.get(S)||"选择目标 agent"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[16rem]",children:l.map(W=>{const X=String(W.id||"").trim(),G=String(W.name||W.id||"").trim()||X;return X?o.jsxs(bt,{onClick:()=>j(X),children:[S===X?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{className:"truncate",title:X,children:G})]},X):null})})]})]}):null,te||H==="manual"?o.jsxs("div",{className:"space-y-4 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs(qt,{className:"text-xs text-muted-foreground",children:["Key ",o.jsx("span",{className:"text-destructive",children:"*"})]}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"key help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"使用标准环境变量格式,如 `OPENAI_API_KEY`"})]})})]}),o.jsx(lt,{placeholder:"OPENAI_API_KEY",className:"h-10 rounded-[12px]",value:m,onChange:W=>h(to(W.target.value))}),!ie&&B?o.jsx("div",{className:"text-[11px] text-destructive",children:"Key 格式不合法"}):null]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Description"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"description help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"描述这个环境变量的用途,`city keys` 会读取这里"})]})})]}),o.jsx(lt,{placeholder:"例如:MinerU 服务 API Key",className:"h-10 rounded-[12px]",value:w,onChange:W=>b(W.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Value"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"value help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"留空会保存为空字符串"})]})})]}),o.jsx(jf,{placeholder:C?"输入新的 value 覆盖当前值":"env value",className:"min-h-[112px] rounded-[12px]",value:x,onChange:W=>y(W.target.value)})]})]}):null,!te&&H==="clipboard"?o.jsxs("div",{className:"space-y-3 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"剪贴板"}),o.jsx("div",{className:"mt-1 text-[11px] leading-5 text-muted-foreground",children:"支持粘贴标准 `.env` 文本。"})]}),o.jsx(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[10px] px-3",onClick:Y,disabled:P==="clipboard:read",children:P==="clipboard:read"?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}),"检测中"]}):"重新读取"})]}),o.jsx("div",{className:"rounded-[12px] bg-background px-3 py-2 text-[11px] text-muted-foreground",children:p==="agent"?`导入到 Agent · ${pe.get(S)||"未选择"}`:"导入到 Global"}),o.jsx("div",{className:"rounded-[12px] bg-background px-3 py-2",children:o.jsx("pre",{className:"max-h-[140px] overflow-auto whitespace-pre-wrap break-all font-mono text-[11px] leading-5 text-muted-foreground",children:I||"剪贴板内容会显示在这里。"})}),k?E.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-sm text-foreground",children:["检测到 ",E.length," 个 env 键"]}),o.jsx("div",{className:"flex flex-wrap gap-2",children:E.map(W=>o.jsx("span",{className:"inline-flex h-7 items-center rounded-full bg-background px-3 font-mono text-xs text-foreground",children:W},W))})]}):o.jsx("div",{className:"text-sm text-muted-foreground",children:"当前剪贴板不是有效的 `.env` 文本,请先复制类似 `KEY=value` 的内容。"}):o.jsx("div",{className:"text-sm text-muted-foreground",children:"正在读取剪贴板..."})]}):null]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>N(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:te||H==="manual"?!ie||a||P.startsWith("save:"):!se||a||P==="import:submit"||P==="clipboard:read",onClick:()=>{if(!te&&H==="clipboard"){ae();return}ue()},children:P.startsWith("save:")?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}),"保存中..."]}):P==="import:submit"?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}),"导入中..."]}):!te&&H==="clipboard"?"确认导入":C?"保存":"创建"})]})]})})]})}const yI=["openai","anthropic","deepseek","gemini","open-compatible","open-responses","moonshot-cn","moonshot-ai","kimi-code","xai","huggingface","openrouter"];function N0(e){const t=String(e||"").trim();if(!t)return"-";const n=Date.parse(t);return!Number.isFinite(n)||Number.isNaN(n)?"-":new Date(n).toLocaleString("zh-CN",{hour12:!1})}function vI(e){return String(e||"").trim()}function wI(e,t){return t?`${t}${e}`:e}function T0(e){return o.jsx("button",{type:"button",className:`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${Vn}`,onClick:e.onClick,disabled:e.disabled||e.loading,title:e.label,"aria-label":e.label,children:e.loading?o.jsx(nt,{className:"size-4 animate-spin"}):e.icon})}function Yr(e){return o.jsx("button",{type:"button",className:`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${e.danger?Ro:Vn}`,onClick:e.onClick,disabled:e.disabled||e.loading,title:e.label,"aria-label":e.label,children:e.loading?o.jsx(nt,{className:"size-3.5 animate-spin"}):e.icon})}function SI(e){const{model:t,providers:n,poolItems:s,loading:r,onUpsertProvider:a,onRemoveProvider:i,onTestProvider:l,onDiscoverProvider:u,onUpsertModel:d,onRemoveModel:f,onPauseModel:g,onTestModel:m}=e,h=Ls(),[x,y]=c.useState({id:"",type:"openai",baseUrl:"",apiKey:"",hasExistingApiKey:!1,apiKeyMasked:""}),[w,b]=c.useState({id:"",providerId:"",name:"",temperature:"",maxTokens:"",topP:"",frequencyPenalty:"",presencePenalty:"",anthropicVersion:""}),[p,v]=c.useState(""),[S,j]=c.useState(""),[C,A]=c.useState(""),[M,O]=c.useState(!1),[P,$]=c.useState(!1),[z,N]=c.useState(!1),[H,R]=c.useState("Reply with exactly: OK"),[I,T]=c.useState(""),[E,q]=c.useState(!1),[k,D]=c.useState(""),[B,Q]=c.useState(""),[Z,te]=c.useState(""),[se,ie]=c.useState([]),[oe,pe]=c.useState([]),[_,Y]=c.useState({}),le=c.useCallback(F=>!!_[F],[_]),ne=c.useCallback(async(F,K)=>{Y(he=>({...he,[F]:!0}));try{await K()}finally{Y(he=>({...he,[F]:!1}))}},[]),ue=c.useMemo(()=>n.map(F=>String(F.id||"").trim()).filter(Boolean),[n]),ae=c.useMemo(()=>new Set(s.map(F=>String(F.id||"").trim()).filter(Boolean)),[s]),xe=c.useMemo(()=>{const F=p.trim().toLowerCase();return F?n.filter(K=>{const he=String(K.id||"").toLowerCase(),Te=String(K.type||"").toLowerCase(),Se=String(K.baseUrl||"").toLowerCase();return he.includes(F)||Te.includes(F)||Se.includes(F)}):n},[p,n]),ee=c.useMemo(()=>{const F=S.trim().toLowerCase();return F?s.filter(K=>{const he=String(K.id||"").toLowerCase(),Te=String(K.providerId||"").toLowerCase(),Se=String(K.name||"").toLowerCase();return he.includes(F)||Te.includes(F)||Se.includes(F)}):s},[S,s]),W=c.useMemo(()=>se.map(F=>{const K=vI(F);if(!K)return null;const he=wI(K,Z),Te=ae.has(he),Se=oe.includes(K);return{remoteName:K,targetModelId:he,exists:Te,checked:Se}}).filter(F=>!!F),[Z,se,ae,oe]),X=c.useMemo(()=>{const F=k.trim().toLowerCase();return F?W.filter(K=>K.remoteName.toLowerCase().includes(F)||K.targetModelId.toLowerCase().includes(F)):W},[k,W]),G=c.useMemo(()=>X.filter(F=>!F.exists),[X]),L=c.useMemo(()=>G.map(F=>F.remoteName),[G]),J=L.length>0&&L.every(F=>oe.includes(F)),me=x.id.trim().length>0&&x.type.trim().length>0,ge=w.id.trim().length>0&&w.providerId.trim().length>0&&w.name.trim().length>0,U=c.useCallback(()=>{y({id:"",type:"openai",baseUrl:"",apiKey:"",hasExistingApiKey:!1,apiKeyMasked:""})},[]),ce=c.useCallback(()=>{b({id:"",providerId:"",name:"",temperature:"",maxTokens:"",topP:"",frequencyPenalty:"",presencePenalty:"",anthropicVersion:""})},[]);return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Providers",description:"配置可用的模型 Provider,支持自定义 baseUrl 与 API Key。",actions:o.jsxs(o.Fragment,{children:[o.jsx(lt,{value:p,onChange:F=>v(F.target.value),placeholder:"筛选 provider",className:"w-[220px]"}),o.jsx(lt,{placeholder:"发现前缀",value:C,onChange:F=>A(F.target.value),className:"w-40"}),o.jsx(T0,{label:"新增 Provider",icon:o.jsx(fa,{className:"size-4"}),onClick:()=>{U(),O(!0)},disabled:r})]}),children:xe.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-3 py-3 text-sm text-muted-foreground",children:"没有 provider"}):o.jsx("div",{className:"space-y-2",children:xe.map(F=>{const K=String(F.id||"").trim();return K?o.jsxs("article",{className:"group flex flex-col gap-3 rounded-[16px] bg-transparent px-3 py-3 transition-colors hover:bg-secondary lg:flex-row lg:items-center lg:justify-between",children:[o.jsx("div",{className:"min-w-0 flex-1 text-[11px] text-muted-foreground",children:o.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[o.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:K}),o.jsx("span",{className:"rounded-full bg-secondary px-2 py-0.5 text-[11px] text-muted-foreground",children:F.type||"-"}),o.jsx("span",{className:"truncate",title:F.baseUrl||"",children:F.baseUrl||"-"}),o.jsx("span",{children:F.hasApiKey?F.apiKeyMasked||"configured":"empty"}),o.jsx("span",{children:N0(F.updatedAt)})]})}),o.jsxs("div",{className:"inline-flex items-center gap-1 opacity-100 transition-opacity lg:opacity-0 lg:group-hover:opacity-100 lg:group-focus-within:opacity-100",children:[o.jsx(Yr,{label:"编辑",icon:o.jsx(hd,{className:"size-3.5"}),onClick:()=>{y({id:K,type:String(F.type||"openai"),baseUrl:String(F.baseUrl||""),apiKey:"",hasExistingApiKey:F.hasApiKey===!0,apiKeyMasked:String(F.apiKeyMasked||"")}),O(!0)}}),o.jsx(Yr,{label:"测试",icon:o.jsx(sa,{className:"size-3.5"}),onClick:()=>{ne(`provider:test:${K}`,async()=>{await Promise.resolve(l(K))})},loading:le(`provider:test:${K}`)}),o.jsx(Yr,{label:"发现",icon:o.jsx(Ym,{className:"size-3.5"}),onClick:()=>{ne(`provider:discover:${K}`,async()=>{const he=C.trim(),Te=await Promise.resolve(u({providerId:K,autoAdd:!1,prefix:he||void 0}));if(!Te)return;const Se=Array.isArray(Te.discoveredModels)?Te.discoveredModels:[];Q(K),te(he),ie(Se),D(""),pe([]),q(!0)})},loading:le(`provider:discover:${K}`)}),o.jsx(Yr,{label:"删除",icon:o.jsx(er,{className:"size-3.5"}),onClick:()=>{(async()=>await h({title:"删除 Provider",description:`确认删除 provider「${K}」吗?关联模型也可能受影响。`,confirmText:"删除",confirmVariant:"destructive"})&&await ne(`provider:delete:${K}`,async()=>{await Promise.resolve(i(K))}))()},loading:le(`provider:delete:${K}`),danger:!0})]})]},K):null})})}),o.jsx(wt,{title:"Models",description:`current ${String((t==null?void 0:t.agentPrimaryModelId)||"-")} · provider ${String((t==null?void 0:t.providerType)||"-")} · providers ${n.length} · models ${s.length}`,actions:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:`${ee.length} items`}),o.jsx(lt,{value:S,onChange:F=>j(F.target.value),placeholder:"筛选 model",className:"w-[220px]"}),o.jsx(T0,{label:"新增 Model",icon:o.jsx(fa,{className:"size-4"}),onClick:()=>{ce(),$(!0)},disabled:r}),n.length>0&&o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",size:"sm",className:"inline-flex items-center gap-1.5 h-8 rounded-[11px] px-3",disabled:r}),children:[o.jsx(Ym,{className:"size-3.5"}),o.jsx("span",{className:"text-xs",children:"发现并添加"}),o.jsx(kr,{className:"size-3"})]}),o.jsx(wn,{className:"min-w-[14rem]",children:n.map(F=>{const K=String(F.id||"").trim();return K?o.jsxs(bt,{onClick:()=>{ne(`provider:discover:${K}`,async()=>{const he=C.trim(),Te=await Promise.resolve(u({providerId:K,autoAdd:!1,prefix:he||void 0}));if(!Te)return;const Se=Array.isArray(Te.discoveredModels)?Te.discoveredModels:[];Q(K),te(he),ie(Se),D(""),pe([]),q(!0)})},children:[o.jsx("span",{children:K}),o.jsx("span",{className:"ml-auto text-[11px] text-muted-foreground",children:F.type||"-"})]},K):null})})]})]}),children:ee.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-3 py-3 text-sm text-muted-foreground",children:"没有 model"}):o.jsx("div",{className:"space-y-2",children:ee.map(F=>{const K=String(F.id||"").trim();if(!K)return null;const he=F.isPaused===!0;return o.jsxs("article",{className:"group flex flex-col gap-3 rounded-[16px] bg-transparent px-3 py-3 transition-colors hover:bg-secondary lg:flex-row lg:items-center lg:justify-between",children:[o.jsx("div",{className:"min-w-0 flex-1 text-[11px] text-muted-foreground",children:o.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[o.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:K}),o.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] ${he?"bg-secondary text-muted-foreground":"bg-emerald-500/12 text-emerald-700"}`,children:[o.jsx("span",{className:`size-1.5 rounded-full ${he?"bg-muted-foreground/70":"bg-emerald-600"}`}),o.jsx("span",{children:he?"paused":"active"})]}),o.jsx("span",{children:F.providerId||"-"}),o.jsx("span",{className:"truncate",children:F.name||"-"}),o.jsx("span",{children:`temp ${F.temperature??"-"}`}),o.jsx("span",{children:`max ${F.maxTokens??"-"}`}),o.jsx("span",{children:`topP ${F.topP??"-"}`}),o.jsx("span",{children:N0(F.updatedAt)})]})}),o.jsxs("div",{className:"inline-flex items-center gap-1 opacity-100 transition-opacity lg:opacity-0 lg:group-hover:opacity-100 lg:group-focus-within:opacity-100",children:[o.jsx(Yr,{label:"编辑",icon:o.jsx(hd,{className:"size-3.5"}),onClick:()=>{b({id:K,providerId:String(F.providerId||""),name:String(F.name||""),temperature:F.temperature===void 0?"":String(F.temperature),maxTokens:F.maxTokens===void 0?"":String(F.maxTokens),topP:F.topP===void 0?"":String(F.topP),frequencyPenalty:F.frequencyPenalty===void 0?"":String(F.frequencyPenalty),presencePenalty:F.presencePenalty===void 0?"":String(F.presencePenalty),anthropicVersion:String(F.anthropicVersion||"")}),$(!0)}}),o.jsx(Yr,{label:"测试",icon:o.jsx(sa,{className:"size-3.5"}),onClick:()=>{T(K),N(!0)}}),o.jsx(Yr,{label:he?"恢复":"暂停",icon:he?o.jsx(sa,{className:"size-3.5"}):o.jsx(Nw,{className:"size-3.5"}),onClick:()=>{ne(`model:pause:${K}`,async()=>{await Promise.resolve(g(K,!he))})},loading:le(`model:pause:${K}`)}),o.jsx(Yr,{label:"删除",icon:o.jsx(er,{className:"size-3.5"}),onClick:()=>{(async()=>await h({title:"删除 Model",description:`确认删除模型「${K}」吗?该操作不可恢复。`,confirmText:"删除",confirmVariant:"destructive"})&&await ne(`model:delete:${K}`,async()=>{await Promise.resolve(f(K))}))()},loading:le(`model:delete:${K}`),danger:!0})]})]},K)})})}),o.jsx($n,{open:E,onOpenChange:q,children:o.jsxs(Un,{className:"w-[min(92vw,720px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"发现模型"}),o.jsx(os,{children:"从 provider 拉取可用模型,并按需添加到本地模型池。"})]}),se.length===0?o.jsx("div",{className:"px-4 pb-2 text-sm text-muted-foreground",children:"未发现可用模型"}):o.jsx("div",{className:"max-h-[58vh] space-y-3 overflow-auto px-4 pb-2",children:o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-[18px] bg-secondary/85 px-3 py-2.5 text-xs text-muted-foreground",children:[o.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[o.jsx("span",{children:`provider ${B||"-"}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`prefix ${Z||"(none)"}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`发现 ${W.length}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`可添加 ${W.filter(F=>!F.exists).length}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`已选 ${oe.length}`})]}),o.jsx("div",{className:"text-[11px]",children:`当前结果 ${X.length} 项`})]}),o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"flex flex-col gap-2 rounded-[14px] bg-transparent px-2 py-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("div",{className:"relative min-w-0 flex-1",children:[o.jsx(Wl,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{value:k,onChange:F=>D(F.target.value),placeholder:"搜索模型名或目标 ID",className:"h-10 border-0 bg-background pl-9 shadow-none"})]}),o.jsx(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[11px] px-3",disabled:L.length===0,onClick:()=>pe(F=>{if(J)return F.filter(he=>!L.includes(he));const K=new Set(F);return L.forEach(he=>K.add(he)),Array.from(K)}),children:J?"取消全选":"全选结果"}),o.jsx(be,{type:"button",size:"sm",variant:"ghost",className:"h-8 rounded-[11px] px-3",disabled:oe.length===0,onClick:()=>pe([]),children:"清空"})]}),X.length===0?o.jsx("div",{className:"rounded-[14px] bg-transparent px-3 py-6 text-center text-sm text-muted-foreground",children:"没有匹配的模型"}):o.jsx("div",{className:"space-y-1",children:X.map(F=>o.jsxs("label",{className:Me("flex items-center justify-between gap-3 rounded-[14px] px-3 py-2.5 text-sm transition-colors",F.exists?"bg-transparent opacity-65":"cursor-pointer bg-transparent hover:bg-background"),children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(m6,{checked:F.checked,disabled:F.exists,className:"size-4 rounded-[5px]",onCheckedChange:K=>{pe(he=>K?he.includes(F.remoteName)?he:[...he,F.remoteName]:he.filter(Te=>Te!==F.remoteName))}}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:F.remoteName}),o.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:F.targetModelId})]})]}),o.jsx("div",{className:"shrink-0 text-[11px] text-muted-foreground",children:F.exists?"已存在":F.checked?"已选中":"可添加"})]},`discover:${F.remoteName}`))})]})})]})}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>q(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:oe.length===0||r||le("discover:add"),onClick:()=>{ne("discover:add",async()=>{for(const F of oe){const K=String(F||"").trim();if(!K)continue;const he=Z?`${Z}${K}`:K;ae.has(he)||await Promise.resolve(d({id:he,providerId:B,name:K}))}q(!1)})},children:le("discover:add")?"添加中...":"添加选中"})]})]})}),o.jsx($n,{open:M,onOpenChange:O,children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"Provider"}),o.jsx(os,{className:"sr-only",children:"Provider editor dialog"})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-3 overflow-y-auto px-4 pb-2",children:[o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Provider"}),o.jsx(lt,{placeholder:"provider id",className:"h-10 rounded-[12px]",value:x.id,onChange:F=>y(K=>({...K,id:F.target.value}))}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:x.type||"provider type"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:yI.map(F=>o.jsxs(bt,{onClick:()=>y(K=>({...K,type:F})),children:[x.type===F?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:F})]},F))})]})]}),o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Connection"}),o.jsx(lt,{placeholder:"base url (optional)",className:"h-10 rounded-[12px]",value:x.baseUrl,onChange:F=>y(K=>({...K,baseUrl:F.target.value}))}),o.jsx(lt,{placeholder:x.hasExistingApiKey?"留空保留当前 API Key":"api key (optional)",className:"h-10 rounded-[12px]",value:x.apiKey,onChange:F=>y(K=>({...K,apiKey:F.target.value}))}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:x.hasExistingApiKey?`已配置:${x.apiKeyMasked||"configured"}`:"未配置 API Key"})]})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>O(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!me||r||le("provider:save"),onClick:()=>{ne("provider:save",async()=>{await Promise.resolve(a({id:x.id.trim(),type:x.type.trim(),baseUrl:x.baseUrl.trim()||void 0,apiKey:x.apiKey||void 0})),O(!1)})},children:le("provider:save")?"保存中...":"保存"})]})]})}),o.jsx($n,{open:z,onOpenChange:N,children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"测试 Model"}),o.jsx(os,{className:"sr-only",children:"Model test dialog"})]}),o.jsxs("div",{className:"space-y-3 overflow-y-auto px-4 pb-2",children:[o.jsx("div",{className:"rounded-[18px] bg-secondary px-3 py-2 text-xs text-muted-foreground",children:`model ${I||"-"}`}),o.jsx(jf,{className:"min-h-[112px] rounded-[12px]",value:H,onChange:F=>R(F.target.value),placeholder:"输入测试 prompt"})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>N(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!I||r||le(`model:test:${I}`),onClick:()=>{ne(`model:test:${I}`,async()=>{await Promise.resolve(m(I,H)),N(!1)})},children:le(`model:test:${I}`)?"测试中...":"运行测试"})]})]})}),o.jsx($n,{open:P,onOpenChange:$,children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"Model"}),o.jsx(os,{className:"sr-only",children:"Model editor dialog"})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-3 overflow-y-auto px-4 pb-2",children:[o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Model"}),o.jsx(lt,{placeholder:"model id",className:"h-10 rounded-[12px]",value:w.id,onChange:F=>b(K=>({...K,id:F.target.value}))}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:w.providerId||"provider"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:ue.map(F=>o.jsxs(bt,{onClick:()=>b(K=>({...K,providerId:F})),children:[w.providerId===F?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:F})]},F))})]}),o.jsx(lt,{placeholder:"upstream model name",className:"h-10 rounded-[12px]",value:w.name,onChange:F=>b(K=>({...K,name:F.target.value}))})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(lt,{placeholder:"temperature",className:"h-10 rounded-[12px]",value:w.temperature,onChange:F=>b(K=>({...K,temperature:F.target.value}))}),o.jsx(lt,{placeholder:"max tokens",className:"h-10 rounded-[12px]",value:w.maxTokens,onChange:F=>b(K=>({...K,maxTokens:F.target.value}))}),o.jsx(lt,{placeholder:"top p",className:"h-10 rounded-[12px]",value:w.topP,onChange:F=>b(K=>({...K,topP:F.target.value}))}),o.jsx(lt,{placeholder:"anthropic version",className:"h-10 rounded-[12px]",value:w.anthropicVersion,onChange:F=>b(K=>({...K,anthropicVersion:F.target.value}))}),o.jsx(lt,{placeholder:"frequency penalty",className:"col-span-2 h-10 rounded-[12px]",value:w.frequencyPenalty,onChange:F=>b(K=>({...K,frequencyPenalty:F.target.value}))}),o.jsx(lt,{placeholder:"presence penalty",className:"col-span-2 h-10 rounded-[12px]",value:w.presencePenalty,onChange:F=>b(K=>({...K,presencePenalty:F.target.value}))})]})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>$(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!ge||r||le("model:save"),onClick:()=>{ne("model:save",async()=>{await Promise.resolve(d({id:w.id.trim(),providerId:w.providerId.trim(),name:w.name.trim(),temperature:w.temperature,maxTokens:w.maxTokens,topP:w.topP,frequencyPenalty:w.frequencyPenalty,presencePenalty:w.presencePenalty,anthropicVersion:w.anthropicVersion})),$(!1)})},children:le("model:save")?"保存中...":"保存"})]})]})})]})}function oa(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function wx(e){const t=e.detail;return oa(t)?t:void 0}function jI(e){const t=wx(e);if(!t)return{};const n=t.config;return oa(n)?n:{}}function CI(e){const t=String(e||"").trim().toLowerCase();return t==="string"||t==="boolean"||t==="number"||t==="secret"||t==="enum"?t:"string"}function kI(e){const t=String(e||"").trim().toLowerCase();return t==="ship_json"||t==="bot_account"||t==="env_fallback"?t:"ship_json"}function NI(e){if(!Array.isArray(e))return;const t=e.map(n=>{if(!oa(n))return null;const s=String(n.value||"").trim();if(!s)return null;const r=String(n.label||s).trim()||s,a=String(n.description||"").trim();return{value:s,label:r,description:a}}).filter(n=>!!n);return t.length>0?t:void 0}function TI(e){if(!oa(e))return null;const t=String(e.key||"").trim();if(!t)return null;const n=String(e.label||t).trim()||t,s=String(e.description||"").trim(),r=CI(e.type);return{key:t,label:n,description:s,type:r,source:kI(e.source),required:e.required===!0,nullable:e.nullable===!0,writable:e.writable===!0,restartRequired:e.restartRequired===!0,defaultValue:typeof e.defaultValue=="string"||typeof e.defaultValue=="number"||typeof e.defaultValue=="boolean"||e.defaultValue===null?e.defaultValue:void 0,example:typeof e.example=="string"||typeof e.example=="number"||typeof e.example=="boolean"||e.example===null?e.example:void 0,options:NI(e.options)}}function Pg(e){return Array.isArray(e)?e.map(t=>TI(t)).filter(t=>!!t):[]}function AI(e){const t=wx(e);if(!t)return null;const n=t.configuration;if(!oa(n))return null;const s=oa(n.fields)?n.fields:{};return{channel:String(n.channel||e.channel||"").trim(),title:String(n.title||`${String(e.channel||"").trim()} Configuration`).trim(),description:String(n.description||"").trim(),version:String(n.version||"1.0.0").trim(),capabilities:oa(n.capabilities)?{canToggleEnabled:n.capabilities.canToggleEnabled===!0,canBindChannelAccount:n.capabilities.canBindChannelAccount===!0,canConfigure:n.capabilities.canConfigure===!0}:void 0,fields:{ship:Pg(s.ship),channelAccount:Pg(s.channelAccount),envFallback:Pg(s.envFallback)}}}const EI={feishu:"https://downcity.ai/zh/docs/services/chat/feishu"};function _a(e){return String(e||"").trim()||null}function $j(e){const t=String(e.chatTitle||"").trim(),n=String(e.chatId||"").trim();return t&&(!n||t!==n)?{value:t,source:"title"}:n?{value:n,source:"chat_id"}:{value:String(e.sessionId||"").trim()||"unknown",source:"session_id"}}function MI(e){const t=$j(e);return JSON.stringify({sessionId:_a(e.sessionId),channel:_a(ma(e)),chatId:_a(e.chatId),chatTitle:_a(e.chatTitle),chatDisplayName:_a(t.value),chatDisplayNameSource:t.source,chatType:_a(e.chatType),threadId:typeof e.threadId=="number"&&Number.isFinite(e.threadId)?e.threadId:null},null,2)}function RI(e){const{sessions:t,chatChannels:n,channelAccounts:s,selectedSessionId:r,focusedChannel:a,formatTime:i,onOpenSession:l,onDeleteSession:u,deletingSessionId:d,onChatAction:f,onChatConfigure:g}=e,m=Ls(),[h,x]=c.useState(""),[y,w]=c.useState("all"),b=String(a||"").trim().toLowerCase(),p=c.useMemo(()=>b?t.filter(k=>ma(k)===b):[],[t,b]),v=c.useMemo(()=>b?n.filter(k=>String(k.channel||"").trim().toLowerCase()===b):[],[n,b]),S=Oz(p,h),C=zj(S).filter(k=>y==="all"?!0:k.key===y).flatMap(k=>k.items),A=v[0]||null,M=String((A==null?void 0:A.channel)||"").trim(),O=bx(M),P=String((A==null?void 0:A.linkState)||"unknown").trim().toLowerCase(),$=c.useMemo(()=>{if(!A)return;const k=wx(A);return k||void 0},[A]),z=c.useMemo(()=>A?jI(A):{},[A]),N=c.useMemo(()=>A?AI(A):null,[A]),H=c.useMemo(()=>{var k;return A?M==="consoleui"||($==null?void 0:$.readonly)===!0||((k=N==null?void 0:N.capabilities)==null?void 0:k.canConfigure)===!1:!1},[A,M,N,$]),R=c.useMemo(()=>String(z.channelAccountId||"").trim(),[z]),I=c.useMemo(()=>{const k=String(M||"").trim().toLowerCase();return!k||k==="consoleui"?[]:s.filter(D=>String(D.channel||"").trim().toLowerCase()===k)},[M,s]),T=c.useMemo(()=>{const k=String(M||"").trim().toLowerCase();return k&&EI[k]||null},[M]),E=c.useMemo(()=>{if(!R)return"config";const k=I.find(D=>String(D.id||"").trim()===R);return k&&String(k.name||k.id||"config").trim()||"config"},[R,I]),q=c.useCallback(k=>{if(!M||H)return;const D=String(k||"").trim(),B=D==="__none__"?"":D;B!==R&&g(M,{channelAccountId:B||null})},[R,M,H,g]);return o.jsxs("div",{className:"space-y-5",children:[A?o.jsx(wt,{title:"Channel Runtime",description:`当前 channel:${O||"unknown"} · account ${E}`,children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 px-1 py-1",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-xl font-semibold leading-none text-foreground",children:O||"unknown"}),M==="qq"?o.jsx("div",{className:"mt-2 rounded-[12px] border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-xs leading-5 text-amber-950",children:"QQ channel 当前为 dev 版本,建议仅用于测试与验证。"}):null,o.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:`size-1.5 rounded-full ${P==="connected"?"bg-emerald-500":P==="disconnected"||P==="error"?"bg-destructive":"bg-muted-foreground/60"}`}),o.jsx("span",{children:`link ${P||"-"}`})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[M!=="consoleui"?o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{size:"sm",variant:"outline",className:"h-8 min-w-[9.5rem] max-w-[12rem] justify-between gap-1 px-2.5 text-[11px]",disabled:H}),children:[o.jsx("span",{className:"truncate",children:E}),o.jsx(kr,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),o.jsxs(wn,{className:"min-w-[12rem]",children:[o.jsxs(bt,{onClick:()=>q("__none__"),children:[R?o.jsx("span",{className:"inline-block w-4"}):o.jsx(Ws,{className:"size-4"}),o.jsx("span",{children:"no binding"})]}),I.map(k=>{const D=String(k.id||"").trim();if(!D)return null;const B=String(k.name||"").trim()||D,Q=D===R;return o.jsxs(bt,{onClick:()=>q(D),children:[Q?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{className:"truncate",children:B})]},D)})]})]}):null,o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||A.enabled===!0,onClick:()=>f("open",M),children:"open"}),o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||A.enabled!==!0,onClick:()=>f("close",M),children:"close"}),o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||!(A.enabled===!0&&A.configured===!0),onClick:()=>f("test",M),children:"test"}),o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||!(A.enabled===!0&&A.configured===!0),onClick:()=>f("reconnect",M),children:"reconnect"})]})]}),T?o.jsx("div",{className:"flex items-center justify-start px-1 pb-1",children:o.jsxs("a",{href:T,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[o.jsx("span",{children:"查看飞书接入文档"}),o.jsx(r5,{className:"size-3"})]})}):null]})}):o.jsx(wt,{title:"Channel Runtime",description:"当前 channel 暂无状态。",children:o.jsx("section",{className:"rounded-[18px] bg-secondary px-3.5 py-5 text-sm text-muted-foreground",children:"当前 channel 暂无状态"})}),o.jsx(wt,{title:"Sessions",description:`当前筛选结果 ${C.length} 条。`,actions:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:`total ${C.length}`}),o.jsx(lt,{value:h,onChange:k=>x(k.target.value),placeholder:"搜索 session",className:"w-[220px]"}),o.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:["all","chat","api","other"].map(k=>o.jsx(be,{type:"button",size:"sm",variant:y===k?"default":"outline",className:"px-2 text-xs",onClick:()=>w(k),children:k},k))})]}),children:C.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-4 py-5 text-sm text-muted-foreground",children:"当前筛选条件下无 session"}):o.jsx("div",{className:"space-y-2",children:C.map(k=>{const D=Oj(k),B=k.sessionId===r,Q=String(d||"").trim()===k.sessionId,Z=k.executing===!0,te=$j(k),se=te.value,ie=MI(k),oe=String(k.chatId||"").trim(),pe=String(k.chatType||"").trim();return o.jsx("article",{className:B?"rounded-[20px] bg-secondary px-4 py-3":"rounded-[20px] bg-transparent px-4 py-3 transition-colors hover:bg-secondary",children:o.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",title:`${se}
|
|
423
|
-
${k.sessionId}`,children:se}),o.jsx("div",{className:"mt-1 truncate font-mono text-[11px] text-muted-foreground/85",children:k.sessionId}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-[10px] text-muted-foreground/90",children:[o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5 uppercase tracking-[0.08em]",children:D}),o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5 uppercase tracking-[0.08em]",children:te.source}),pe?o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5 uppercase tracking-[0.08em]",children:pe}):null,o.jsx("span",{className:`rounded-full px-1.5 py-0.5 uppercase tracking-[0.08em] ${Z?"bg-primary/12 text-primary":"bg-background text-muted-foreground"}`,children:Z?"executing":"idle"}),o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5",children:`${k.messageCount||0} msgs`}),o.jsx("span",{children:i(k.updatedAt)}),oe?o.jsx("span",{className:"max-w-[10rem] truncate font-mono",title:oe,children:oe}):null]}),o.jsx("div",{className:"mt-2 truncate text-xs text-muted-foreground",title:k.lastText||"",children:`${k.lastRole||"unknown"} · ${k.lastText||"(empty)"}`})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 lg:justify-end",children:[o.jsxs(yj,{children:[o.jsxs(vj,{render:o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]"}),children:[o.jsx(WA,{className:"size-3.5"}),o.jsx("span",{children:"Route"})]}),o.jsxs(wj,{align:"end",className:"w-[min(92vw,34rem)] overflow-hidden p-0",children:[o.jsx("div",{className:"bg-secondary px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:"context route json"}),o.jsx("pre",{className:"max-h-[320px] overflow-auto whitespace-pre-wrap break-words bg-background/85 px-3 py-3 font-mono text-[11px] leading-relaxed text-foreground/85",children:ie})]})]}),o.jsx(be,{size:"sm",variant:B?"secondary":"outline",className:"h-8 px-2.5",onClick:()=>l(k.sessionId),children:B?"已打开":"打开"}),o.jsxs(be,{size:"sm",variant:"destructive",className:"h-8 px-2.5",disabled:!!d,onClick:async()=>{await m({title:"删除 Session",description:`确认彻底删除 session「${k.sessionId}」吗?该操作不可恢复。`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"})&&u(k.sessionId)},children:[o.jsx(er,{className:"size-3.5"}),o.jsx("span",{children:Q?"删除中...":"删除"})]})]})]})},k.sessionId)})})})]})}function La(e){return String(e||"").trim()||null}function Uj(e){const t=String(e||""),n=t.match(/<info>([\s\S]*?)<\/info>/i),s=n?String(n[1]||"").trim():"";return{text:t.replace(/<info>[\s\S]*?<\/info>/gi,"").trim()||"(empty)",info:s}}function OI(e){const t=String(e.role||"unknown").trim(),n=String(e.toolName||"").trim();return(t==="tool-call"||t==="tool-result")&&n?`${t} · ${n}`:t||"unknown"}function zI(e){const t=String(e||"unknown").trim();return t==="tool-call"?{cardClassName:"border border-border/70 bg-secondary/88 shadow-[inset_0_1px_0_rgba(255,255,255,0.52)] dark:bg-muted/58",roleBadgeClassName:"bg-foreground text-background dark:bg-foreground dark:text-background",toolBadgeClassName:"bg-background/92 text-foreground ring-1 ring-border/70 dark:bg-background/70 dark:ring-border/80",textClassName:"font-mono text-[10px] leading-[1.6] text-foreground/96"}:t==="tool-result"?{cardClassName:"border border-border/55 bg-background shadow-[inset_0_1px_0_rgba(255,255,255,0.34)] dark:bg-background/88",roleBadgeClassName:"bg-secondary text-foreground/86 dark:bg-secondary dark:text-foreground/86",toolBadgeClassName:"bg-secondary/82 text-foreground/78 ring-1 ring-border/60 dark:bg-muted/72 dark:ring-border/70",textClassName:"font-mono text-[10px] leading-[1.6] text-foreground/82"}:t==="user"?{cardClassName:"border border-border/55 bg-secondary/42",roleBadgeClassName:"bg-secondary text-foreground/78",toolBadgeClassName:"bg-secondary text-muted-foreground",textClassName:"text-[10px] leading-[1.55] text-foreground/92"}:{cardClassName:"border border-border/45 bg-background",roleBadgeClassName:"bg-secondary text-foreground/78",toolBadgeClassName:"bg-secondary text-muted-foreground",textClassName:"text-[10px] leading-[1.55] text-foreground/90"}}function Hj(e){const t=String(e.chatTitle||"").trim(),n=String(e.chatId||"").trim();return t&&(!n||t!==n)?{value:t,source:"title"}:n?{value:n,source:"chat_id"}:{value:String(e.sessionId||"").trim()||"unknown",source:"session_id"}}function II(e){const t=Hj({chatTitle:e.chatTitle,chatId:e.chatId,sessionId:e.selectedSessionId});return JSON.stringify({sessionId:La(e.selectedSessionId),channel:La(e.channel),chatId:La(e.chatId),chatTitle:La(e.chatTitle),chatDisplayName:La(t.value),chatDisplayNameSource:t.source,chatType:La(e.chatType),threadId:typeof e.threadId=="number"&&Number.isFinite(e.threadId)?e.threadId:null},null,2)}function DI(e){const t=Array.isArray(e==null?void 0:e.sections)?e.sections:[];if(t.length===0)return[];const n=t.filter(r=>{const a=String(r.key||"").trim().toLowerCase(),i=String(r.title||"").trim().toLowerCase();return a.includes("system")||a.includes("profile")||i.includes("system")||i.includes("profile")});return(n.length>0?n:t.slice(0,2)).flatMap(r=>{const a=String(r.title||r.key||"section").trim()||"section",i=Array.isArray(r.items)?r.items:[];return i.length===0?[{title:a,content:""}]:i.map((l,u)=>{const d=String(l.content||"").trim();return{title:typeof l.index=="number"&&Number.isFinite(l.index)?`${a} · #${l.index}`:`${a} · ${u+1}`,content:d}})})}function _I(e){const{events:t,formatTime:n}=e,s=c.useRef(null),r=c.useRef(!0),a=c.useRef(0);return c.useLayoutEffect(()=>{const i=s.current;if(!i)return;t.length>a.current&&r.current&&(i.scrollTop=i.scrollHeight),a.current=t.length},[t]),o.jsx("div",{ref:s,className:"h-full min-h-0 space-y-2 overflow-y-auto px-2 py-2",onScroll:i=>{const l=i.currentTarget,u=l.scrollHeight-l.scrollTop-l.clientHeight;r.current=u<=48},children:t.length===0?o.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"暂无 chat history"}):t.map((i,l)=>{const d=String(i.direction||"unknown")==="inbound",f=i,g=String(f.actorName||f.username||f.userName||f.senderName||f.displayName||f.fromName||f.from||"").trim(),m=d?g||"user":"agent",h=Uj(String(i.text||"")),x=i.ts?n(i.ts):String(i.isoTime||"").trim()||"-";return o.jsxs("article",{className:Me("rounded-[16px] px-3 py-2.5",d?"bg-background":"bg-secondary"),children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[o.jsx("span",{className:"truncate font-medium uppercase tracking-[0.08em]",children:m}),o.jsx("span",{className:"shrink-0 font-mono text-[10px]",children:x})]}),o.jsx("div",{className:"whitespace-pre-wrap break-words text-[11px] leading-[1.5] text-foreground",children:h.text}),h.info?o.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer select-none",children:"info"}),o.jsx("pre",{className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1 font-mono text-[11px] leading-relaxed text-foreground/80",children:h.info})]}):null]},`${String(i.id||"evt")}:${String(i.ts||"na")}:${l}`)})})}function Fj(e){const{items:t,formatTime:n}=e;return o.jsx("div",{className:"h-full min-h-0 space-y-2 overflow-y-auto px-3 py-3",children:t.length===0?o.jsx("div",{className:"py-8 text-center text-xs text-muted-foreground",children:"暂无 session messages"}):t.map((s,r)=>{const a=String(s.role||"unknown"),i=OI({role:a,toolName:s.toolName}),l=zI(a),u=String(s.toolName||"").trim(),d=Uj(String(s.text||"")),f=n(s.ts);return o.jsxs("article",{className:Me("rounded-[16px] px-3 py-2.5",l.cardClassName),children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:Me("inline-flex h-5 max-w-full items-center rounded-full px-2 text-[10px] font-semibold uppercase tracking-[0.1em]",l.roleBadgeClassName),title:i,children:o.jsx("span",{className:"truncate",children:a})}),u?o.jsx("span",{className:Me("inline-flex h-5 max-w-[min(52vw,16rem)] items-center rounded-full px-2 font-mono text-[10px]",l.toolBadgeClassName),title:u,children:o.jsx("span",{className:"truncate",children:u})}):null]}),o.jsx("span",{className:"shrink-0 font-mono text-[10px]",children:f})]}),o.jsx("div",{className:Me("whitespace-pre-wrap break-words",l.textClassName),children:d.text}),d.info?o.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer select-none",children:"info"}),o.jsx("pre",{className:"mt-1 max-h-32 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1 font-mono text-[11px] leading-relaxed text-foreground/80",children:d.info})]}):null]},`${s.id||a}-${r}`)})})}function LI(e){return o.jsx("div",{className:"h-full min-h-0 overflow-hidden px-3 py-3",children:o.jsx("pre",{className:"h-full overflow-auto whitespace-pre-wrap break-words rounded-[16px] bg-secondary/85 px-3 py-3 font-mono text-xs leading-relaxed text-foreground/85",children:e.routeJson})})}function BI(e){const{blocks:t}=e;return o.jsx("div",{className:"h-full min-h-0 overflow-y-auto px-3 py-3",children:t.length===0?o.jsx("div",{className:"py-8 text-center text-xs text-muted-foreground",children:"暂无 system 内容"}):o.jsx("div",{className:"space-y-3",children:t.map((n,s)=>o.jsxs("section",{className:"rounded-[18px] border border-border/45 bg-secondary/85 px-3 py-3",children:[o.jsx("div",{className:"border-b border-border/40 pb-2 text-xs font-medium text-foreground/85",children:n.title}),o.jsx("div",{className:"pt-3",children:o.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-foreground/85",children:n.content||"(empty)"})})]},`${n.title}-${s}`))})})}function PI(e){const{archives:t,selectedArchiveId:n,archiveMessages:s,formatTime:r,onSelectArchive:a,onRefreshArchives:i}=e;return o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[220px_minmax(0,1fr)]",children:[o.jsxs("div",{className:"flex min-h-0 flex-col rounded-l-[18px] bg-secondary/85",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/45 px-3 py-2",children:[o.jsxs("div",{className:"inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:[o.jsx(PA,{className:"size-3.5"}),o.jsx("span",{children:"compact archives"})]}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"size-7 rounded-md",onClick:i,"aria-label":"刷新 archive",title:"刷新 archive",children:o.jsx(xc,{className:"size-3.5"})})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 pb-2",children:t.length===0?o.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"暂无 compact archive"}):o.jsx("div",{className:"space-y-1",children:t.map((l,u)=>{const d=String(l.archiveId||"").trim();if(!d)return null;const f=d===n,g=Number(l.messageCount||0);return o.jsxs("button",{type:"button",className:Me("w-full rounded-[14px] px-2.5 py-2 text-left text-xs transition-colors",f?"bg-background text-foreground":"text-muted-foreground hover:bg-background hover:text-foreground"),onClick:()=>a(d),children:[o.jsx("div",{className:"truncate font-mono text-[11px]",title:d,children:d}),o.jsxs("div",{className:"mt-0.5 flex items-center justify-between gap-2 text-[10px]",children:[o.jsx("span",{children:`${g} msgs`}),o.jsx("span",{className:"truncate",title:r(l.archivedAt),children:r(l.archivedAt)})]})]},`${d}-${u}`)})})})]}),o.jsx("div",{className:"min-h-0 overflow-hidden rounded-r-[18px] bg-background/55",children:n?o.jsx(Fj,{items:s,formatTime:r}):o.jsx("div",{className:"flex h-full items-center justify-center px-4 text-xs text-muted-foreground",children:"请选择左侧 archive 查看 compact 前的历史消息"})})]})}function $I(e){const t=String(e.state||"unknown").trim().toLowerCase(),n=t==="connected"?"bg-primary/12 text-primary":t==="disconnected"||t==="error"?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground";return o.jsxs("div",{className:Me("inline-flex items-center gap-1 rounded-full px-2 py-1 text-[11px]",n),children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",t==="connected"?"bg-primary":"bg-current")}),o.jsx("span",{children:t||"unknown"})]})}function UI(e){const{selectedSessionId:t,sessions:n,channelHistory:s,chatChannels:r,sessionMessages:a,sessionArchives:i,selectedArchiveId:l,sessionArchiveMessages:u,prompt:d,chatInput:f,debugPanelsCollapsed:g,sending:m,clearingSessionMessages:h,clearingChatHistory:x,deletingSession:y,formatTime:w,onChangeInput:b,onSendConsoleUiMessage:p,onClearSessionMessages:v,onClearChatHistory:S,onDeleteSession:j,onRefreshArchives:C,onSelectArchive:A}=e,M=Ls(),[O,P]=c.useState("route"),$=c.useMemo(()=>n.find(k=>String(k.sessionId||"").trim()===t)||null,[n,t]),z=c.useMemo(()=>{const k=ma($||t);return k==="other"?"unknown":k},[$,t]),N=z==="consoleui",H=($==null?void 0:$.executing)===!0,R=c.useMemo(()=>{if(z==="consoleui")return"connected";if(z==="unknown")return"unknown";const k=r.find(D=>String(D.channel||"").trim().toLowerCase()===z);return String((k==null?void 0:k.linkState)||"unknown")},[r,z]),I=c.useMemo(()=>Hj({chatTitle:$==null?void 0:$.chatTitle,chatId:$==null?void 0:$.chatId,sessionId:t}),[$,t]),T=c.useMemo(()=>II({selectedSessionId:t,channel:z,chatId:$==null?void 0:$.chatId,chatTitle:$==null?void 0:$.chatTitle,chatType:$==null?void 0:$.chatType,threadId:$==null?void 0:$.threadId}),[z,$,t]),E=c.useMemo(()=>DI(d),[d]),q=c.useCallback(async()=>{await M({title:"删除 Chat",description:`确认彻底删除 session「${t}」吗?该操作不可恢复。`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"})&&j()},[M,j,t]);return c.useEffect(()=>{P("route")},[t]),t?o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 xl:flex-row",children:[o.jsxs("section",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[22px] bg-background ring-1 ring-border/70 shadow-[0_1px_0_rgba(17,17,19,0.03)]",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 border-b border-border/55 px-4 py-4",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-base font-semibold text-foreground",title:I.value,children:I.value}),o.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",title:t,children:t}),o.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:`source: ${I.source}`})]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full bg-secondary px-2 py-1 text-[11px] text-muted-foreground",children:[o.jsx("span",{className:"font-mono",children:z}),o.jsx("span",{children:`${s.length} msgs`})]}),o.jsxs("div",{className:Me("inline-flex items-center gap-1 rounded-full px-2 py-1 text-[11px]",H?"bg-primary/12 text-primary":"bg-secondary text-muted-foreground"),children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",H?"bg-primary":"bg-muted-foreground/60")}),o.jsx("span",{children:H?"executing":"idle"})]}),o.jsx($I,{state:R}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[11px] px-2.5 text-[11px]",disabled:y||h||x}),children:[o.jsx(kw,{className:"size-3.5"}),o.jsx("span",{children:"操作"})]}),o.jsxs(wn,{align:"end",className:"w-48",children:[o.jsx(bt,{disabled:h,onClick:v,children:h?"清理 context 中...":"清理 session messages"}),o.jsx(bt,{disabled:x,onClick:S,children:x?"清理 history 中...":"清理 chat history"}),o.jsx(Md,{}),o.jsx(bt,{variant:"destructive",disabled:y,onClick:()=>{q()},children:y?"删除中...":"删除 chat"})]})]})]})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:o.jsx(_I,{events:s,formatTime:w})}),o.jsxs("div",{className:"border-t border-border/55 px-4 py-4",children:[o.jsx(jf,{value:f,onChange:k=>b(k.target.value),onKeyDown:k=>{(k.metaKey||k.ctrlKey)&&k.key==="Enter"&&(k.preventDefault(),!(!N||m||!f.trim())&&p())},rows:3,placeholder:N?"输入发给 consoleui channel 的消息...":"当前 session 为只读,仅 consoleui channel 可发送",disabled:!N,className:"min-h-[84px] resize-y rounded-[14px] bg-secondary/85 text-[11px] focus-visible:bg-secondary"}),o.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[o.jsx("div",{className:"text-[11px] text-muted-foreground",children:N?"Cmd/Ctrl + Enter 发送":"只读模式"}),o.jsx(be,{onClick:p,disabled:!N||m||!f.trim(),children:m?"发送中...":"发送"})]})]})]}),g?null:o.jsxs("aside",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden rounded-[22px] bg-background ring-1 ring-border/70 shadow-[0_1px_0_rgba(17,17,19,0.03)] xl:w-[min(40%,560px)] xl:min-w-[340px]",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/55 px-4 py-4",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground",children:"details"}),o.jsxs("div",{className:"inline-flex rounded-[12px] bg-secondary p-0.5",children:[o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="route"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("route"),children:"route"}),o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="system"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("system"),children:"system"}),o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="context"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("context"),children:"context"}),o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="archive"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("archive"),children:"archive"})]})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:O==="route"?o.jsx(LI,{routeJson:T}):O==="system"?o.jsx(BI,{blocks:E}):O==="context"?o.jsx(Fj,{items:a,formatTime:w}):o.jsx(PI,{archives:i,selectedArchiveId:l,archiveMessages:u,formatTime:w,onSelectArchive:A,onRefreshArchives:C})})]})]}):o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"请选择一个 context 进入工作区"})}function Kr(e,t){return e.some(n=>String(n.name||"").trim()===t)}function _u(e){const t=String(e.state||"").trim().toLowerCase();return t==="disabled"?"disabled":t==="available"?"enabled":"attention"}function A0(e){return _u(e)!=="disabled"}function HI(e){return e==="enabled"?{cardClass:"border-border/70 bg-background",badgeLabel:"Enabled",badgeClass:"bg-emerald-500/10 text-emerald-700",dotClass:"bg-emerald-600"}:e==="disabled"?{cardClass:"border-border/65 bg-[color-mix(in_oklab,var(--background)_96%,var(--secondary)_4%)]",badgeLabel:"Disabled",badgeClass:"bg-secondary text-muted-foreground",dotClass:"bg-muted-foreground/45"}:{cardClass:"border-amber-200/80 bg-[color-mix(in_oklab,var(--background)_95%,oklch(0.95_0.02_85)_5%)]",badgeLabel:"Setup required",badgeClass:"bg-amber-500/10 text-amber-700",dotClass:"bg-amber-500"}}function du(e){const{icon:t,label:n,loading:s,disabled:r=!1,tone:a="default",onClick:i}=e;return o.jsxs("button",{type:"button",onClick:i,disabled:r||s,className:`inline-flex h-8 items-center gap-1.5 rounded-full border border-transparent px-2.5 text-[12px] transition-colors disabled:pointer-events-none disabled:opacity-50 ${a==="danger"?"text-red-600 hover:border-red-200 hover:bg-red-50 hover:text-red-700":"text-muted-foreground hover:border-border/60 hover:bg-background hover:text-foreground"}`,children:[s?o.jsx(nt,{className:"size-3.5 animate-spin"}):t,o.jsx("span",{children:n})]})}function FI(e,t){const n=t&&typeof t=="object"?t:null,s=n!=null&&n.plugin&&typeof n.plugin=="object"?n.plugin:null,r=n!=null&&n.transcriber&&typeof n.transcriber=="object"?n.transcriber:null,a={...s||{},...r||{}},i={};for(const l of(e==null?void 0:e.fields)||[]){const u=a[l.key];if(l.type==="checkbox"){i[l.key]=u===!0;continue}if(typeof u=="string"&&u.trim()){i[l.key]=u.trim();continue}if(Array.isArray(l.options)&&l.options.length>0){i[l.key]=l.options[0].value;continue}i[l.key]=""}return i}function qI(e,t){const n=t&&typeof t=="object"?t:null,s=Array.isArray(n==null?void 0:n.options)?n.options:Array.isArray(n==null?void 0:n.models)?n.models:[],r=[];for(const a of s){const i=a&&typeof a=="object"?a:null,l=String((i==null?void 0:i.value)||(i==null?void 0:i.id)||"").trim();l&&r.push({label:String((i==null?void 0:i.label)||l).trim()||l,value:l,hint:String((i==null?void 0:i.hint)||(i==null?void 0:i.description)||"").trim()||void 0})}return r}function GI(e,t){const n={};for(const s of(e==null?void 0:e.fields)||[]){const r=t[s.key];if(s.type==="checkbox"){n[s.key]=r===!0;continue}typeof r=="string"&&r.trim()&&(n[s.key]=r.trim())}if((e==null?void 0:e.primaryAction)==="install"){const s=typeof n.modelId=="string"?n.modelId:"";s&&(n.modelIds=[s],n.activeModel=s)}return n}function VI(e,t){return e==="install"?t?"修复安装":"重新安装":e==="configure"?"保存配置":t?"修复并更新配置":"更新安装配置"}function YI(e,t){const n=t&&typeof t=="object"?t:null,s=n!=null&&n.plugin&&typeof n.plugin=="object"?n.plugin:n,r={};for(const a of(e==null?void 0:e.fields)||[]){const i=s==null?void 0:s[a.key];if(a.type==="boolean"){r[a.key]=i===!0;continue}if(typeof i=="string"&&i.trim()){r[a.key]=i.trim();continue}if(typeof i=="number"&&Number.isFinite(i)){r[a.key]=String(i);continue}if(Array.isArray(a.options)&&a.options.length>0){r[a.key]=a.options[0].value;continue}r[a.key]=""}return r}function KI(e,t){const n=t&&typeof t=="object"?t:null,s=Array.isArray(n==null?void 0:n.options)?n.options:Array.isArray(n==null?void 0:n.models)?n.models:[],r=[];for(const a of s){const i=a&&typeof a=="object"?a:null,l=String((i==null?void 0:i.value)||(i==null?void 0:i.id)||"").trim();l&&r.push({label:String((i==null?void 0:i.label)||l).trim()||l,value:l,description:String((i==null?void 0:i.description)||(i==null?void 0:i.hint)||"").trim()||void 0})}return r}function XI(e,t){const n={};for(const s of(e==null?void 0:e.fields)||[]){const r=t[s.key];if(s.type==="boolean"){n[s.key]=r===!0;continue}const a=typeof r=="string"?r.trim():"";if(a){if(s.type==="number"){const i=Number(a);Number.isFinite(i)&&(n[s.key]=i);continue}n[s.key]=a}}return n}function E0(e){var oe,pe;const{scope:t,plugins:n,onRunAction:s}=e,r=t==="agent"?e.hasRunningAgent:!1,a=t==="agent"?e.selectedAgentName:void 0,i=Ls(),[l,u]=c.useState(""),[d,f]=c.useState({}),[g,m]=c.useState({}),[h,x]=c.useState({}),[y,w]=c.useState({}),[b,p]=c.useState({}),[v,S]=c.useState({}),[j,C]=c.useState({}),[A,M]=c.useState({}),[O,P]=c.useState(""),[$,z]=c.useState("");c.useEffect(()=>{m(_=>{let Y=!1;const le={..._};for(const ne of n){const ue=String(ne.name||"").trim();if(!ue)continue;const ae=le[ue];ae!==void 0&&ae===A0(ne)&&(delete le[ue],Y=!0)}return Y?le:_})},[n]);const N=c.useMemo(()=>{const _=l.trim().toLowerCase();return n.filter(Y=>_?String(Y.name||"").toLowerCase().includes(_)||String(Y.title||"").toLowerCase().includes(_)||String(Y.description||"").toLowerCase().includes(_):!0)},[n,l]),H=c.useMemo(()=>{let _=0,Y=0,le=0;for(const ne of N){const ue=_u(ne);ue==="enabled"?_+=1:ue==="disabled"?Y+=1:le+=1}return{enabled:_,disabled:Y,attention:le}},[N]),R=c.useMemo(()=>n.find(_=>String(_.name||"").trim()===O)||null,[n,O]),I=c.useMemo(()=>n.find(_=>String(_.name||"").trim()===$)||null,[n,$]),T=c.useCallback(async(_,Y,le,ne)=>{const ue=Date.now();f(ae=>({...ae,[_]:Y}));try{const ae=await s(_,le,ne);if(Array.isArray(ae==null?void 0:ae.logs)&&M(xe=>({...xe,[_]:ae.logs||[]})),Y==="toggle"){const xe=le==="on";ae.success&&m(W=>({...W,[_]:xe}));const ee=Date.now()-ue;ee<220&&await new Promise(W=>window.setTimeout(W,220-ee))}return ae}finally{f(ae=>({...ae,[_]:null}))}},[s]),E=c.useCallback(async _=>{var ue,ae,xe;const Y=String(_.name||"").trim(),le=Array.isArray((ue=_.config)==null?void 0:ue.actions)?(ae=_.config)==null?void 0:ae.actions:[],ne=(xe=_.config)==null?void 0:xe.setup;if(!(!Y||!ne)){if(ne.statusAction&&Kr(le,ne.statusAction)){const ee=await T(Y,"status",ne.statusAction);ee!=null&&ee.success&&w(W=>({...W,[Y]:{...W[Y]||{},...FI(ne,ee.data)}}))}for(const ee of ne.fields){if(!ee.sourceAction||!Kr(le,ee.sourceAction))continue;const W=await T(Y,"setupOptions",ee.sourceAction);if(!(W!=null&&W.success))continue;const X=qI(ee,W.data);p(G=>({...G,[Y]:{...G[Y]||{},[ee.key]:X}})),w(G=>{const L={...G[Y]||{}};return ee.type==="select"&&typeof L[ee.key]!="string"&&X.length>0&&(L[ee.key]=X[0].value),ee.type==="select"&&!L[ee.key]&&X.length>0&&(L[ee.key]=X[0].value),{...G,[Y]:L}})}}},[T]),q=c.useCallback(async _=>{var ue,ae,xe;const Y=String(_.name||"").trim(),le=Array.isArray((ue=_.config)==null?void 0:ue.actions)?(ae=_.config)==null?void 0:ae.actions:[],ne=(xe=_.config)==null?void 0:xe.usage;if(!(!Y||!ne)){if(ne.statusAction&&Kr(le,ne.statusAction)){const ee=await T(Y,"status",ne.statusAction);ee!=null&&ee.success&&S(W=>({...W,[Y]:{...W[Y]||{},...YI(ne,ee.data)}}))}for(const ee of ne.fields){if(!ee.sourceAction||!Kr(le,ee.sourceAction))continue;const W=await T(Y,"usageOptions",ee.sourceAction);if(!(W!=null&&W.success))continue;const X=KI(ee,W.data);C(G=>({...G,[Y]:{...G[Y]||{},[ee.key]:X}})),S(G=>{const L={...G[Y]||{}};return ee.type==="select"&&typeof L[ee.key]!="string"&&X.length>0&&(L[ee.key]=X[0].value),ee.type==="select"&&!L[ee.key]&&X.length>0&&(L[ee.key]=X[0].value),{...G,[Y]:L}})}}},[T]),k=c.useCallback(_=>{var le;const Y=String(_.name||"").trim();!Y||!((le=_.config)!=null&&le.setup)||(P(Y),M(ne=>({...ne,[Y]:[]})),E(_))},[E]),D=c.useCallback(()=>{P("")},[]),B=c.useCallback(_=>{var le;const Y=String(_.name||"").trim();!Y||!((le=_.config)!=null&&le.usage)||(z(Y),q(_))},[q]),Q=c.useCallback(()=>{z("")},[]),Z=c.useCallback((_,Y,le)=>{w(ne=>({...ne,[_]:{...ne[_]||{},[Y]:le}}))},[]),te=c.useCallback((_,Y,le)=>{S(ne=>({...ne,[_]:{...ne[_]||{},[Y]:le}}))},[]),se=c.useCallback(async()=>{var xe,ee;if(!((xe=R==null?void 0:R.config)!=null&&xe.setup))return;const _=String(R.name||"").trim(),Y=R.config.setup,le=y[_]||{},ne=GI(Y,le),ue=Y.primaryAction,ae=await T(_,"setup",ue,ne);(ee=ae==null?void 0:ae.logs)!=null&&ee.length||M(W=>({...W,[_]:[ae!=null&&ae.success?"操作完成":(ae==null?void 0:ae.message)||"操作失败"]})),Y.statusAction&&await E(R),D()},[D,T,R,y,E]),ie=c.useCallback(async()=>{var ue;if(!((ue=I==null?void 0:I.config)!=null&&ue.usage))return;const _=String(I.name||"").trim(),Y=I.config.usage,le=v[_]||{},ne=XI(Y,le);await T(_,"usage",Y.saveAction,ne),Y.statusAction&&await q(I),Q()},[Q,T,q,v,I]);return o.jsxs(o.Fragment,{children:[o.jsx(wt,{title:"Plugins",description:`enabled ${H.enabled} · disabled ${H.disabled}${H.attention>0?` · attention ${H.attention}`:""}`,bodyClassName:"min-h-0 overflow-y-auto",actions:o.jsxs("div",{className:"relative w-[220px]",children:[o.jsx(Wl,{className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{value:l,onChange:_=>u(_.target.value),placeholder:"搜索 plugin",className:"pl-9"})]}),children:t==="agent"&&!r&&N.length===0?o.jsx("div",{className:"rounded-[18px] border border-border/70 bg-secondary/45 px-4 py-6 text-sm text-muted-foreground",children:a?`${a} 当前未运行,Console UI 无法读取 runtime plugins。先启动 agent 再查看。`:"当前没有运行中的 agent,Console UI 无法读取 runtime plugins。先启动 agent 再查看。"}):N.length===0?o.jsx("div",{className:"rounded-[18px] border border-border/70 bg-secondary/45 px-4 py-6 text-sm text-muted-foreground",children:"当前没有匹配的 plugin。"}):o.jsx("div",{className:"space-y-3",children:N.map(_=>{var jt,Ct,zt,Ce,rt,et;const Y=String(_.name||"unknown").trim()||"unknown",le=String(_.title||Y).trim()||Y,ne=String(_.description||"").trim(),ue=Array.isArray((jt=_.config)==null?void 0:jt.actions)?(Ct=_.config)==null?void 0:Ct.actions:[],ae=(zt=_.config)==null?void 0:zt.setup,xe=(Ce=_.config)==null?void 0:Ce.usage,ee=_u(_),W=g[Y]??A0(_),X=d[Y]||null,G=X==="toggle",L=X==="status",J=X==="doctor",me=X==="setup",ge=X==="usage",U=X==="setupOptions",ce=X==="usageOptions",F=Kr(ue,"status"),K=Kr(ue,"doctor"),he=Kr(ue,"on"),Te=Kr(ue,"off"),Se=he||Te,Fe=HI(W?ee==="attention"?"attention":"enabled":"disabled"),Re=(Array.isArray((rt=_.availability)==null?void 0:rt.reasons)?(et=_.availability)==null?void 0:et.reasons:[]).map($e=>String($e||"").trim()).filter(Boolean).join(" · "),Ye=h[Y]===!0,yt=Array.isArray(_.pipelines)?_.pipelines:[],De=Array.isArray(_.guards)?_.guards:[],ot=Array.isArray(_.effects)?_.effects:[],_e=Array.isArray(_.resolves)?_.resolves:[],Je=ue.map($e=>String($e.name||"").trim()).filter(Boolean);return o.jsxs("article",{className:Me("rounded-[20px] border px-4 py-4 shadow-[0_1px_0_rgba(17,17,19,0.02)] transition-colors",Fe.cardClass),children:[o.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:Me("inline-flex size-2 rounded-full",Fe.dotClass)}),o.jsx("div",{className:"min-w-0 truncate text-[15px] font-semibold tracking-[-0.02em] text-foreground",children:le}),o.jsx("span",{className:"inline-flex h-6 items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-muted-foreground",children:Y}),o.jsx("span",{className:Me("inline-flex h-6 items-center rounded-full px-2.5 text-[11px]",Fe.badgeClass),children:Fe.badgeLabel})]}),ne?o.jsx("div",{className:"mt-2 max-w-3xl text-[13px] leading-6 text-foreground/70",children:ne}):null,Re?o.jsx("div",{className:"mt-3 text-[12px] leading-5 text-muted-foreground",children:Re}):null]}),o.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-1 rounded-full bg-secondary/70 p-1 lg:justify-end",children:[t==="global"&&ae?o.jsx(du,{icon:o.jsx(pd,{className:"size-3.5"}),label:ee==="attention"?"修复":"安装",loading:me||U,disabled:G||L||J||ge||ce,onClick:()=>k(_)}):null,t==="agent"&&xe?o.jsx(du,{icon:o.jsx(pd,{className:"size-3.5"}),label:"选项",loading:ge||ce,disabled:G||L||J||me||U,onClick:()=>B(_)}):null,t==="agent"&&F?o.jsx(du,{icon:o.jsx(xc,{className:"size-3.5"}),label:"同步",loading:L,disabled:G||J||me||U||ge||ce,onClick:()=>{T(Y,"status","status")}}):null,t==="global"&&Se?o.jsx(du,{icon:o.jsx(M5,{className:"size-3.5"}),label:W?"停用":"启用",loading:G,disabled:L||J||me||U||ge||ce,tone:W?"danger":"default",onClick:()=>{if((W?"off":"on")==="off"){(async()=>await i({title:"关闭 Plugin",description:`确认关闭 "${Y}"?`,confirmText:"关闭",confirmVariant:"destructive"})&&await T(Y,"toggle","off"))();return}T(Y,"toggle","on")}}):null,o.jsxs("button",{type:"button",className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-transparent px-2.5 text-[12px] text-muted-foreground transition-colors hover:border-border/60 hover:bg-background hover:text-foreground",onClick:()=>x($e=>({...$e,[Y]:!Ye})),children:[o.jsx(kr,{className:Me("size-3.5 transition-transform",Ye?"rotate-180":"")}),o.jsx("span",{children:Ye?"收起":"详情"})]})]})]}),Ye?o.jsx("div",{className:"mt-4 border-t border-border/60 pt-4",children:o.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto]",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.12em] text-muted-foreground",children:"Hooks"}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:[...yt,...De,...ot,..._e].length>0?o.jsxs(o.Fragment,{children:[yt.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`pipeline · ${$e}`},`${Y}:pipeline:${$e}`)),De.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`guard · ${$e}`},`${Y}:guard:${$e}`)),ot.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`effect · ${$e}`},`${Y}:effect:${$e}`)),_e.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`resolve · ${$e}`},`${Y}:resolve:${$e}`))]}):o.jsx("span",{className:"text-[12px] text-muted-foreground",children:"未声明额外 hooks。"})})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.12em] text-muted-foreground",children:"Actions"}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:Je.length>0?Je.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:$e},`${Y}:action:${$e}`)):o.jsx("span",{className:"text-[12px] text-muted-foreground",children:"未暴露额外 actions。"})})]})]}),t==="agent"&&K?o.jsx("div",{className:"flex items-start",children:o.jsxs(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[12px] px-3",disabled:G||L||me||U||ge||ce,onClick:()=>{T(Y,"doctor","doctor")},children:[J?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(Ew,{className:"size-3.5"}),o.jsx("span",{children:"Doctor"})]})}):null]})}):null]},Y)})})}),o.jsx($n,{open:!!R,onOpenChange:_=>{_||D()},children:o.jsx(Un,{className:"w-[min(92vw,560px)] overflow-hidden border border-border/75 bg-background p-0 shadow-[0_24px_72px_rgba(17,17,19,0.12)]",children:(oe=R==null?void 0:R.config)!=null&&oe.setup?o.jsxs(o.Fragment,{children:[o.jsxs(Hn,{className:"border-b border-border/60 px-5 py-4",children:[o.jsx(Fn,{children:R.config.setup.title}),o.jsx(os,{className:"max-w-[40ch] text-[12px] leading-5 text-muted-foreground",children:R.config.setup.description||"使用统一 setup 流程完成插件安装或配置。"})]}),o.jsx("div",{className:"space-y-4 px-5 py-5",children:(()=>{var W,X,G;const _=String(R.name||"").trim(),Y=(W=R.config)==null?void 0:W.setup,le=d[_]==="setup"||d[_]==="status"||d[_]==="setupOptions",ne=_u(R),ue=Array.isArray((X=R.availability)==null?void 0:X.reasons)?(G=R.availability)==null?void 0:G.reasons:[],ae=y[_]||{},xe=b[_]||{},ee=A[_]||[];return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-[16px] bg-secondary/55 px-4 py-3",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:String(R.title||_)}),o.jsx("div",{className:"mt-1 text-[12px] leading-5 text-muted-foreground",children:ne==="attention"?ue.join(" · ")||"当前插件需要修复或补全运行环境。":"当前插件已可用,可在这里更新配置。"})]}),o.jsx("div",{className:"space-y-4",children:Y.fields.map(L=>{var ge,U,ce;if(L.type==="checkbox")return o.jsxs("label",{className:"flex items-center gap-2 rounded-[14px] bg-secondary/55 px-3 py-2 text-[12px] text-foreground",children:[o.jsx("input",{type:"checkbox",checked:ae[L.key]===!0,onChange:F=>Z(_,L.key,F.target.checked)}),o.jsx("span",{children:L.label})]},`${_}:field:${L.key}`);const J=Array.isArray(xe[L.key])&&xe[L.key].length>0?xe[L.key]:Array.isArray(L.options)?L.options:[],me=typeof ae[L.key]=="string"?String(ae[L.key]||""):((ge=J[0])==null?void 0:ge.value)||"";return o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{htmlFor:`${_}:${L.key}`,children:L.label}),o.jsx("select",{id:`${_}:${L.key}`,value:me,onChange:F=>Z(_,L.key,F.target.value),className:"flex h-10 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none transition-colors focus:border-ring",children:J.map(F=>o.jsx("option",{value:F.value,children:F.label},`${_}:${L.key}:${F.value}`))}),(U=J.find(F=>F.value===me))!=null&&U.hint?o.jsx("div",{className:"text-[12px] text-muted-foreground",children:(ce=J.find(F=>F.value===me))==null?void 0:ce.hint}):null]},`${_}:field:${L.key}`)})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-muted-foreground",children:"安装日志"}),o.jsxs("div",{className:"max-h-48 overflow-y-auto rounded-[14px] border border-border/70 bg-secondary/35 px-3 py-2 font-mono text-[11px] leading-5 text-foreground/82",children:[le?o.jsx("div",{children:"正在执行,请稍候..."}):null,ee.length>0?ee.map((L,J)=>o.jsx("div",{children:L},`${_}:log:${J}`)):le?null:o.jsx("div",{className:"text-muted-foreground",children:"执行完成后会在这里显示安装过程与错误信息。"})]})]}),o.jsxs(rs,{className:"border-t border-border/60 px-0 pt-4 sm:justify-end",children:[o.jsx(be,{type:"button",variant:"outline",onClick:D,disabled:le,children:"取消"}),o.jsxs(be,{type:"button",disabled:le||Y.fields.some(L=>{var J;return L.required!==!0||L.type==="checkbox"?!1:!String(((J=y[_])==null?void 0:J[L.key])||"").trim()}),onClick:()=>void se(),children:[le?o.jsx(nt,{className:"size-4 animate-spin"}):null,o.jsx("span",{children:VI(Y.mode,ne==="attention")})]})]})]})})()})]}):null})}),o.jsx($n,{open:!!I,onOpenChange:_=>{_||Q()},children:o.jsx(Un,{className:"w-[min(92vw,560px)] overflow-hidden border border-border/75 bg-background p-0 shadow-[0_24px_72px_rgba(17,17,19,0.12)]",children:(pe=I==null?void 0:I.config)!=null&&pe.usage?o.jsxs(o.Fragment,{children:[o.jsxs(Hn,{className:"border-b border-border/60 px-5 py-4",children:[o.jsx(Fn,{children:I.config.usage.title}),o.jsx(os,{className:"max-w-[40ch] text-[12px] leading-5 text-muted-foreground",children:I.config.usage.description||"配置当前 agent 如何使用这个 plugin。"})]}),o.jsx("div",{className:"space-y-4 px-5 py-5",children:(()=>{var ae;const _=String(I.name||"").trim(),Y=(ae=I.config)==null?void 0:ae.usage,le=d[_]==="usage"||d[_]==="status"||d[_]==="usageOptions",ne=v[_]||{},ue=j[_]||{};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-[16px] bg-secondary/55 px-4 py-3",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:String(I.title||_)}),o.jsx("div",{className:"mt-1 text-[12px] leading-5 text-muted-foreground",children:"这里修改的是 agent 运行时如何使用该 plugin,不负责依赖安装或资源修复。"})]}),o.jsx("div",{className:"space-y-4",children:Y.fields.map(xe=>{var X;const ee=Array.isArray(ue[xe.key])&&ue[xe.key].length>0?ue[xe.key]:Array.isArray(xe.options)?xe.options:[],W=xe.type==="boolean"?ne[xe.key]===!0:typeof ne[xe.key]=="string"?String(ne[xe.key]||""):((X=ee[0])==null?void 0:X.value)||"";return o.jsx(Pj,{field:{key:xe.key,label:xe.label,type:xe.type,placeholder:xe.placeholder,description:xe.description,required:xe.required,disabled:xe.disabled||le,trueLabel:xe.trueLabel,falseLabel:xe.falseLabel,options:ee.map(G=>({value:G.value,label:G.label,description:G.description}))},value:W,onChange:G=>te(_,xe.key,G)},`${_}:usage:${xe.key}`)})}),o.jsxs(rs,{className:"border-t border-border/60 px-0 pt-4 sm:justify-end",children:[o.jsx(be,{type:"button",variant:"outline",onClick:Q,disabled:le,children:"取消"}),o.jsxs(be,{type:"button",disabled:le||Y.fields.some(xe=>{var ee;return xe.required!==!0||xe.type==="boolean"?!1:!String(((ee=v[_])==null?void 0:ee[xe.key])||"").trim()}),onClick:()=>void ie(),children:[le?o.jsx(nt,{className:"size-4 animate-spin"}):null,o.jsx("span",{children:"保存选项"})]})]})]})})()})]}):null})})]})}function M0(e){return{projectRoot:"",agentName:"",executionType:e?"api":"acp",agentType:"kimi",modelId:e,localModel:""}}function $g(e){const t=String(e||"").trim().replace(/[\\/]+$/,"");if(!t)return"selected-folder";const n=t.split(/[\\/]/).filter(Boolean);return n[n.length-1]||t}function R0(e){if(e.executionMode==="api")return{executionType:"api",agentType:"kimi"};if(e.executionMode==="local")return{executionType:"local",agentType:"kimi"};const t=String(e.agentType||"").trim();return t==="claude"||t==="codex"?{executionType:"acp",agentType:t}:{executionType:"acp",agentType:"kimi"}}function ZI(e){return e.executionType==="api"?e.selectedModelLabel||"-":e.executionType==="local"?`Local · ${e.selectedLocalModelLabel||"-"}`:`ACP · ${e.agentType}`}function JI(e){return e.executionMode==="api"?String(e.modelId||"").trim()||"-":e.executionMode==="local"?`local ${String(e.localModel||"-").trim()||"-"}`:`acp ${String(e.agentType||"-").trim()||"-"}`}function QI(e,t){const n=new Set,s=String(t||"").trim();s&&n.add(s);for(const r of e){const a=String(r||"").trim();a&&n.add(a)}return Array.from(n)}const WI=c.forwardRef(function(t,n){const{agents:s,modelPoolItems:r,onPickAgentDirectory:a,onInspectAgentDirectory:i,onLoadLocalModels:l,onRestartAgent:u,onStopAgent:d,onStartAgent:f,onStartAgentWithInitialization:g}=t,m=Ls(),[h,x]=c.useState(""),[y,w]=c.useState(""),[b,p]=c.useState(""),[v,S]=c.useState(!1),[j,C]=c.useState(""),[A,M]=c.useState(!1),[O,P]=c.useState(!1),[$,z]=c.useState([]),[N,H]=c.useState(!1),R=c.useMemo(()=>r.filter(_=>_.isPaused!==!0),[r]),I=c.useMemo(()=>{var _,Y;return String(((_=R[0])==null?void 0:_.id)||((Y=r[0])==null?void 0:Y.id)||"").trim()},[R,r]),[T,E]=c.useState(()=>M0(I)),q=c.useCallback(()=>{S(!1),C(""),P(!1),z([]),H(!1),E(M0(I))},[I]),k=c.useCallback(async(_,Y)=>{try{H(!0);const le=await l(_);z(le);const ne=String(Y||"").trim();E(ue=>{const ae=String(ue.localModel||ne||le[0]||"").trim();return ae===ue.localModel?ue:{...ue,localModel:ae}})}finally{H(!1)}},[l]),D=c.useCallback(_=>{C(String(_.agentId||_.projectRoot||"").trim()),E({projectRoot:String(_.projectRoot||"").trim(),agentName:String(_.agentName||"").trim(),...R0({executionMode:_.executionMode,agentType:_.agentType}),modelId:String(_.modelId||I||"").trim(),localModel:String(_.localModel||"").trim()}),S(!0),k(String(_.projectRoot||"").trim(),String(_.localModel||"").trim())},[I,k]),B=c.useCallback(async()=>{try{M(!0);const _=await a();if(!_)return;const Y=await i(_);if(!Y)return;if(Y.initialized){try{x(Y.projectRoot),await Promise.resolve(f(Y.projectRoot))}finally{x("")}return}D({agentId:Y.knownAgent?Y.projectRoot:"",projectRoot:Y.projectRoot,agentName:Y.displayName,executionMode:Y.executionMode,modelId:Y.modelId,localModel:Y.localModel,agentType:Y.agentType})}finally{M(!1)}},[i,a,f,D]);c.useImperativeHandle(n,()=>({openFolder:B}),[B]),c.useEffect(()=>{E(_=>_.modelId||!I?_:{..._,modelId:I})},[I]);const Q=c.useCallback(async()=>{try{M(!0);const _=await a();if(!_)return;const Y=await i(_);if(!Y)return;if(Y.initialized){q();try{x(Y.projectRoot),await Promise.resolve(f(Y.projectRoot))}finally{x("")}return}E(le=>({...le,projectRoot:Y.projectRoot,agentName:Y.displayName||le.agentName,...R0({executionMode:Y.executionMode,agentType:Y.agentType}),modelId:String(Y.modelId||le.modelId||"").trim(),localModel:String(Y.localModel||le.localModel||"").trim()})),k(Y.projectRoot,String(Y.localModel||"").trim())}finally{M(!1)}},[i,a,f,k,q]);c.useEffect(()=>{v&&T.executionType==="local"&&(N||$.length>0||k(T.projectRoot,T.localModel))},[v,T.executionType,T.localModel,T.projectRoot,N,$.length,k]);const Z=!!String(T.projectRoot||"").trim()&&(T.executionType==="api"&&!!String(T.modelId||"").trim()&&R.length>0||T.executionType==="local"&&!!String(T.localModel||"").trim()||T.executionType==="acp"),te=String(T.agentName||"").trim()||$g(T.projectRoot),se=c.useMemo(()=>{const _=R.find(Y=>String(Y.id||"").trim()===String(T.modelId||"").trim());return String((_==null?void 0:_.name)||(_==null?void 0:_.id)||T.modelId||"").trim()},[R,T.modelId]),ie=String(T.localModel||"").trim(),oe=c.useMemo(()=>QI($,ie),[$,ie]),pe=ZI({executionType:T.executionType,agentType:T.agentType,selectedModelLabel:se,selectedLocalModelLabel:ie});return o.jsxs("section",{className:"min-h-0 overflow-y-auto",children:[s.length===0?o.jsx("div",{className:"rounded-[20px] bg-secondary px-4 py-5 text-sm text-muted-foreground",children:"暂无 agent,点击右上角打开文件夹"}):o.jsx("div",{className:"space-y-2",children:s.map(_=>{const Y=_.running===!0,le=JI(_),ne=h===_.id,ue=y===_.id,ae=b===_.id;return o.jsx("article",{className:Y?"rounded-[20px] bg-transparent px-4 py-3 transition-colors hover:bg-secondary":"rounded-[20px] bg-transparent px-4 py-3 text-muted-foreground opacity-58 transition-all hover:bg-secondary hover:opacity-78",children:o.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[o.jsx("div",{className:Y?"mt-0.5 rounded-full bg-emerald-500/12 p-2 text-emerald-700":"mt-0.5 rounded-full bg-secondary/80 p-2 text-muted-foreground",children:o.jsx(zp,{className:"size-4"})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:Y?"truncate text-[15px] font-semibold text-foreground":"truncate text-[15px] font-semibold text-foreground/72",children:_.name||"unknown-agent"}),o.jsx("div",{className:"truncate font-mono text-[11px] text-muted-foreground",children:_.id})]})]}),o.jsxs("div",{className:"flex flex-1 flex-wrap items-center gap-2 lg:justify-end",children:[o.jsx("span",{className:Y?"inline-flex h-7 max-w-full items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-foreground/86":"inline-flex h-7 max-w-full items-center rounded-full bg-secondary/75 px-2.5 font-mono text-[11px] text-foreground/62",children:le}),o.jsx("span",{className:Y?"inline-flex h-7 items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-muted-foreground":"inline-flex h-7 items-center rounded-full bg-secondary/75 px-2.5 font-mono text-[11px] text-muted-foreground",children:`pid ${Y?String(_.daemonPid||"-"):"-"}`}),o.jsx("span",{className:Y?"inline-flex h-7 items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-muted-foreground":"inline-flex h-7 items-center rounded-full bg-secondary/75 px-2.5 font-mono text-[11px] text-muted-foreground",children:`port ${Y?String(_.port||"-"):"-"}`}),o.jsx("div",{className:"ml-auto flex items-center gap-1.5",children:Y?o.jsxs(o.Fragment,{children:[o.jsx(be,{size:"icon",variant:"ghost",className:Vn,onClick:async()=>{try{w(_.id),await Promise.resolve(u(_.id))}finally{w("")}},disabled:ue||ae,"aria-label":"重启",title:"重启",children:ue?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Ip,{className:"size-4"})}),o.jsx(be,{size:"icon",variant:"ghost",className:Ro,onClick:()=>{(async()=>{if(await m({title:"停止 Agent",description:`确认停止 "${_.name||"unknown-agent"}"?停止前会检查当前是否有正在执行的 context 和 task。`,confirmText:"停止",confirmVariant:"destructive"}))try{p(_.id),await Promise.resolve(d(_.id))}finally{p("")}})()},disabled:ue||ae,"aria-label":"停止",title:"停止",children:ae?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Dp,{className:"size-4"})})]}):o.jsx(be,{size:"icon",variant:"ghost",className:Vn,disabled:ne||ue||ae,"aria-label":"启动",title:"启动",onClick:async()=>{try{x(_.id),await Promise.resolve(f(_.id))}finally{x("")}},children:ne?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(sa,{className:"size-4"})})})]})]})},_.id)})}),o.jsx($n,{open:v,onOpenChange:_=>_?S(!0):q(),children:o.jsxs(Un,{className:"w-[min(92vw,640px)] overflow-hidden border border-border/80 bg-[linear-gradient(180deg,rgba(250,250,250,0.98),rgba(246,247,249,0.98))] p-0 shadow-[0_28px_90px_rgba(15,23,42,0.14)]",children:[o.jsxs(Hn,{className:"gap-3 border-b border-border/70 px-5 py-5 sm:px-6",children:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"mt-0.5 rounded-[16px] border border-foreground/8 bg-foreground/[0.03] p-2.5 text-foreground",children:o.jsx(Ym,{className:"size-4"})}),o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx(Fn,{className:"text-[1.05rem] font-semibold tracking-[0.01em]",children:"初始化并启动 Agent"}),o.jsx(os,{className:"max-w-[46ch] text-[12px] leading-5 text-muted-foreground",children:"当前文件夹还没有完成 Downcity 初始化。确认后会补齐运行骨架,再把它接入 Console。"})]})]}),o.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[o.jsxs("div",{className:"rounded-[18px] border border-border/75 bg-background/78 px-3 py-3",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:"Folder"}),o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-foreground",title:T.projectRoot||"-",children:$g(T.projectRoot)})]}),o.jsxs("div",{className:"rounded-[18px] border border-border/75 bg-background/78 px-3 py-3",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:"Agent Name"}),o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-foreground",title:te,children:te})]}),o.jsxs("div",{className:"rounded-[18px] border border-border/75 bg-background/78 px-3 py-3",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:"Execution"}),o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-foreground",title:pe||"-",children:pe||"-"})]})]})]}),o.jsxs("div",{className:"space-y-4 px-5 py-5 sm:px-6",children:[o.jsxs("div",{className:"rounded-[22px] border border-border/75 bg-background/82 p-4",children:[o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"Source Folder"}),o.jsx("div",{className:"mt-1 text-sm font-medium text-foreground",children:"选择要接入或编辑的项目目录"})]}),o.jsx("span",{className:"inline-flex items-center rounded-full border border-border/70 bg-secondary/75 px-2.5 py-1 text-[11px] text-muted-foreground",children:"step 1"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(lt,{id:"agent-project-root",value:T.projectRoot,placeholder:"请选择目录",readOnly:!0,disabled:!0,className:"h-11 rounded-[14px] border-border/80 bg-secondary/55 px-3 font-mono text-[12px] text-foreground/88"}),o.jsx(be,{type:"button",variant:"ghost",className:Vn,onClick:()=>void Q(),disabled:A,"aria-label":"选择目录",title:"选择目录",children:A?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(a5,{className:"size-4"})})]}),o.jsx("p",{className:"mt-3 text-[12px] leading-5 text-muted-foreground",children:"已初始化目录会直接启动;未初始化目录会自动补齐 `PROFILE.md`、`SOUL.md` 和 `downcity.json`。"})]}),o.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[o.jsxs("div",{className:"rounded-[22px] border border-border/75 bg-background/82 p-4",children:[o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"Identity"}),o.jsx("div",{className:"mt-1 text-sm font-medium text-foreground",children:"确认这个文件夹在 Console 里的名称"})]}),o.jsx("span",{className:"inline-flex items-center rounded-full border border-border/70 bg-secondary/75 px-2.5 py-1 text-[11px] text-muted-foreground",children:"step 2"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{htmlFor:"agent-name",className:"text-[12px] font-medium text-foreground/82",children:"Agent 名称"}),o.jsx(lt,{id:"agent-name",value:T.agentName,placeholder:$g(T.projectRoot),className:"h-11 rounded-[14px] border-border/80 bg-background px-3 text-sm",onChange:_=>E(Y=>({...Y,agentName:_.target.value}))})]})]}),o.jsxs("div",{className:"rounded-[22px] border border-border/75 bg-background/82 p-4",children:[o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"Execution"}),o.jsx("div",{className:"mt-1 text-sm font-medium text-foreground",children:"统一选择 api、local 或 acp"})]}),o.jsx("span",{className:"inline-flex items-center rounded-full border border-border/70 bg-secondary/75 px-2.5 py-1 text-[11px] text-muted-foreground",children:"step 3"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{htmlFor:"agent-runtime",className:"text-[12px] font-medium text-foreground/82",children:"执行模式"}),o.jsxs("select",{id:"agent-runtime",className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",value:T.executionType,onChange:_=>E(Y=>({...Y,executionType:_.target.value})),children:[o.jsx("option",{value:"api",children:"API"}),o.jsx("option",{value:"acp",children:"ACP"}),o.jsx("option",{value:"local",children:"Local"})]})]}),T.executionType==="api"?o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx(qt,{htmlFor:"agent-model",className:"text-[12px] font-medium text-foreground/82",children:"模型 ID"}),o.jsxs("select",{id:"agent-model",className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",value:T.modelId,onChange:_=>E(Y=>({...Y,modelId:_.target.value})),disabled:R.length===0,children:[R.length===0?o.jsx("option",{value:"",children:"请先在 Global / Model 创建可用模型"}):null,R.map(_=>o.jsx("option",{value:_.id,children:String(_.id||"").trim()},_.id))]})]}):T.executionType==="local"?o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx(qt,{htmlFor:"agent-local-model",className:"text-[12px] font-medium text-foreground/82",children:"GGUF 文件名"}),o.jsxs("select",{id:"agent-local-model",value:T.localModel,className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 font-mono text-[12px] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",onChange:_=>E(Y=>({...Y,localModel:_.target.value})),disabled:N||oe.length===0,children:[oe.length===0?o.jsx("option",{value:"",children:N?"正在读取本地模型":"没有发现本地 GGUF 模型"}):null,oe.map(_=>o.jsx("option",{value:_,children:_},_))]}),o.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:"直接选择已安装模型;默认扫描 `~/.models`,若项目配置了 `plugins.lmp.modelsDir` 会优先使用该目录。"})]}):T.executionType==="acp"?o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx(qt,{htmlFor:"agent-acp-type",className:"text-[12px] font-medium text-foreground/82",children:"Coding Agent"}),o.jsxs("select",{id:"agent-acp-type",className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",value:T.agentType,onChange:_=>E(Y=>({...Y,agentType:_.target.value})),children:[o.jsx("option",{value:"kimi",children:"Kimi"}),o.jsx("option",{value:"claude",children:"Claude"}),o.jsx("option",{value:"codex",children:"Codex"})]})]}):o.jsx(o.Fragment,{})]})]}),o.jsxs("div",{className:"rounded-[20px] border border-dashed border-border/85 bg-secondary/45 px-4 py-3",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"What Will Be Written"}),o.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[12px] text-foreground/78",children:[o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`downcity.json.execution`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`downcity.json.plugins.lmp`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`PROFILE.md`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`SOUL.md`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`.downcity/*`"})]})]})]}),o.jsxs(rs,{className:"border-t border-border/70 bg-background/74 px-5 py-4 sm:px-6 sm:justify-end",children:[o.jsx(be,{type:"button",variant:"ghost",onClick:q,disabled:O,children:"取消"}),o.jsx(be,{type:"button",disabled:!Z||O,className:"min-w-[8.5rem] rounded-[14px] bg-foreground px-4 text-background hover:bg-foreground/92",onClick:async()=>{try{P(!0);const _=T.executionType==="api"?{executionMode:"api",modelId:T.modelId.trim()}:T.executionType==="local"?{executionMode:"local",localModel:T.localModel.trim()}:{executionMode:"acp",agentType:T.agentType};await Promise.resolve(g(j||T.projectRoot.trim(),{agentName:T.agentName.trim()||void 0,..._})),q()}finally{P(!1)}},children:O?o.jsx(nt,{className:"size-4 animate-spin"}):"初始化并启动"})]})]})})]})});function O0(e){const{cityVersion:t,agents:n,modelPoolItems:s,plugins:r,configStatus:a,onPickAgentDirectory:i,onInspectAgentDirectory:l,onLoadLocalModels:u,onStartAgent:d,onStartAgentWithInitialization:f,onRestartAgent:g,onStopAgent:m}=e,h=c.useRef(null),[x,y]=c.useState(!1),w=c.useCallback(async()=>{if(h.current){y(!0);try{await h.current.openFolder()}finally{y(!1)}}},[]),b=new Set(["ship_db","console_pid","agents_registry"]),p=a.filter(N=>N.scope==="console"),v=p.filter(N=>b.has(N.key)),S=p.filter(N=>!b.has(N.key)&&N.status==="missing").length,j=v.filter(N=>N.status!=="ok"),C=r.filter(N=>String(N.state||"").toLowerCase()==="unavailable").length,A=v.length-j.length,O=j.length===0?S>0?"warning":"ok":"error",P=[...p.filter(N=>N.status!=="ok").map(N=>({key:`config:${N.key}`,source:b.has(N.key)?"required config":"optional config",name:N.label,state:N.status,detail:N.reason||N.path})),...r.filter(N=>String(N.state||"").toLowerCase()==="unavailable").map(N=>({key:`plugin:${String(N.name||"unknown")}`,source:"plugin",name:String(N.name||"unknown"),state:String(N.state||"unavailable"),detail:String(N.lastError||"").trim()||"-"}))],$=Array.from(new Map(P.map(N=>[N.key,N])).values()),z=$.length;return o.jsxs("section",{className:"space-y-5",children:[o.jsx(wt,{title:"Global Summary",description:"当前全局运行态与异常信号概览。",children:o.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`dc ${String(t||"-")}`}),o.jsx("span",{className:O==="ok"?"inline-flex items-center rounded-full bg-emerald-500/12 px-2 py-1 text-emerald-700":O==="warning"?"inline-flex items-center rounded-full bg-secondary px-2 py-1 text-foreground":"inline-flex items-center rounded-full bg-destructive/10 px-2 py-1 text-destructive",children:`config ${A}/${v.length}`}),S>0?o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`optional missing ${S}`}):null,o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`plugin unavailable ${C}`}),o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`signals ${z}`})]})}),o.jsx(wt,{title:"Agent Runtime",description:`共 ${n.length} 个 agent,可直接在此启动、重启或停止。`,actions:o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:()=>void w(),disabled:x,"aria-label":"打开文件夹",title:"打开文件夹",children:x?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(fa,{className:"size-4"})}),children:o.jsx(WI,{ref:h,agents:n,modelPoolItems:s,onPickAgentDirectory:i,onInspectAgentDirectory:l,onLoadLocalModels:u,onStartAgent:d,onStartAgentWithInitialization:f,onRestartAgent:g,onStopAgent:m})}),o.jsx(wt,{title:"Signals",description:$.length===0?"当前没有异常信号。":`共 ${$.length} 条异常信号。`,className:"shadow-[0_1px_0_rgba(17,17,19,0.02)]",children:$.length===0?o.jsx("div",{className:"py-2 text-sm text-muted-foreground",children:"没有异常信号"}):o.jsx("div",{className:"space-y-1",children:$.map(N=>o.jsxs("div",{className:"rounded-[16px] bg-destructive/8 px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 text-sm",children:[o.jsx("span",{className:"font-medium text-foreground",children:N.name}),o.jsx("span",{className:"text-[11px] uppercase tracking-[0.1em] text-muted-foreground",children:N.source}),o.jsx("span",{className:"text-xs text-destructive",children:N.state})]}),o.jsx("div",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:N.detail,children:N.detail})]},N.key))})})]})}function e7(e){const{logs:t,formatTime:n}=e,s=t.length===0?"暂无日志":t.map(r=>{const a=n(r.timestamp),i=String(r.type||r.level||"info").toUpperCase(),l=String(r.message||"");return`[${a}] [${i}] ${l}`}).join(`
|
|
424
|
-
`);return o.jsx(wt,{title:"Recent Logs",description:`最近 ${t.length} 条日志输出。`,bodyClassName:"gap-0",children:o.jsx("div",{className:"overflow-hidden rounded-[20px] bg-secondary/85",children:o.jsx("pre",{className:"max-h-[68vh] overflow-auto px-4 py-4 font-mono text-[11px] leading-relaxed text-foreground/88",children:s})})})}function z0(e){const t=String(e||"").trim().toLowerCase();return t?t==="project"||t==="home"||t==="external"?t:"other":"unknown"}function Fo(e){return o.jsx("span",{className:e.tone==="strong"?"inline-flex h-6 items-center rounded-full bg-background px-2.5 text-[11px] text-foreground":"inline-flex h-6 items-center rounded-full bg-background/80 px-2.5 text-[11px] text-muted-foreground",children:e.children})}function t7(e){const{skills:t,loading:n,selectedAgentId:s,onRefreshSkills:r,onFindSkill:a,onInstallSkill:i}=e,[l,u]=c.useState(""),[d,f]=c.useState(""),[g,m]=c.useState(""),[h,x]=c.useState(!1),[y,w]=c.useState(!0),[b,p]=c.useState(!0),[v,S]=c.useState("claude-code"),[j,C]=c.useState(""),[A,M]=c.useState(null),O=!!String(s||"").trim(),P=l.trim().toLowerCase(),$=c.useMemo(()=>P?t.filter(R=>{const I=String(R.id||"").toLowerCase(),T=String(R.name||"").toLowerCase(),E=String(R.description||"").toLowerCase(),q=String(R.source||"").toLowerCase(),k=String(R.skillMdPath||"").toLowerCase(),D=Array.isArray(R.allowedTools)?R.allowedTools.join(" ").toLowerCase():"";return I.includes(P)||T.includes(P)||E.includes(P)||q.includes(P)||k.includes(P)||D.includes(P)}):t,[P,t]),z=c.useMemo(()=>{const R={project:0,home:0,external:0,other:0};for(const I of $){const T=z0(String(I.source||""));R[T]+=1}return R},[$]),N=c.useCallback(async()=>{const R=String(d||"").trim();if(R)try{C("find");const I=await a(R);M({title:"Find",message:(I==null?void 0:I.message)||`已执行 find: ${R}`,nextAction:I==null?void 0:I.nextAction,workflow:I==null?void 0:I.workflow})}finally{C("")}},[d,a]),H=c.useCallback(async()=>{const R=String(g||"").trim();if(R)try{C("install");const I=await i({spec:R,global:y,yes:b,agent:String(v||"").trim()||"claude-code"});M({title:"Install",message:(I==null?void 0:I.message)||`已执行 install: ${R}`,nextAction:I==null?void 0:I.nextAction,workflow:I==null?void 0:I.workflow})}finally{C("")}},[v,y,g,b,i]);return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Skills",actions:o.jsxs(o.Fragment,{children:[o.jsx(Fo,{tone:"strong",children:`total ${$.length}`}),o.jsx(Fo,{children:`project ${z.project}`}),o.jsx(Fo,{children:`home ${z.home}`}),o.jsx(Fo,{children:`external ${z.external}`}),o.jsxs("div",{className:"relative",children:[o.jsx(Wl,{className:"pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{value:l,onChange:R=>u(R.target.value),placeholder:"搜索 skills",className:"w-[220px] pl-8"})]}),o.jsx(be,{size:"sm",variant:"outline",disabled:n||!O,onClick:()=>void r(),children:o.jsx(xc,{className:`size-3.5 ${n?"animate-spin":""}`})})]}),children:$.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary/85 px-4 py-8 text-sm text-muted-foreground",children:P?"没有匹配的 skills。":"暂无 skills。"}):o.jsx("div",{className:"space-y-2",children:$.map(R=>{const I=String(R.id||"unknown"),T=String(R.name||"unknown"),E=z0(String(R.source||"")),q=String(R.description||"").trim(),k=Array.isArray(R.allowedTools)?R.allowedTools:[],D=String(R.skillMdPath||"").trim()||"-",B=[E,k.length>0?k.join(", "):"no tools"].filter(Boolean).join(" · ");return o.jsx("div",{className:"group rounded-[14px] bg-transparent px-3 py-3 transition-colors hover:bg-secondary",children:o.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between",children:[o.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:T}),o.jsx("span",{className:"inline-flex h-5 items-center rounded-full bg-background px-2 text-[11px] text-muted-foreground",children:E})]}),o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:I}),q?o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:q}):null]}),o.jsxs("div",{className:"min-w-0 text-left lg:max-w-[42rem] lg:text-right",children:[o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:B}),o.jsx("div",{className:"truncate font-mono text-[11px] text-muted-foreground/90",title:D,children:D})]})]})},`${E}:${I}`)})})}),o.jsx(wt,{title:"Find / Install",actions:o.jsxs(o.Fragment,{children:[o.jsx(Fo,{children:`global ${String(y)}`}),o.jsx(Fo,{children:`yes ${String(b)}`}),o.jsx(Fo,{children:`agent ${String(v||"claude-code")}`}),o.jsx(be,{size:"sm",variant:"outline",onClick:()=>x(!0),children:o.jsx(pd,{className:"size-3.5"})})]}),children:o.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"mb-2 text-xs uppercase tracking-[0.12em] text-muted-foreground",children:"Find"}),o.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[o.jsx(lt,{value:d,onChange:R=>f(R.target.value),placeholder:"例如 playwright",className:"flex-1"}),o.jsx(be,{variant:"outline",className:"sm:min-w-24",disabled:!O||j==="install"||j==="find",onClick:()=>void N(),children:j==="find"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Wl,{className:"size-4"})})]})]})}),o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"mb-2 text-xs uppercase tracking-[0.12em] text-muted-foreground",children:"Install"}),o.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[o.jsx(lt,{value:g,onChange:R=>m(R.target.value),placeholder:"例如 owner/repo@playwright",className:"flex-1"}),o.jsx(be,{variant:"outline",className:"sm:min-w-24",disabled:!O||j==="install"||j==="find",onClick:()=>void H(),children:j==="install"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Ew,{className:"size-4"})})]})]})})]})}),o.jsx(wt,{title:"Action Report",children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:A?o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3 text-sm",children:[o.jsx("div",{className:"text-foreground",children:A.title}),o.jsx("div",{className:"mt-1 text-muted-foreground",children:A.message}),A.nextAction?o.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:`next · ${A.nextAction}`}):null,Array.isArray(A.workflow)&&A.workflow.length>0?o.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:`workflow · ${A.workflow.join(" -> ")}`}):null]}):o.jsx("div",{className:"rounded-[14px] bg-transparent px-3 py-6 text-sm text-muted-foreground",children:"暂无动作反馈"})})}),o.jsx($n,{open:h,onOpenChange:x,children:o.jsxs(Un,{className:"w-[min(92vw,520px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"Install 配置"}),o.jsx(os,{children:"设置 `city skill install` 的默认参数。配置会用于当前页面的 Install 操作。"})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("div",{className:"text-xs font-medium text-foreground",children:"Agent"}),o.jsx(lt,{value:v,onChange:R=>S(R.target.value),placeholder:"claude-code"})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(be,{type:"button",variant:y?"default":"outline",size:"sm",onClick:()=>w(R=>!R),children:`global: ${y?"on":"off"}`}),o.jsx(be,{type:"button",variant:b?"default":"outline",size:"sm",onClick:()=>p(R=>!R),children:`yes: ${b?"on":"off"}`})]})]}),o.jsx(rs,{children:o.jsx(be,{variant:"outline",onClick:()=>x(!1),children:"完成"})})]})})]})}function n7(e){const t=String(e||"").trim();if(!t)return"-";const n=t.match(/^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-(\d{3})$/);if(!n)return t;const[,s,r,a,i,l,u,d]=n,f=new Date(Number(s),Number(r)-1,Number(a),Number(i),Number(l),Number(u),Number(d));if(Number.isNaN(f.getTime()))return t;const g=f.toLocaleString("zh-CN",{hour12:!1}),m=Date.now()-f.getTime();return Number.isFinite(m)?m<6e4?`${g} · 刚刚`:m<36e5?`${g} · ${Math.floor(m/6e4)} 分钟前`:m<864e5?`${g} · ${Math.floor(m/36e5)} 小时前`:`${g} · ${Math.floor(m/864e5)} 天前`:g}function Ba(e){return o.jsx("div",{className:"truncate text-sm text-foreground",title:e.value,children:e.value})}function Pa(e){const t=e.tone==="success"?"bg-emerald-500/8 text-emerald-700":e.tone==="danger"?"bg-destructive/8 text-destructive":"bg-background/80 text-muted-foreground";return o.jsx("span",{className:`inline-flex h-6 items-center rounded-full px-2.5 text-[11px] ${t}`,children:e.children})}function s7(e){return e.action==="start"||e.action==="resume"?o.jsx(sa,{className:"size-3.5"}):e.action==="pause"?o.jsx(Nw,{className:"size-3.5"}):e.action==="restart"?o.jsx(Ip,{className:"size-3.5"}):o.jsx(Dp,{className:"size-3.5"})}function r7(e){if(e.executionMode==="api"||!e.executionMode)return{executionType:"api",agentType:"kimi"};if(e.executionMode==="local")return{executionType:"local",agentType:"kimi"};const t=String(e.agentType||"").trim();return t==="claude"||t==="codex"?{executionType:"acp",agentType:t}:{executionType:"acp",agentType:"kimi"}}function o7(e){return e.executionType==="api"?"api":e.executionType==="local"?"local":`acp ${e.agentType}`}function a7(e,t){const n=new Set,s=String(t||"").trim();s&&n.add(s);for(const r of e){const a=String(r||"").trim();a&&n.add(a)}return Array.from(n)}function i7(e){var me,ge;const{selectedAgent:t,overview:n,services:s,skills:r,tasks:a,sessions:i,channelAccounts:l,consoleUiSessionId:u,configStatus:d,model:f,onLoadLocalModels:g,onUpdateExecution:m,onStartAgent:h,onRestartAgent:x,onStopAgent:y,onOpenTask:w,onOpenSession:b,onControlService:p,chatChannels:v,onChatAction:S}=e,j=Ls(),A=(Array.isArray((me=n==null?void 0:n.sessions)==null?void 0:me.items)?n.sessions.items:[]).some(U=>U.sessionId===u),M=Array.isArray(t==null?void 0:t.chatProfiles)?t.chatProfiles:[],O=c.useMemo(()=>i.filter(U=>U.executing===!0),[i]),P=O.length>0,$=d.filter(U=>U.scope==="agent"),z=$.filter(U=>String(U.status||"").toLowerCase()!=="ok"),N=$.filter(U=>{const ce=String(U.key||"").toLowerCase(),F=String(U.label||"").toLowerCase(),K=String(U.path||"").toLowerCase();return ce.includes("memory")||F.includes("memory")||K.includes("/memory")}),H=Array.isArray(f==null?void 0:f.availableModels)?f.availableModels:[],R=String((f==null?void 0:f.agentPrimaryModelId)||(f==null?void 0:f.primaryModelId)||(t==null?void 0:t.modelId)||"").trim(),I=String(((ge=H[0])==null?void 0:ge.id)||"").trim(),T=R||I,E=String((t==null?void 0:t.localModel)||"").trim(),q=r7({executionMode:t==null?void 0:t.executionMode,agentType:t==null?void 0:t.agentType}),[k,D]=c.useState(T),[B,Q]=c.useState(E),[Z,te]=c.useState(q.executionType),[se,ie]=c.useState(q.agentType),[oe,pe]=c.useState([]),[_,Y]=c.useState(!1),[le,ne]=c.useState(""),[ue,ae]=c.useState({});c.useEffect(()=>{D(T)},[T]),c.useEffect(()=>{te(q.executionType),ie(q.agentType)},[q]),c.useEffect(()=>{Q(E)},[E]),c.useEffect(()=>{if(!t)return;let U=!1;return(async()=>{try{Y(!0);const ce=await g(t.projectRoot||t.id);if(U)return;pe(ce)}finally{U||Y(!1)}})(),()=>{U=!0}},[g,t]);const xe=c.useMemo(()=>a7(oe,B||E),[E,oe,B]),ee=c.useCallback(U=>!!ue[U],[ue]),W=c.useMemo(()=>{const U=new Map;for(const ce of v){const F=String(ce.channel||"").trim().toLowerCase();if(!F)continue;const K=ce.detail,he=K&&typeof K=="object"&&!Array.isArray(K)?K:null,Te=he!=null&&he.config&&typeof he.config=="object"&&!Array.isArray(he.config)?he.config:null;U.set(F,{enabled:ce.enabled,configured:ce.configured,channelAccountId:String((Te==null?void 0:Te.channelAccountId)||"").trim()})}return U},[v]),X=c.useMemo(()=>{const U=new Map;for(const ce of l){const F=String(ce.id||"").trim();if(!F)continue;const K=String(ce.name||ce.id||"").trim()||F;U.set(F,K)}return U},[l]),G=c.useMemo(()=>{const U=["chat","task","skill","memory","context"],ce=new Map;for(const K of s){const he=String(K.name||"").trim().toLowerCase();he&&(ce.has(he)||ce.set(he,K))}const F=U.map(K=>{const he=ce.get(K);return he||{name:K,state:"stopped"}});for(const[K,he]of ce.entries())U.includes(K)||F.push(he);return F},[s]),L=c.useCallback(U=>{const ce=String(U||"").trim().toLowerCase();if(!ce)return"";const F=i.map(K=>String(K.sessionId||"").trim()).filter(K=>K.startsWith(`${ce}-`));return F.length===0?"":F[0]||""},[i]),J=c.useCallback(U=>{const ce=String(U||"").trim().toLowerCase();return ce==="running"?["pause","restart","stop"]:ce==="paused"?["resume","restart","stop"]:ce==="stopped"||ce==="idle"||ce==="unknown"?["start","restart"]:["start","restart","stop"]},[]);return t?o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Agent",actions:o.jsxs(o.Fragment,{children:[o.jsx(Pa,{tone:t.running?"success":"default",children:t.running?"running":"stopped"}),o.jsx(Pa,{tone:P?"success":"default",children:P?`executing ${O.length}`:"idle"}),t.running?o.jsxs(o.Fragment,{children:[o.jsx(be,{size:"icon",variant:"ghost",className:Vn,onClick:()=>{ne("restart"),Promise.resolve(x()).finally(()=>ne(""))},disabled:le!=="",children:le==="restart"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Ip,{className:"size-4"})}),o.jsx(be,{size:"icon",variant:"ghost",className:Ro,onClick:()=>{(async()=>await j({title:"停止 Agent",description:`确认停止 "${t.name||"unknown-agent"}"?`,confirmText:"停止",confirmVariant:"destructive"})&&(ne("stop"),Promise.resolve(y()).finally(()=>ne(""))))()},disabled:le!=="",children:le==="stop"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Dp,{className:"size-4"})})]}):o.jsx(be,{size:"icon",variant:"ghost",className:Vn,onClick:()=>{ne("start"),Promise.resolve(h()).finally(()=>ne(""))},disabled:le!=="",children:le==="start"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(sa,{className:"size-4"})})]}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:o.jsxs("div",{className:"min-w-0 flex items-start gap-3",children:[o.jsx("img",{src:"/image.png",alt:"bot",className:"size-9 shrink-0 rounded-[6px] object-cover"}),o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx("div",{className:"truncate text-base font-medium text-foreground",children:t.name||"-"}),o.jsx("div",{className:"truncate text-sm text-muted-foreground",children:t.projectRoot||t.id||"-"})]})]})}),o.jsxs("div",{className:"mt-4 grid gap-x-8 md:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Ba,{value:String((n==null?void 0:n.cityVersion)||"-")}),o.jsx(Ba,{value:String(t.daemonPid||"-")}),o.jsx(Ba,{value:String(t.host||"-")})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Ba,{value:t.port?String(t.port):"-"}),o.jsx(Ba,{value:String(t.projectRoot||"-")}),o.jsx(Ba,{value:String(t.id||"-")})]})]})]})})}),o.jsx(wt,{title:"Execution",actions:o.jsxs(o.Fragment,{children:[o.jsx(Pa,{children:o7(q)}),o.jsx(Pa,{children:`available ${H.length}`})]}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"grid gap-3 md:grid-cols-1",children:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium"}),children:o.jsx("span",{className:"truncate",children:Z==="api"?"API":Z==="local"?"Local":"ACP"})}),o.jsxs(wn,{className:"max-h-72 min-w-[20rem]",children:[o.jsx(bt,{onClick:()=>{te("api"),T&&(D(T),!(q.executionType==="api"&&T===R)&&m({executionMode:"api",modelId:T}))},children:"API"}),o.jsx(bt,{onClick:()=>{te("local");const U=String(B||E||xe[0]||"").trim();U&&(q.executionType==="local"&&U===E||m({executionMode:"local",localModel:U}))},children:"Local"}),o.jsx(bt,{onClick:()=>{te("acp"),ie(q.agentType);const U=q.agentType||"kimi";q.executionType==="acp"&&q.agentType===U||m({executionMode:"acp",agentType:U})},children:"ACP"})]})]})}),Z==="api"?o.jsx("div",{className:"mt-3 grid gap-3 md:grid-cols-1",children:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium"}),children:o.jsx("span",{className:"truncate",children:k||"选择 execution.modelId"})}),o.jsx(wn,{className:"max-h-72 min-w-[20rem]",children:H.length===0?o.jsx(bt,{disabled:!0,children:"无可选模型"}):H.map(U=>{const ce=String(U.id||"").trim();return ce?o.jsx(bt,{onClick:()=>{const F=String(ce||"").trim();D(F),!(!F||q.executionType==="api"&&F===R)&&m({executionMode:"api",modelId:F})},children:`${ce} · ${U.providerType||"-"}${U.isPaused?" · paused":""}`},ce):null})})]})}):Z==="local"?o.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[o.jsxs("select",{value:B,className:"flex h-9 flex-1 rounded-[12px] border border-input bg-background px-3 font-mono text-[12px] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",onChange:U=>Q(U.target.value),disabled:_||xe.length===0,children:[xe.length===0?o.jsx("option",{value:"",children:_?"正在读取本地模型":"没有发现本地 GGUF 模型"}):null,xe.map(U=>o.jsx("option",{value:U,children:U},U))]}),o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 rounded-[12px] bg-background px-3 text-xs",disabled:!String(B||"").trim()||_,onClick:()=>{const U=String(B||"").trim();U&&(q.executionType==="local"&&U===E||m({executionMode:"local",localModel:U}))},children:"应用"})]}):Z==="acp"?o.jsx("div",{className:"mt-3 grid gap-3 md:grid-cols-1",children:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium"}),children:o.jsx("span",{className:"truncate",children:`ACP · ${se}`})}),o.jsx(wn,{className:"max-h-72 min-w-[20rem]",children:["kimi","claude","codex"].map(U=>o.jsx(bt,{onClick:()=>{ie(U),!(q.executionType==="acp"&&q.agentType===U)&&m({executionMode:"acp",agentType:U})},children:`ACP · ${U}`},U))})]})}):null]})})}),G.map((U,ce)=>{const F=String(U.name||U.service||`service-${ce}`).trim().toLowerCase(),K=F==="skill"?"skills":F,he=String(U.state||U.status||"unknown").trim().toLowerCase(),Te=J(he),Ae=he==="error"||he==="failed"?"danger":he==="running"?"success":"default",Re=F.includes("task"),Ye=F.includes("chat"),yt=F.includes("skill"),De=F.includes("memory"),ot=F.includes("context"),_e=Ye?M.map(Ce=>{const rt=String(Ce.channel||"-"),et=String(Ce.linkState||Ce.statusText||"unknown"),$e=L(rt),Ht=W.get(rt.trim().toLowerCase()),zn=String((Ht==null?void 0:Ht.channelAccountId)||"").trim(),ms=zn?String(X.get(zn)||zn):"no binding";return{channel:rt,link:et,sessionId:$e,clickable:!!$e,enabled:(Ht==null?void 0:Ht.enabled)===!0,configured:(Ht==null?void 0:Ht.configured)===!0,accountName:ms}}):[],Je=Re?a.slice(0,5):[],jt=yt?r.slice(0,5):[],Ct=ot?i.slice(0,5).map(Ce=>String(Ce.sessionId||"-")):[],zt=De?N.length>0?N.map(Ce=>`${Ce.label} · ${Ce.status}`):["无 memory 配置"]:ot&&Ct.length===0?[`consoleui · ${A?"ok":"missing"}`]:!Re&&!Ye&&!yt&&!ot?["无额外明细"]:[];return o.jsx(wt,{title:K,actions:o.jsxs(o.Fragment,{children:[o.jsx(Pa,{tone:Ae,children:he||"-"}),o.jsx("div",{className:"flex items-center gap-1",children:Te.map(Ce=>{const rt=`${F}:${Ce}`;return o.jsx("button",{type:"button",className:Ce==="stop"?`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${Ro}`:`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${Vn}`,disabled:ee(rt),onClick:()=>{(async()=>Ce==="stop"&&!await j({title:"停止 Service",description:`确认停止 service「${K}」吗?`,confirmText:"停止",confirmVariant:"destructive"})||(ae(et=>({...et,[rt]:!0})),Promise.resolve(p(F,Ce)).finally(()=>{ae(et=>({...et,[rt]:!1}))})))()},title:Ce,"aria-label":Ce,children:ee(rt)?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(s7,{action:Ce})},rt)})})]}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"space-y-3 rounded-[14px] bg-transparent px-3 py-3",children:[Ye&&_e.length>0?o.jsx("div",{className:"space-y-1.5",children:_e.map((Ce,rt)=>{const et=String(Ce.channel||"").trim(),$e=!!et&&et!=="-",Ht=!$e||!(Ce.enabled&&Ce.configured),zn=!$e||Ce.enabled,ms=!$e||!Ce.enabled,Bs=`${F}:chat:${et}:open`,In=`${F}:chat:${et}:close`,Sn=`${F}:chat:${et}:test`,Jn=`${F}:chat:${et}:reconnect`;return o.jsx("div",{className:"flex flex-col gap-2 rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:o.jsxs("div",{className:"flex flex-col gap-1 lg:flex-row lg:items-center lg:justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-foreground",children:Ce.channel}),o.jsx("div",{className:"truncate",children:`${Ce.link} · ${Ce.accountName}`})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[o.jsx("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",onClick:()=>b(Ce.sessionId),disabled:!Ce.clickable,children:"session"}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:zn||ee(Bs),onClick:()=>{ae(vt=>({...vt,[Bs]:!0})),Promise.resolve(S("open",et)).finally(()=>{ae(vt=>({...vt,[Bs]:!1}))})},children:[ee(Bs)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"open"})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:ms||ee(In),onClick:()=>{ae(vt=>({...vt,[In]:!0})),Promise.resolve(S("close",et)).finally(()=>{ae(vt=>({...vt,[In]:!1}))})},children:[ee(In)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"close"})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:Ht||ee(Sn),onClick:()=>{ae(vt=>({...vt,[Sn]:!0})),Promise.resolve(S("test",et)).finally(()=>{ae(vt=>({...vt,[Sn]:!1}))})},children:[ee(Sn)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"test"})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:Ht||ee(Jn),onClick:()=>{ae(vt=>({...vt,[Jn]:!0})),Promise.resolve(S("reconnect",et)).finally(()=>{ae(vt=>({...vt,[Jn]:!1}))})},children:[ee(Jn)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"reconnect"})]})]})]})},`${F}:chat:${Ce.channel}:${rt}`)})}):null,Re&&Je.length>0?o.jsx("div",{className:"space-y-1.5",children:Je.map((Ce,rt)=>{const et=String(Ce.title||`task-${rt}`).trim(),$e=String(Ce.status||"unknown").trim().toLowerCase();return o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-foreground",children:et}),o.jsx("div",{className:"truncate",children:`${$e} · ${n7(Ce.lastRunTimestamp)}`})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1 rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground",onClick:()=>w(et),children:[o.jsx("span",{children:"open"}),o.jsx(my,{className:"size-3 shrink-0"})]})]},`${F}:task:${et}:${rt}`)})}):null,yt&&jt.length>0?o.jsx("div",{className:"space-y-1.5",children:jt.map((Ce,rt)=>o.jsxs("div",{className:"rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:[o.jsx("div",{className:"truncate text-foreground",children:Ce.name||Ce.id||"-"}),o.jsx("div",{className:"truncate",children:`${Ce.source||"-"} · ${Array.isArray(Ce.allowedTools)&&Ce.allowedTools.length>0?Ce.allowedTools.join(", "):"-"}`})]},`${F}:skill:${Ce.id||Ce.name||rt}`))}):null,ot&&Ct.length>0?o.jsx("div",{className:"space-y-1.5",children:Ct.map(Ce=>o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:[o.jsx("div",{className:"min-w-0 truncate",children:Ce}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1 rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground",onClick:()=>b(Ce),children:[o.jsx("span",{children:"open"}),o.jsx(my,{className:"size-3 shrink-0"})]})]},`${F}:session:${Ce}`))}):null,zt.length>0?o.jsx("div",{className:"space-y-1",children:zt.map((Ce,rt)=>o.jsx("div",{className:"truncate rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:Ce},`${F}:detail:${rt}`))}):null]})})},`${F}:${ce}`)}),o.jsx(wt,{title:"Signals",actions:o.jsx(Pa,{tone:z.length>0?"danger":"default",children:`issues ${z.length}`}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:z.length>0?z.map(U=>o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3 text-sm text-muted-foreground transition-colors hover:bg-background",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"text-foreground",children:U.label}),o.jsx("span",{className:"text-xs text-destructive",children:U.status})]}),o.jsx("div",{className:"mt-1 truncate text-xs",title:U.reason||U.path,children:U.reason||U.path||"-"})]},`${U.key}:${U.path}`)):o.jsx("div",{className:"rounded-[14px] bg-transparent px-3 py-6 text-sm text-muted-foreground",children:"当前没有异常信号"})})})]}):o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"未选择 agent"})}function l7(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return"-";const n=Math.max(0,Number(t)-Number(e));return n<1e3?`${n} ms`:`${(n/1e3).toFixed(2)} s`}function fu(e,t){const n=String(e||"").trim();if(!n)return"-";const s=n.match(/^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-(\d{3})$/);if(s){const a=Number(s[1]),i=Number(s[2])-1,l=Number(s[3]),u=Number(s[4]),d=Number(s[5]),f=Number(s[6]),g=Number(s[7]),m=new Date(a,i,l,u,d,f,g).getTime(),h=t(m);return h==="-"?"未记录时间":h}const r=t(n);return r==="-"?"未记录时间":r}function c7(e,t){var s;const n=String(((s=t==null?void 0:t.progress)==null?void 0:s.status)||"").trim();return n||(e!=null&&e.inProgress?"running":String((e==null?void 0:e.status)||(e==null?void 0:e.executionStatus)||"unknown"))}function I0(e){const t=String(e||"").trim();return!t||t==="@manual"?"manual":t.startsWith("time:")?t.slice(5)||"time":t}function u7(e){var xe,ee,W,X;const{tasks:t,statusBadgeVariant:n,formatTime:s,onRunTask:r,onSetTaskStatus:a,onDeleteTask:i,onLoadTaskRuns:l,onDeleteTaskRun:u,onClearTaskRuns:d,onLoadTaskRunDetail:f,selectedTaskTitle:g,onSelectTaskTitle:m}=e,h=Ls(),x=String(g||"").trim(),y=c.useMemo(()=>t.find(G=>String(G.title||"").trim()===x)||null,[x,t]),w=!x,[b,p]=c.useState([]),[v,S]=c.useState(""),[j,C]=c.useState(null),[A,M]=c.useState(!1),[O,P]=c.useState(!1),[$,z]=c.useState(!1),[N,H]=c.useState(!1),[R,I]=c.useState(!1),[T,E]=c.useState(""),[q,k]=c.useState(!1),D=c.useCallback(G=>{const L=n(G);return L==="ok"?"bg-secondary text-foreground":L==="bad"?"border-destructive/40 bg-destructive/10 text-destructive":"bg-card text-muted-foreground"},[n]),B=c.useMemo(()=>b.find(G=>String(G.timestamp||"").trim()===v)||null,[b,v]),Q=c.useMemo(()=>b.find(G=>!!G.inProgress)||null,[b]),Z=c.useMemo(()=>{var G;return!!(B!=null&&B.inProgress)||String(((G=j==null?void 0:j.progress)==null?void 0:G.status)||"").trim().toLowerCase()==="running"},[B,j]),te=c.useMemo(()=>{const G=t.length,L=t.filter(ge=>String(ge.status||"").toLowerCase()==="running").length,J=t.filter(ge=>{const U=String(ge.status||"").toLowerCase();return U==="error"||U==="failed"||U==="failure"}).length,me=t.filter(ge=>String(ge.when||"").trim()==="@manual").length;return{total:G,running:L,failed:J,manual:me}},[t]),se=c.useCallback(async(G,L)=>{const J=String(G||"").trim();if(!J)return[];const me=(L==null?void 0:L.showLoading)!==!1;me&&M(!0);try{const ge=await l(J,50);return p(ge),S(U=>{var F;const ce=L!=null&&L.preferInProgress?ge.find(K=>!!K.inProgress):null;return ce!=null&&ce.timestamp?String(ce.timestamp):U&&ge.some(K=>K.timestamp===U)?U:String(((F=ge[0])==null?void 0:F.timestamp)||"").trim()}),ge}finally{me&&M(!1)}},[l]),ie=c.useCallback(async(G,L,J)=>{const me=String(G||"").trim(),ge=String(L||"").trim();if(!me||!ge)return C(null),null;const U=(J==null?void 0:J.showLoading)!==!1;U&&P(!0);try{const ce=await f(me,ge);return C(ce),ce}finally{U&&P(!1)}},[f]);if(c.useEffect(()=>{if(!y){p([]),S(""),C(null),z(!1),H(!1);return}se(String(y.title||""),{showLoading:!0,preferInProgress:!0})},[se,y]),c.useEffect(()=>{const G=String((y==null?void 0:y.title)||"").trim(),L=String(v||"").trim();if(!G||!L){C(null);return}ie(G,L,{showLoading:!0})},[ie,v,y]),c.useEffect(()=>{Q!=null&&Q.timestamp&&Q.timestamp!==v&&S(Q.timestamp)},[Q,v]),c.useEffect(()=>{const G=String((y==null?void 0:y.title)||"").trim();if(!G||!($||Z||b.some(me=>!!me.inProgress)))return;const J=window.setInterval(()=>{se(G,{showLoading:!1,preferInProgress:!0}).then(me=>{var ce;const ge=me.find(F=>!!F.inProgress),U=String((ge==null?void 0:ge.timestamp)||v||((ce=me[0])==null?void 0:ce.timestamp)||"").trim();U&&ie(G,U,{showLoading:!1}),ge||z(!1)})},1500);return()=>{window.clearInterval(J)}},[$,ie,se,b,Z,v,y]),w)return o.jsx(wt,{title:"Tasks",description:"任务定义、状态与最近执行时间总览。",actions:o.jsxs(o.Fragment,{children:[o.jsx(An,{variant:"outline",className:"bg-secondary text-foreground",children:`total ${te.total}`}),o.jsx(An,{variant:"outline",className:"border-border/60 bg-primary/10 text-primary",children:`running ${te.running}`}),o.jsx(An,{variant:"outline",className:"border-border/60 bg-destructive/10 text-destructive",children:`failed ${te.failed}`}),o.jsx(An,{variant:"outline",className:"bg-secondary text-foreground",children:`manual ${te.manual}`})]}),children:t.length===0?o.jsx("div",{className:"rounded-[20px] bg-secondary px-4 py-6 text-sm text-muted-foreground",children:"暂无 task 数据"}):o.jsx("div",{className:"space-y-1.5",children:t.map(G=>{const L=String(G.title||"").trim();if(!L)return null;const J=String(G.status||"unknown"),me=String(G.description||"").trim(),ge=I0(G.when);return o.jsxs("button",{type:"button",className:"flex w-full items-start justify-between gap-3 rounded-[18px] bg-transparent px-3 py-2.5 text-left transition-colors hover:bg-secondary",onClick:()=>m==null?void 0:m(L),children:[o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:L}),o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:me||"无描述"})]}),o.jsxs("div",{className:"flex flex-shrink-0 flex-wrap items-center justify-end gap-1.5",children:[o.jsx(An,{variant:"outline",className:D(J),children:J}),o.jsx(An,{variant:"outline",className:"bg-secondary text-muted-foreground",children:ge}),o.jsx(An,{variant:"outline",className:"bg-background text-muted-foreground",children:fu(String(G.lastRunTimestamp||""),s)})]})]},L)})})});if(!y)return o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"该 task 不存在或已被删除"});const oe=String(y.title||"").trim(),pe=String(y.status||"").trim().toLowerCase(),_=pe==="enabled"?"paused":"enabled",Y=_==="enabled"?"恢复调度":"暂停调度",le=pe==="paused"?"paused:保留定义,不参与调度,可随时恢复。":pe==="disabled"?"disabled:显式禁用,仍保留定义,但当前作为关闭态处理。":"enabled:参与调度,按 when 正常运行。",ne=c.useCallback(async()=>{if(!(!oe||!await h({title:"删除任务",description:`确认删除任务「${oe}」及其全部运行记录?`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"}))){I(!0);try{await i(oe)&&(m==null||m(""))}finally{I(!1)}}},[h,i,m,oe]),ue=c.useCallback(async()=>{if(oe){I(!0);try{await a(oe,"disabled")}finally{I(!1)}}},[a,oe]),ae=c.useCallback(async()=>{if(oe){I(!0);try{await a(oe,_)}finally{I(!1)}}},[a,oe,_]);return o.jsxs("div",{className:"space-y-4",children:[o.jsxs(wt,{title:"Task Runtime",description:String(y.description||"").trim()||"无描述",actions:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{size:"icon",variant:"ghost",className:Vn,disabled:R||!oe,"aria-label":"任务操作",title:"任务操作"}),children:o.jsx(kw,{className:"size-4"})}),o.jsxs(wn,{align:"end",className:"min-w-[14rem]",children:[o.jsxs(ih,{children:[o.jsx(lh,{children:"任务操作"}),o.jsx(bt,{onClick:()=>void ae(),children:Y}),pe!=="disabled"?o.jsx(bt,{onClick:()=>void ue(),children:"设为 disabled"}):null]}),o.jsx(Md,{}),o.jsx(bt,{variant:"destructive",onClick:()=>void ne(),children:"删除任务"})]})]}),children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(An,{variant:"outline",className:D(String(y.status||"unknown")),children:String(y.status||"unknown")}),o.jsx(be,{size:"sm",variant:"outline",onClick:()=>m==null?void 0:m(""),children:"返回列表"}),o.jsx(be,{size:"sm",onClick:()=>{const G=String(y.title||"").trim();G&&(z(!0),r(G),window.setTimeout(()=>{se(G,{showLoading:!1,preferInProgress:!0})},350))},children:"Run Task"})]}),o.jsx("div",{className:"text-lg font-semibold tracking-tight text-foreground",children:String(y.title||"-")}),o.jsx("div",{className:"text-xs text-muted-foreground",children:le})]}),o.jsxs("div",{className:"grid min-h-0 gap-4 xl:grid-cols-[minmax(0,1.08fr)_minmax(0,1fr)]",children:[o.jsxs(wt,{title:"Definition",description:"任务定义、触发方式与原始内容。",children:[o.jsx("div",{className:"rounded-[20px] bg-secondary px-4 py-3.5",children:o.jsxs("div",{className:"grid gap-1.5 text-xs text-muted-foreground",children:[o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"kind"}),o.jsx("span",{children:y.kind||"-"})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"when"}),o.jsx("span",{children:I0(y.when)})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"session"}),o.jsx("span",{className:"truncate font-mono",title:y.sessionId||"",children:y.sessionId||"-"})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"file"}),o.jsx("span",{className:"truncate font-mono",title:y.taskMdPath||"",children:y.taskMdPath||"-"})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"lastRun"}),o.jsx("span",{children:fu(String(y.lastRunTimestamp||""),s)})]})]})}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:"Body"}),o.jsx("pre",{className:"h-[46vh] min-h-[20rem] overflow-auto rounded-[20px] bg-secondary px-4 py-3.5 text-[12px] leading-relaxed text-foreground/90",children:y.body||"-"})]})]}),o.jsx(wt,{title:"Runtime",description:"最近执行记录、状态与运行详情。",bodyClassName:"min-h-0",actions:o.jsx("div",{className:"flex items-center gap-1.5",children:o.jsx(be,{size:"sm",variant:"outline",onClick:async()=>{var J;const G=String(y.title||"").trim();if(!(!G||!await h({title:"清空 Run Log",description:`确认清理任务「${G}」的全部 run 记录?`,confirmText:"清空",cancelText:"取消",confirmVariant:"destructive"}))){k(!0);try{if(!await d(G))return;const ge=await se(G,{showLoading:!1,preferInProgress:!0});String(((J=ge[0])==null?void 0:J.timestamp)||"").trim()||(S(""),C(null),H(!1))}finally{k(!1)}}},disabled:A||q,children:q?"清理中...":"清空 Run Log"})}),children:b.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-4 py-5 text-sm text-muted-foreground",children:"暂无执行记录"}):o.jsx("div",{className:"max-h-[62vh] space-y-1.5 overflow-y-auto pr-1",children:b.map(G=>{const L=G.inProgress?"running":String(G.status||G.executionStatus||"unknown"),J=String(G.timestamp||"")===String(v||""),me=String(G.timestamp||"").trim(),ge=T===me;return o.jsxs("div",{className:"flex items-start gap-1.5",children:[o.jsxs("button",{type:"button",className:Me("min-w-0 flex-1 rounded-[18px] px-3.5 py-3 text-left transition-colors",J?"bg-secondary":"bg-transparent hover:bg-secondary"),onClick:()=>{S(G.timestamp),H(!0)},children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsx("div",{className:"text-xs font-medium text-foreground/90",children:fu(G.timestamp,s)}),o.jsx(An,{variant:"outline",className:D(L),children:L})]}),o.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-3 text-[11px] text-muted-foreground",children:[o.jsx("span",{children:`start ${s(G.startedAt)}`}),o.jsx("span",{children:`duration ${l7(G.startedAt,G.endedAt)}`}),o.jsx("span",{children:`rounds ${G.dialogueRounds??G.progressRound??"-"}`})]})]}),o.jsx(be,{size:"icon",variant:"ghost",className:`mt-1 ${Ro}`,disabled:!!G.inProgress||ge,onClick:async()=>{var ce;if(!(!oe||!me||!await h({title:"删除 Run 记录",description:`确认删除 run「${me}」记录?`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"}))){E(me);try{if(!await u(oe,me))return;const K=await se(oe,{showLoading:!1,preferInProgress:!0});if(!K.some(he=>String(he.timestamp||"").trim()===me)&&String(v||"").trim()===me){const he=String(((ce=K[0])==null?void 0:ce.timestamp)||"").trim();S(he),he||(C(null),H(!1))}}finally{E("")}}},title:"删除 run","aria-label":"删除 run",children:ge?o.jsx(er,{className:"size-3.5 animate-pulse"}):o.jsx(er,{className:"size-3.5"})})]},G.timestamp)})})})]}),o.jsx($n,{open:N,onOpenChange:H,children:o.jsxs(Un,{className:"w-[min(96vw,980px)] p-0",children:[o.jsxs(Hn,{className:"bg-secondary px-4 py-4",children:[o.jsx(Fn,{children:`Run Detail${v?` · ${fu(v,s)}`:""}`}),o.jsx(os,{children:(y==null?void 0:y.title)||"-"})]}),o.jsx("div",{className:"max-h-[68vh] space-y-3 overflow-y-auto px-4 py-4",children:O?o.jsx("div",{className:"text-sm text-muted-foreground",children:"加载中..."}):j?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-[18px] bg-secondary px-3.5 py-3 text-xs text-muted-foreground",children:[o.jsx("div",{children:`runDir: ${j.runDirRel||"-"}`}),o.jsx("div",{children:`status: ${c7(B,j)}`}),o.jsx("div",{children:`phase: ${String(((xe=j.progress)==null?void 0:xe.phase)||"-")}`}),o.jsx("div",{children:`message: ${String(((ee=j.progress)==null?void 0:ee.message)||"-")}`}),o.jsx("div",{children:`updatedAt: ${s((W=j.progress)==null?void 0:W.updatedAt)}`}),o.jsx("div",{children:`error: ${String(((X=j.meta)==null?void 0:X.error)||"-")}`})]}),o.jsx("div",{className:"grid gap-3 xl:grid-cols-2",children:["input","output","result","dialogue","error"].map(G=>{var L;return o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:G}),o.jsx("pre",{className:"max-h-56 overflow-auto rounded-[16px] bg-card px-3 py-2.5 text-[11px] leading-relaxed",children:String(((L=j.artifacts)==null?void 0:L[G])||"-")})]},G)})})]}):o.jsx("div",{className:"text-sm text-muted-foreground",children:"未找到执行详情"})})]})})]})}function d7(e){const{message:t,type:n}=e;return o.jsx("div",{className:Me("fixed right-5 bottom-5 z-50 rounded-[18px] px-4 py-2.5 text-sm shadow-[0_10px_26px_rgba(24,24,27,0.06)] backdrop-blur-sm",n==="success"&&"bg-card text-foreground",n==="error"&&"bg-destructive/10 text-destructive",n==="info"&&"bg-card text-muted-foreground"),children:t})}function f7(e){const[t,n]=c.useState("");return c.useEffect(()=>{var a,i;const s=((a=e.board)==null?void 0:a.agents)||[];if(s.length===0){n("");return}s.find(l=>l.id===t)||n(((i=s[0])==null?void 0:i.id)||"")},[e.board,t]),o.jsxs("section",{className:"space-y-4",children:[e.errorMessage?o.jsx("div",{className:"rounded-[22px] border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive",children:e.errorMessage}):null,o.jsx(mz,{board:e.board,loading:e.loading,selectedAgentId:t,onSelectAgent:n,onRefresh:e.onRefresh})]})}function g7(e){const{viewLabel:t,rightActions:n}=e,s=c.useMemo(()=>{const r=String(t||"").trim();if(!r)return"Overview";const a=r.toLowerCase();return a.includes("global")?r.replace(/global\s*/i,"").trim()||"Overview":a.includes("context")?"Chat":a.includes("agent")?r.replace(/agent\s*/i,"").trim()||"Agent":r},[t]);return o.jsx("header",{className:"flex h-(--header-height) shrink-0 items-center gap-2 bg-transparent transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-(--header-height)",children:o.jsx("div",{className:"flex w-full flex-wrap items-center gap-2 px-3 py-2 md:px-4 lg:gap-2 lg:px-5",children:o.jsxs("div",{className:"flex h-10 w-full items-center gap-2 rounded-[18px] bg-transparent px-2.5",children:[o.jsx(Cz,{className:"-ml-0.5"}),o.jsx("h1",{className:"text-[0.95rem] font-medium tracking-[-0.02em] text-foreground",children:s}),o.jsx("div",{className:"ml-auto flex items-center",children:n})]})})})}const Sx="city.console-ui.auth.v1";class Lu extends Error{constructor(n,s,r){super(n);at(this,"status");at(this,"statusText");this.name="ConsoleApiError",this.status=s,this.statusText=r}}function Id(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Sx);if(!e)return null;const t=JSON.parse(e),n=String((t==null?void 0:t.token)||"").trim();if(!n)return null;const s=String((t==null?void 0:t.username)||"").trim();return{token:n,...s?{username:s}:{}}}catch{return null}}function m7(e){if(typeof window>"u")return;const t=String(e.token||"").trim();if(!t)return;const n=String(e.username||"").trim();window.localStorage.setItem(Sx,JSON.stringify({token:t,...n?{username:n}:{}}))}function D0(){typeof window>"u"||window.localStorage.removeItem(Sx)}function qj(e,t,n){const s=String(e||"");if(!s.startsWith("/api/")||s.startsWith("/api/ui/"))return s;const r=n??t;if(!r)return s;const a=new URL(s,window.location.origin);return a.searchParams.set("agent",r),`${a.pathname}${a.search}`}async function Bu(e){var i;const t=Id(),n=new Headers((i=e.options)==null?void 0:i.headers);n.has("Content-Type")||n.set("Content-Type","application/json"),t!=null&&t.token&&!n.has("Authorization")&&n.set("Authorization",`Bearer ${t.token}`);const s=await fetch(qj(e.path,e.selectedAgentId,e.preferredAgentId),{...e.options||{},headers:n}),r=await s.text();let a=null;try{a=r?JSON.parse(r):{}}catch{a=null}if(!s.ok){const l=typeof(a==null?void 0:a.error)=="string"?a.error:typeof(a==null?void 0:a.message)=="string"?a.message:`${s.status} ${s.statusText}`;throw new Lu(l,s.status,s.statusText)}if(a&&a.success===!1){const l=typeof a.error=="string"?a.error:typeof a.message=="string"?a.message:"request failed";throw new Lu(l,s.status,s.statusText)}if(a===null)throw new Lu(`Invalid JSON response from ${e.path}`,s.status,s.statusText);return a}const ve={authStatus:()=>"/api/auth/status",authMe:()=>"/api/auth/me",authTokenList:()=>"/api/auth/token/list",authTokenCreate:()=>"/api/auth/token/create",authTokenDelete:()=>"/api/auth/token/delete",uiAgents:e=>e?`/api/ui/agents?agent=${encodeURIComponent(e)}`:"/api/ui/agents",uiAgentRuntimeStatus:e=>`/api/ui/agents/runtime-status?agent=${encodeURIComponent(e)}`,uiLocalModels:()=>"/api/ui/local-models",uiPlugins:e=>e?`/api/ui/plugins?agent=${encodeURIComponent(e)}`:"/api/ui/plugins",uiPluginsAction:e=>e?`/api/ui/plugins/action?agent=${encodeURIComponent(e)}`:"/api/ui/plugins/action",uiModel:e=>e?`/api/ui/model?agent=${encodeURIComponent(e)}`:"/api/ui/model",uiModelSwitch:e=>`/api/ui/model/switch?agent=${encodeURIComponent(e)}`,uiConfigStatus:e=>e?`/api/ui/config-status?agent=${encodeURIComponent(e)}`:"/api/ui/config-status",uiAgentEnv:e=>`/api/ui/env?scope=agent&agent=${encodeURIComponent(e)}`,overview:(e=40)=>`/api/dashboard/overview?sessionLimit=${encodeURIComponent(String(e))}`,workboardSnapshot:()=>"/api/workboard/snapshot",services:()=>"/api/dashboard/services",sessions:(e=120)=>`/api/dashboard/sessions?limit=${encodeURIComponent(String(e))}`,sessionMessages:(e,t=100)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/messages?limit=${encodeURIComponent(String(t))}`,sessionArchives:(e,t=80)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/archives?limit=${encodeURIComponent(String(t))}`,sessionArchiveDetail:(e,t)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/archives/${encodeURIComponent(t)}`,sessionExecute:e=>`/api/dashboard/sessions/${encodeURIComponent(e)}/execute`,sessionClearMessages:e=>`/api/dashboard/sessions/${encodeURIComponent(e)}/messages`,sessionClearChatHistory:e=>`/api/dashboard/sessions/${encodeURIComponent(e)}/chat-history`,systemPrompt:e=>`/api/dashboard/system-prompt?sessionId=${encodeURIComponent(e)}`,tasks:()=>"/api/dashboard/tasks",taskRun:()=>"/api/dashboard/tasks/run",taskStatus:e=>`/api/dashboard/tasks/${encodeURIComponent(e)}/status`,taskDetail:e=>`/api/dashboard/tasks/${encodeURIComponent(e)}`,taskRuns:(e,t=50)=>`/api/dashboard/tasks/${encodeURIComponent(e)}/runs?limit=${encodeURIComponent(String(t))}`,taskRunDetail:(e,t)=>`/api/dashboard/tasks/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}`,logs:(e=260)=>`/api/dashboard/logs?limit=${encodeURIComponent(String(e))}`,authorization:()=>"/api/dashboard/authorization",authorizationConfig:()=>"/api/dashboard/authorization/config",authorizationAction:()=>"/api/dashboard/authorization/action",localMessages:(e,t=80)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/messages?limit=${encodeURIComponent(String(t))}`,servicesCommand:()=>"/api/services/command",servicesControl:()=>"/api/services/control",pluginsAction:()=>"/api/plugins/action",uiModelPool:()=>"/api/ui/model/pool",uiEnv:()=>"/api/ui/env",uiChannelAccounts:()=>"/api/ui/channel-accounts",uiAgentStart:()=>"/api/ui/agents/start",uiAgentCreate:()=>"/api/ui/agents/create",uiAgentInspect:()=>"/api/ui/agents/inspect",uiAgentExecution:()=>"/api/ui/agents/execution",uiPickDirectory:()=>"/api/ui/system/pick-directory",uiAgentRestart:()=>"/api/ui/agents/restart",uiAgentStop:()=>"/api/ui/agents/stop",uiCommandExecute:()=>"/api/ui/command/execute",uiModelProviderUpsert:()=>"/api/ui/model/provider/upsert",uiModelProviderRemove:()=>"/api/ui/model/provider/remove",uiModelProviderTest:()=>"/api/ui/model/provider/test",uiModelProviderDiscover:()=>"/api/ui/model/provider/discover",uiModelItemUpsert:()=>"/api/ui/model/model/upsert",uiModelItemRemove:()=>"/api/ui/model/model/remove",uiModelItemPause:()=>"/api/ui/model/model/pause",uiModelItemTest:()=>"/api/ui/model/model/test",uiChannelAccountUpsert:()=>"/api/ui/channel-accounts/upsert",uiChannelAccountProbe:()=>"/api/ui/channel-accounts/probe",uiChannelAccountRemove:()=>"/api/ui/channel-accounts/remove",uiEnvUpsert:()=>"/api/ui/env/upsert",uiEnvImport:()=>"/api/ui/env/import",uiEnvRemove:()=>"/api/ui/env/remove"},Js="consoleui-chat-main";function Le(e){return e instanceof Error?e.message:String(e)}function Gj(e){const t=String(e||"").toLowerCase();return t.includes("no running agent found")||t.includes("start one via `city agent start` first")||t.includes("no running agent selected")}function kf(e){const t=String(e||"").toLowerCase();return Gj(t)||t.includes("service unavailable")||t.includes("selected agent runtime endpoint is unavailable")||t.includes("503")}function h7(e){const t=String(e||"").toLowerCase();return t.includes("service")&&t.includes("chat")&&t.includes("未启动")||t.includes("service")&&t.includes("chat")&&t.includes("not started")||t.includes("service")&&t.includes("chat")&&t.includes("not start")||t.includes("chat")&&t.includes("not running")}function mh(e){const t=String(e||"").toLowerCase();return t.includes("404")||t.includes("not found")}function Vj(e){if(typeof e=="object"&&e!==null&&"status"in e)return Number(e.status)===401;const t=Le(e).toLowerCase();return t.includes("missing bearer token")||t.includes("invalid bearer token")||t.includes("token is revoked")||t.includes("token is expired")||t.includes("user not found for token")}function p7(e){const t=String(e||"").toLowerCase();return["running","ok","active","enabled","success"].includes(t)?"ok":["stopped","disabled","paused","error","failed","offline"].includes(t)?"bad":"warn"}function x7(e){if(e==null)return"-";const t=typeof e=="number"?e:Date.parse(String(e));return!Number.isFinite(t)||Number.isNaN(t)?"-":new Date(t).toLocaleString("zh-CN",{hour12:!1})}function b7(e){var s,r;const t=((s=e.availability)==null?void 0:s.enabled)===!0,n=((r=e.availability)==null?void 0:r.available)===!0;return t?n?"available":"unavailable":"disabled"}function y7(e){return e.map(t=>{var s,r;const n=Array.isArray((s=t.availability)==null?void 0:s.reasons)?(r=t.availability)==null?void 0:r.reasons:[];return{...t,state:b7(t),lastError:n.length>0?n.join("; "):""}})}function dl(e){return new Promise(t=>{window.setTimeout(t,e)})}function v7(e){const t=String(e||"").trim().toLowerCase();return t?t.startsWith("consoleui-")||t==="local_ui":!1}function w7(e,t){return t.map((n,s)=>{const r=String(n.role||"").trim().toLowerCase(),a=n.ts,i=typeof a=="number"?a:Number.isFinite(Date.parse(String(a||"")))?Date.parse(String(a||"")):Date.now();return{id:String(n.id||`${e}:timeline:${s}`),sessionId:e,contextId:e,channel:"consoleui",direction:r==="user"?"inbound":"outbound",ts:i,text:String(n.text||""),...r==="user"?{actorName:"user"}:{actorName:"agent"}}})}async function S7(e){var g,m,h,x;const t=String(e.preferredAgentId||e.selectedAgentId||"").trim(),n=ve.uiAgents(t||void 0);let s;try{s=await e.requestJson(n)}catch(y){const w=Le(y);if(Gj(w))return{nextAgentId:"",list:[],cityVersion:""};throw y}const r=Array.isArray(s.agents)?s.agents:[],a=String(s.cityVersion||"").trim(),i=t&&((g=r.find(y=>y.id===t))==null?void 0:g.id)||"",l=String(s.selectedAgentId||"").trim(),u=l&&((m=r.find(y=>y.id===l))==null?void 0:m.id)||"",d=((h=r.find(y=>y.running===!0))==null?void 0:h.id)||"",f=((x=r[0])==null?void 0:x.id)||"";return{nextAgentId:i||u||d||f,list:r,cityVersion:a}}async function j7(e,t){return t?e(ve.overview(40),{},t):null}async function C7(e,t){if(!t)return[];const n=await e(ve.services(),{},t);return Array.isArray(n.services)?n.services:[]}async function k7(e,t){var n;if(!t)return[];try{const s=await e(ve.pluginsAction(),{method:"POST",body:JSON.stringify({pluginName:"skill",actionName:"list",payload:{}})},t);return Array.isArray((n=s==null?void 0:s.data)==null?void 0:n.skills)?s.data.skills:[]}catch(s){const r=Le(s);if(/404|not found|unknown action|unknown plugin/i.test(r)||kf(r))return[];throw s}}async function jx(e){const t=String(e.agentId||"").trim();if(!t)throw new Error("当前无可用 agent");const n=String(e.command||"").trim();if(!n)throw new Error("skill command 不能为空");const s=e.payload??{};return e.requestJson(ve.pluginsAction(),{method:"POST",body:JSON.stringify({pluginName:"skill",actionName:n,payload:s})},t)}async function Cx(e){const t=String(e.agentId||"").trim();if(!t)return{running:!1,servicesReady:!1};const n=Number.isFinite(e.maxRetry)?Number(e.maxRetry):36,s=Number.isFinite(e.intervalMs)?Number(e.intervalMs):500;let r=!1;for(let a=0;a<n;a+=1){try{const i=await e.requestJson(ve.uiAgents(t)),u=(Array.isArray(i.agents)?i.agents:[]).find(d=>String(d.id||"")===t);r=(u==null?void 0:u.running)===!0}catch{r=!1}if(!r){await dl(s);continue}try{const i=await e.requestJson(ve.uiAgentRuntimeStatus(t));if(i.running!==!0){await dl(s);continue}if(i.serverReady!==!0){await dl(s);continue}if(i.servicesReady===!0)return{running:!0,servicesReady:!0};await dl(s);continue}catch(i){const l=Le(i);kf(l)}await dl(s)}return{running:r,servicesReady:!1}}async function _0(e,t){const n=await e(ve.uiPlugins(t)),s=Array.isArray(n.plugins)?n.plugins:[];return y7(s)}async function N7(e,t){const n=await e(ve.uiLocalModels(),{method:"POST",body:JSON.stringify(t?{projectRoot:t}:{})});return Array.isArray(n.models)?n.models.map(s=>String(s||"").trim()).filter(Boolean):[]}async function T7(e,t){var n;if(!t)return[];try{const s=await e(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"status",payload:{}})},t);return[...Array.isArray((n=s==null?void 0:s.data)==null?void 0:n.channels)?s.data.channels:[],{channel:"consoleui",enabled:!0,configured:!0,running:!0,linkState:"connected",statusText:"console-ui built-in channel",detail:{readonly:!0,managedBy:"console-ui"}}]}catch(s){const r=Le(s);if(h7(r)||kf(r))return[{channel:"consoleui",enabled:!0,configured:!0,running:!0,linkState:"connected",statusText:"console-ui built-in channel",detail:{readonly:!0,managedBy:"console-ui"}}];throw s}}async function A7(e,t){if(!t)return[];const n=await e(ve.sessions(120),{},t),s=Array.isArray(n.sessions)?n.sessions:[];return s.some(a=>String(a.sessionId||"").trim()===Js)?s:[{sessionId:Js,channel:"consoleui",messageCount:0,updatedAt:Date.now(),lastRole:"system",lastText:"consoleui channel"},...s]}async function E7(e,t,n){var a;if(!t||!n)return[];try{const i=await e(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"history",payload:{sessionId:n,limit:80}})},t),l=Array.isArray((a=i==null?void 0:i.data)==null?void 0:a.events)?i.data.events:[];if(l.length>0||!String(n||"").startsWith("consoleui-"))return l}catch(i){if(!(String(n||"").trim().toLowerCase().startsWith("consoleui-")||String(n||"").trim().toLowerCase()==="local_ui"))throw i}const s=await e(ve.sessionMessages(n,100),{},t),r=Array.isArray(s.messages)?s.messages:[];return w7(n,r)}async function M7(e,t,n){if(!t||!n)return[];const s=await e(ve.sessionMessages(n,100),{},t);return Array.isArray(s.messages)?s.messages:[]}async function R7(e,t,n,s){return e(ve.sessionArchiveDetail(n,s),{},t)}async function O7(e,t,n){if(!t||!n)return[];try{const s=await e(ve.sessionArchives(n,80),{},t);return Array.isArray(s.archives)?s.archives:[]}catch(s){if(mh(Le(s)))return[];throw s}}async function z7(e,t){if(!t)return[];const n=await e(ve.tasks(),{},t);return Array.isArray(n.tasks)?n.tasks:[]}async function I7(e,t){if(!t)return[];const n=await e(ve.logs(260),{},t);return Array.isArray(n.logs)?n.logs:[]}async function D7(e,t){try{const n=ve.uiModel(t||void 0);return(await e(n,{},t)).model||null}catch(n){if(/404|not found/i.test(Le(n)))return null;throw n}}async function _7(e,t){const n=ve.uiConfigStatus(t||void 0),s=await e(n,{},t);return Array.isArray(s.items)?s.items:[]}async function L7(e){const t=await e(ve.uiModelPool());return{providers:Array.isArray(t.providers)?t.providers:[],models:Array.isArray(t.models)?t.models:[]}}async function B7(e){const t=await e(ve.uiEnv());return Array.isArray(t.items)?t.items:[]}async function P7(e,t){if(!t)return[];const n=await e(ve.uiAgentEnv(t));return Array.isArray(n.items)?n.items:[]}async function $7(e){const t=await e(ve.uiChannelAccounts());return Array.isArray(t.items)?t.items:[]}async function U7(e,t,n){if(!t)return null;const s=String(n).trim()||Js;try{return await e(ve.systemPrompt(s),{},t)}catch(r){if(/404|not found/i.test(Le(r)))return null;throw r}}async function H7(e,t){if(!t)return[];const n=await e(ve.localMessages(Js,80),{},t);return Array.isArray(n.messages)?n.messages:[]}async function F7(e,t){return t?e(ve.authorization(),{},t):null}async function q7(e){try{await e.requestJson(ve.servicesControl(),{method:"POST",body:JSON.stringify({serviceName:e.serviceName,action:e.action})}),e.showToast(`service ${e.serviceName} ${e.action} 已执行`,"success"),await Promise.all([e.refreshServices(e.selectedAgentId),e.refreshSkills(e.selectedAgentId)])}catch(t){e.showToast(`service 操作失败: ${Le(t)}`,"error")}}async function L0(e){try{const t=Id(),n=e.scope==="global"?"global":"agent",s=n==="global"?ve.uiPluginsAction(e.selectedAgentId):qj(ve.pluginsAction(),e.selectedAgentId),r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...t!=null&&t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({pluginName:e.pluginName,actionName:e.actionName,payload:e.payload})}),a=await r.text(),i=a?JSON.parse(a):{},l=String((i==null?void 0:i.message)||(i==null?void 0:i.error)||`${e.pluginName} ${e.actionName}`).trim(),u=G7(i==null?void 0:i.data,l),d=e.actionName==="on"||e.actionName==="off"||e.actionName==="install"||e.actionName==="configure"||e.actionName==="use";return d&&n==="global"&&e.refreshGlobalPlugins&&e.refreshGlobalPlugins().catch(()=>{}),d&&n==="agent"&&e.selectedAgentId&&e.refreshPlugins(e.selectedAgentId).catch(()=>{}),e.showToast(`plugin ${e.pluginName} ${e.actionName}: ${l}`,r.ok&&(i!=null&&i.success)?"success":"error"),{success:r.ok&&(i==null?void 0:i.success)===!0,message:l,data:i==null?void 0:i.data,logs:u}}catch(t){const n=Le(t);return e.showToast(`plugin 操作失败: ${n}`,"error"),{success:!1,message:n}}}function G7(e,t){const n=e&&typeof e=="object"?e:null,r=(Array.isArray(n==null?void 0:n.logs)?n.logs:n!=null&&n.details&&typeof n.details=="object"&&Array.isArray(n.details.logs)?n.details.logs:[]).map(a=>String(a||"").trim()).filter(Boolean);return r.length>0?r:t?[t]:[]}async function V7(e){var t;try{const n=e.channel?{channel:e.channel}:{},s=await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:e.action,payload:n})});if(e.action==="test"){const r=Array.isArray((t=s==null?void 0:s.data)==null?void 0:t.results)?s.data.results:[],a=e.channel?r.find(f=>String(f.channel||"")===e.channel):r[0],i=String((a==null?void 0:a.message)||"test completed");e.showToast(`${e.channel||"chat"} test: ${i}`,a!=null&&a.success?"success":"error");const l=e.chatChannels.find(f=>String(f.channel||"").trim()===String(e.channel||"").trim()),u=String((l==null?void 0:l.linkState)||"").trim().toLowerCase();!!e.channel&&!!(a!=null&&a.success)&&u!=="connected"&&(await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"reconnect",payload:{channel:e.channel}})}),e.showToast(`${e.channel} test 通过,已自动 reconnect`,"success"))}else e.action==="open"||e.action==="close"?e.showToast(`${e.channel||"chat"} ${e.action} 已执行(已写入 downcity.json)`,"success"):e.showToast(`${e.channel||"chat"} ${e.action} 已执行`,"success");await Promise.all([e.refreshChatChannels(e.selectedAgentId),e.refreshServices(e.selectedAgentId)])}catch(n){e.showToast(`chat ${e.action} 失败: ${Le(n)}`,"error")}}async function Y7(e){const t=String(e.channel||"").trim();if(t)try{await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"configure",payload:{channel:t,config:e.config,restart:!0}})}),e.showToast(`${t} 配置已保存并重载`,"success"),await e.refreshDashboard(e.selectedAgentId)}catch(n){e.showToast(`配置 ${t} 失败: ${Le(n)}`,"error")}}async function K7(e){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}try{const t=await e.requestJson(ve.authorizationConfig(),{method:"POST",body:JSON.stringify({config:e.config})},e.selectedAgentId);e.setAuthorization(t),e.showToast("authorization 配置已保存","success")}catch(t){e.showToast(`保存 authorization 失败: ${Le(t)}`,"error")}}async function X7(e){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}try{const t=await e.requestJson(ve.authorizationAction(),{method:"POST",body:JSON.stringify(e.input)},e.selectedAgentId);e.setAuthorization(t),e.showToast(`authorization ${e.input.action} 已执行`,"success")}catch(t){e.showToast(`authorization ${e.input.action} 失败: ${Le(t)}`,"error")}}async function Z7(e){const t=String(e.query||"").trim();if(!t)return e.showToast("请输入要查找的 skill 关键词","error"),null;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),null;const n={query:t};try{const s=await jx({requestJson:e.requestJson,agentId:e.selectedAgentId,command:"find",payload:n}),r=(s==null?void 0:s.data)||null;return e.showToast((r==null?void 0:r.message)||`已执行 skill find: ${t}`,"success"),await e.refreshSkills(e.selectedAgentId),r}catch(s){return e.showToast(`skill find 失败: ${Le(s)}`,"error"),null}}async function J7(e){const t=String(e.input.spec||"").trim();if(!t)return e.showToast("请输入要安装的 skill spec","error"),null;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),null;const n={spec:t,global:e.input.global!==!1,yes:e.input.yes!==!1,agent:String(e.input.agent||"claude-code").trim()||"claude-code"};try{const s=await jx({requestJson:e.requestJson,agentId:e.selectedAgentId,command:"install",payload:n}),r=(s==null?void 0:s.data)||null;return e.showToast((r==null?void 0:r.message)||`skill 安装完成: ${t}`,"success"),await e.refreshSkills(e.selectedAgentId),r}catch(s){return e.showToast(`skill install 失败: ${Le(s)}`,"error"),null}}async function Q7(e){var n;const t=String(e.name||"").trim();if(!t)return e.showToast("请输入 skill 名称","error"),null;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),null;try{const s=await jx({requestJson:e.requestJson,agentId:e.selectedAgentId,command:"lookup",payload:{name:t}}),r=(s==null?void 0:s.data)||null,a=String(((n=r==null?void 0:r.skill)==null?void 0:n.name)||t).trim()||t;return e.showToast((r==null?void 0:r.message)||`skill lookup 已执行: ${a}`,"success"),r}catch(s){return e.showToast(`skill lookup 失败: ${Le(s)}`,"error"),null}}async function W7(e){const t=String(e.primaryModelId||"").trim();if(t){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}try{await e.requestJson(ve.uiModelSwitch(e.selectedAgentId),{method:"POST",body:JSON.stringify({primaryModelId:t})},e.selectedAgentId),await e.refreshModel(e.selectedAgentId),e.showToast("agent model.primary 已更新(需重启 agent 完整生效)","success")}catch(n){e.showToast(`model.primary 更新失败: ${Le(n)}`,"error")}}}async function eD(e){const t=String(e.agentId||"").trim(),n=String(e.primaryModelId||"").trim();if(!(!t||!n))try{await e.requestJson(ve.uiModelSwitch(t),{method:"POST",body:JSON.stringify({primaryModelId:n})},t),await e.refreshDashboard(e.selectedAgentId||t),e.showToast(`已更新 ${t} 的 model.primary(需重启 agent 生效)`,"success")}catch(s){e.showToast(`agent model.primary 更新失败: ${Le(s)}`,"error")}}async function tD(e){const t=String(e.agentId||"").trim();if(t)try{await e.requestJson(ve.uiAgentExecution(),{method:"POST",body:JSON.stringify({projectRoot:t,executionMode:e.executionMode,modelId:e.modelId,localModel:e.localModel,agentType:e.agentType})},t),await e.refreshDashboard(e.selectedAgentId||t),e.showToast(`已更新 ${t} 的 execution(需重启 agent 生效)`,"success")}catch(n){e.showToast(`agent execution 更新失败: ${Le(n)}`,"error")}}async function nD(e){var n,s;const t=String(e.agentId||"").trim();if(t)try{const r=await e.requestJson(ve.uiAgentStart(),{method:"POST",body:JSON.stringify({agentId:t,initializeIfNeeded:((n=e.options)==null?void 0:n.initializeIfNeeded)===!0,initialization:(s=e.options)!=null&&s.initialization?{agentName:e.options.initialization.agentName,executionMode:e.options.initialization.executionMode,modelId:e.options.initialization.modelId,localModel:e.options.initialization.localModel,agentType:e.options.initialization.agentType}:void 0})}),a=await Cx({requestJson:e.requestJson,agentId:t,maxRetry:120,intervalMs:500});if(a.running&&a.servicesReady){await e.refreshDashboard(t),r.started===!0?e.showToast(`agent 已启动(pid ${String(r.pid||"-")})`,"success"):e.showToast("agent 已在运行","info");return}e.showToast("agent 启动超时:服务未全部就绪","error")}catch(r){e.showToast(`启动 agent 失败: ${Le(r)}`,"error")}}async function sD(e){const t=String(e.input.projectRoot||"").trim();if(t)try{const n=await e.requestJson(ve.uiAgentCreate(),{method:"POST",body:JSON.stringify({projectRoot:t,agentName:e.input.agentName,executionMode:e.input.executionMode,modelId:e.input.modelId,localModel:e.input.localModel,agentType:e.input.agentType,autoStart:e.input.autoStart!==!1})});if(e.input.autoStart===!1||n.started!==!0){await e.refreshDashboard(t),e.showToast(`agent 已创建:${String(n.agentName||t)}`,"success");return}const s=await Cx({requestJson:e.requestJson,agentId:t,maxRetry:120,intervalMs:500});if(s.running&&s.servicesReady){await e.refreshDashboard(t),e.showToast(`agent 已创建并启动(pid ${String(n.pid||"-")})`,"success");return}e.showToast("agent 创建成功,但启动超时:服务未全部就绪","error")}catch(n){e.showToast(`创建 agent 失败: ${Le(n)}`,"error")}}async function rD(e){const t=await e(ve.uiPickDirectory(),{method:"POST"});return String(t.directoryPath||"").trim()}async function oD(e,t){const n=String(t||"").trim();return n&&(await e(ve.uiAgentInspect(),{method:"POST",body:JSON.stringify({projectRoot:n})})).inspection||null}async function aD(e){const t=String(e.agentId||"").trim();if(t)try{await e.requestJson(ve.uiAgentRestart(),{method:"POST",body:JSON.stringify({agentId:t})});const n=await Cx({requestJson:e.requestJson,agentId:t,maxRetry:120,intervalMs:500});if(n.running&&n.servicesReady){await e.refreshDashboard(t),e.showToast("agent 已重启","success");return}e.showToast("agent 重启超时:服务未全部就绪","error")}catch(n){const s=Le(n);if(/not found/i.test(s)){e.showToast("当前 Console UI 进程版本过旧,请先重启 `city console ui` 后再重启 agent","error");return}e.showToast(`重启 agent 失败: ${s}`,"error")}}async function iD(e){const t=String(e.agentId||"").trim();if(t)try{await e.requestJson(ve.uiAgentStop(),{method:"POST",body:JSON.stringify({agentId:t})});const n=20,s=400;let r=!1;for(let a=0;a<n;a+=1){const i=await e.requestJson(ve.uiAgents(t)),u=(Array.isArray(i.agents)?i.agents:[]).find(d=>String(d.id||"")===t);if(!u||u.running!==!0){r=!0;break}await new Promise(d=>window.setTimeout(d,s))}if(await e.refreshDashboard(e.selectedAgentId||t),r){e.showToast("agent 已停止","success");return}e.showToast("agent 停止中,请稍后刷新","info")}catch(n){const s=Le(n);if(/not found/i.test(s)){e.showToast("当前 Console UI 进程版本过旧,请先重启 `city console ui` 后再停止 agent","error");return}e.showToast(`停止 agent 失败: ${s}`,"error")}}async function Is(e){try{await e.requestJson(e.path,{method:"POST",body:JSON.stringify(e.body)}),e.after&&await e.after(),e.showToast(e.successMessage,"success")}catch(t){e.showToast(`${e.errorMessage}: ${Le(t)}`,"error")}}async function lD(e){try{const t=await e.requestJson(ve.uiChannelAccountProbe(),{method:"POST",body:JSON.stringify(e.input)}),n={channel:String(t.channel||e.input.channel||"").trim(),accountId:String(t.accountId||"").trim(),name:String(t.name||"").trim(),identity:String(t.identity||"").trim()||void 0,owner:String(t.owner||"").trim()||void 0,creator:String(t.creator||"").trim()||void 0,botUserId:String(t.botUserId||"").trim()||void 0,message:String(t.message||"").trim()||void 0};return!n.accountId||!n.name?(e.showToast("bot 信息探测成功,但返回数据不完整","error"),null):(e.showToast(n.message||"bot 信息探测成功","success"),n)}catch(t){return e.showToast(`bot 信息探测失败: ${Le(t)}`,"error"),null}}async function cD(e){try{const t=await e.requestJson(ve.uiModelProviderDiscover(),{method:"POST",body:JSON.stringify(e.input)}),n={providerId:String(t.providerId||e.input.providerId||"").trim(),discoveredModels:Array.isArray(t.discoveredModels)?t.discoveredModels:[],modelCount:Number(t.modelCount||0),autoAdded:Array.isArray(t.autoAdded)?t.autoAdded:[]};return e.input.autoAdd===!0?(await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)]),e.showToast(`discover 完成:${n.modelCount} 个,自动添加 ${n.autoAdded.length} 个`,"success")):e.showToast(`discover 完成:发现 ${n.modelCount} 个模型,请选择后添加`,"success"),n}catch(t){return e.showToast(`discover 失败: ${Le(t)}`,"error"),null}}async function B0(e){try{const t=await e.requestJson(ve.uiEnvImport(),{method:"POST",body:JSON.stringify({scope:e.scope,...e.agentId?{agentId:e.agentId}:{},raw:String(e.raw||"")})});await e.refresh();const n=Number(t.count||0),s=Array.isArray(t.keys)?t.keys.map(r=>String(r||"").trim()).filter(Boolean):[];e.showToast(n>0?`已批量导入 ${n} 个${e.scope==="global"?"全局":"agent"} env${s.length?`:${s.slice(0,3).join("、")}${s.length>3?"…":""}`:""}`:`已导入 ${e.scope==="global"?"全局":"agent"} env`,"success")}catch(t){throw e.showToast(`批量导入 env 失败: ${Le(t)}`,"error"),t}}async function uD(e){const t=String(e.input.command||"").trim(),n=String(e.input.agentId||e.selectedAgentId||"").trim();if(!t)throw new Error("command 不能为空");if(!n)throw new Error("当前无可用 agent");const s=await e.requestJson(ve.uiCommandExecute(),{method:"POST",body:JSON.stringify({agentId:n,command:t,timeoutMs:e.input.timeoutMs})},n);if(!s.result)throw new Error("command 执行失败:缺少结果");return s.result}async function dD(e){try{await e.requestJson(ve.taskRun(),{method:"POST",body:JSON.stringify({title:e.title,reason:"dashboard_manual_trigger"})}),e.showToast(`task ${e.title} 已触发`,"success"),await Promise.all([e.refreshTasks(e.selectedAgentId),e.refreshLogs(e.selectedAgentId)])}catch(t){e.showToast(`task 执行失败: ${Le(t)}`,"error")}}async function fD(e){const t=String(e.title||"").trim();if(!t)return e.showToast("task title 不能为空","error"),!1;try{const n=await e.requestJson(ve.taskStatus(t),{method:"POST",body:JSON.stringify({status:e.status})},e.selectedAgentId),s=String((n==null?void 0:n.status)||e.status).trim()||e.status;return e.showToast(`task ${t} 状态已更新为 ${s}`,"success"),await Promise.all([e.refreshTasks(e.selectedAgentId),e.refreshOverview(e.selectedAgentId)]),!0}catch(n){return e.showToast(`task 状态更新失败: ${Le(n)}`,"error"),!1}}async function gD(e){const t=String(e.title||"").trim();if(!t)return e.showToast("task title 不能为空","error"),!1;try{return await e.requestJson(ve.taskDetail(t),{method:"DELETE"},e.selectedAgentId),e.showToast(`task ${t} 已删除`,"success"),await Promise.all([e.refreshTasks(e.selectedAgentId),e.refreshOverview(e.selectedAgentId),e.refreshLogs(e.selectedAgentId)]),!0}catch(n){return e.showToast(`task 删除失败: ${Le(n)}`,"error"),!1}}async function mD(e){const t=String(e.title||"").trim();if(!t)return[];try{const n=await e.requestJson(ve.taskRuns(t,e.limit||50),{},e.selectedAgentId);return Array.isArray(n.runs)?n.runs:[]}catch(n){return e.showToast(`加载 task runs 失败: ${Le(n)}`,"error"),[]}}async function hD(e){const t=String(e.title||"").trim(),n=String(e.timestamp||"").trim();if(!t||!n)return e.showToast("task title 或 run timestamp 不能为空","error"),!1;try{return await e.requestJson(ve.taskRunDetail(t,n),{method:"DELETE"},e.selectedAgentId),e.showToast(`run ${n} 已删除`,"success"),await e.refreshLogs(e.selectedAgentId),!0}catch(s){return e.showToast(`删除 run 记录失败: ${Le(s)}`,"error"),!1}}async function pD(e){const t=String(e.title||"").trim();if(!t)return e.showToast("task title 不能为空","error"),!1;try{const n=await e.requestJson(ve.taskRuns(t),{method:"DELETE"},e.selectedAgentId),s=typeof n.deletedCount=="number"&&Number.isFinite(n.deletedCount)?n.deletedCount:0,r=typeof n.skippedRunningCount=="number"&&Number.isFinite(n.skippedRunningCount)?n.skippedRunningCount:0;return r>0?e.showToast(`已清理 ${s} 条 run,跳过 ${r} 条运行中记录`,"success"):e.showToast(`已清理 ${s} 条 run 记录`,"success"),await e.refreshLogs(e.selectedAgentId),!0}catch(n){return e.showToast(`清理 run 记录失败: ${Le(n)}`,"error"),!1}}async function xD(e){const t=String(e.title||"").trim(),n=String(e.timestamp||"").trim();if(!t||!n)return null;try{return await e.requestJson(ve.taskRunDetail(t,n),{},e.selectedAgentId)}catch(s){return e.showToast(`加载 run 详情失败: ${Le(s)}`,"error"),null}}function bD(e){e.setChannelHistory([]),e.setSessionMessages([]),e.setSessionArchives([]),e.setSelectedArchiveId(""),e.setSessionArchiveMessages([]),e.setPrompt(null)}function yD(e){var r,a,i;const t=((r=e.sessions.find(l=>l.sessionId===e.currentSessionId))==null?void 0:r.sessionId)||"",n=((a=e.sessions.find(l=>l.sessionId===Js))==null?void 0:a.sessionId)||"",s=((i=e.sessions[0])==null?void 0:i.sessionId)||"";return t||n||s}function vD(e){const t=c.useCallback(async s=>{e.setLoading(!0);try{const{nextAgentId:r,list:a}=await e.refreshAgents(s);if(!r){e.setSelectedAgentId(""),e.clearPanelDataForNoAgent(),await Promise.allSettled([e.refreshGlobalPlugins(),e.refreshPlugins(""),e.refreshModel(""),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshConfigStatus("")]),e.setAgentEnvItems([]),e.setTopbarError(!1),e.setTopbarStatus("Console 在线");return}const i=a.find(d=>d.id===r)||null;if(i&&i.running!==!0){e.clearPanelDataForNoAgent(),await Promise.allSettled([e.refreshGlobalPlugins(),e.refreshPlugins(""),e.refreshModel(r),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshAgentEnv(r),e.refreshConfigStatus(r)]),e.setTopbarError(!1),e.setTopbarStatus("Console 在线");return}const[,l]=await Promise.all([e.refreshChatChannels(r),e.refreshSessions(r)]);await Promise.all([e.refreshGlobalPlugins(),e.refreshAuthorization(r),e.refreshPlugins(r),e.refreshOverview(r),e.refreshServices(r),e.refreshSkills(r),e.refreshTasks(r),e.refreshLogs(r),e.refreshModel(r),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshAgentEnv(r),e.refreshConfigStatus(r),e.refreshLocalChat(r)]);const u=yD({sessions:l,currentSessionId:String(e.selectedSessionIdRef.current||"").trim()});e.setSelectedSessionId(u),u?await Promise.all([e.refreshChannelHistory(r,u),e.refreshSessionMessages(r,u),e.refreshSessionArchives(r,u),e.refreshPrompt(r,u)]):bD({setChannelHistory:e.setChannelHistory,setSessionMessages:e.setSessionMessages,setSessionArchives:e.setSessionArchives,setSelectedArchiveId:e.setSelectedArchiveId,setSessionArchiveMessages:e.setSessionArchiveMessages,setPrompt:e.setPrompt}),e.setAuthRequired(!1),e.setTopbarError(!1),e.setTopbarStatus("Console 在线")}catch(r){const a=Le(r);if(kf(a)){const i=String(s||e.selectedAgentId||"").trim();if(i)try{const l=await e.requestJson(ve.uiAgents(i)),d=(Array.isArray(l.agents)?l.agents:[]).find(f=>String(f.id||"")===i);if((d==null?void 0:d.running)===!0){e.setSelectedAgentId(i),e.setTopbarError(!1);return}}catch{}e.clearPanelDataForNoAgent(),e.setSelectedAgentId(""),await Promise.allSettled([e.refreshGlobalPlugins(),e.refreshPlugins(""),e.refreshModel(""),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshConfigStatus("")]),e.setAgentEnvItems([]),e.setTopbarError(!1),e.setTopbarStatus("Console 在线");return}if(Vj(r)){e.setAuthRequired(!0),e.setTopbarError(!0),e.setTopbarStatus("需要 Bearer Token");return}e.setTopbarError(!0),e.setTopbarStatus(`连接失败: ${a}`),e.showToast(`刷新失败: ${a}`,"error")}finally{e.setLoading(!1)}},[e]),n=c.useCallback(async s=>{const r=String(s||"").trim();e.setSelectedSessionId(r),!(!e.selectedAgentId||!r)&&await Promise.all([e.refreshChannelHistory(e.selectedAgentId,r),e.refreshSessionMessages(e.selectedAgentId,r),e.refreshSessionArchives(e.selectedAgentId,r),e.refreshPrompt(e.selectedAgentId,r)])},[e]);return{refreshDashboard:t,handleSessionChange:n}}function wD(e){var t;(t=e.setSelectedSessionId)==null||t.call(e,""),e.setChannelHistory([]),e.setSessionMessages([]),e.setSessionArchives([]),e.setSelectedArchiveId(""),e.setSessionArchiveMessages([]),e.setPrompt(null)}function SD(e){var r,a,i;const t=((r=e.sessions.find(l=>l.sessionId===e.currentSessionId))==null?void 0:r.sessionId)||"",n=((a=e.sessions.find(l=>l.sessionId===Js))==null?void 0:a.sessionId)||"",s=((i=e.sessions[0])==null?void 0:i.sessionId)||"";return t||n||s}function jD(e){const t=c.useCallback(async()=>{if(e.sending)return;const a=e.chatInput.trim();if(a){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}e.setSending(!0);try{const i=String(e.selectedSessionIdRef.current||"").trim(),l=i.startsWith("consoleui-")||i==="local_ui"?i:Js;await e.requestJson(ve.sessionExecute(l),{method:"POST",body:JSON.stringify({instructions:a})}),e.setChatInput(""),await Promise.all([e.refreshLocalChat(e.selectedAgentId),e.refreshChannelHistory(e.selectedAgentId,l),e.refreshSessionMessages(e.selectedAgentId,l),e.refreshSessionArchives(e.selectedAgentId,l),e.refreshPrompt(e.selectedAgentId,l),e.refreshLogs(e.selectedAgentId),e.refreshOverview(e.selectedAgentId)]),e.showToast("已发送到 consoleui channel","success")}catch(i){e.showToast(`发送失败: ${Le(i)}`,"error")}finally{e.setSending(!1)}}},[e]),n=c.useCallback(async a=>{const i=String(a||"").trim();if(i){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}if(!e.clearingSessionMessages){e.setClearingSessionMessages(!0);try{await e.requestJson(ve.sessionClearMessages(i),{method:"DELETE"},e.selectedAgentId),await Promise.all([e.refreshSessions(e.selectedAgentId),e.refreshChannelHistory(e.selectedAgentId,i),e.refreshSessionMessages(e.selectedAgentId,i),e.refreshSessionArchives(e.selectedAgentId,i),e.refreshPrompt(e.selectedAgentId,i),e.refreshOverview(e.selectedAgentId),e.refreshLogs(e.selectedAgentId)]),e.showToast("session messages 已清理","success")}catch(l){e.showToast(`清理 session messages 失败: ${Le(l)}`,"error")}finally{e.setClearingSessionMessages(!1)}}}},[e]),s=c.useCallback(async a=>{const i=String(a||"").trim();if(i){if(v7(i)){await n(i);return}if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}if(!e.clearingChatHistory){e.setClearingChatHistory(!0);try{await e.requestJson(ve.sessionClearChatHistory(i),{method:"DELETE"},e.selectedAgentId),await Promise.all([e.refreshChannelHistory(e.selectedAgentId,i),e.refreshLogs(e.selectedAgentId)]),e.showToast("chat history 已清理","success")}catch(l){e.showToast(`清理 chat history 失败: ${Le(l)}`,"error")}finally{e.setClearingChatHistory(!1)}}}},[n,e]),r=c.useCallback(async a=>{var l;const i=String(a||"").trim();if(!i)return!1;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),!1;if(e.deletingSessionId)return!1;e.setDeletingSessionId(i);try{const u=await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"delete",payload:{sessionId:i}})},e.selectedAgentId),d=((l=u==null?void 0:u.data)==null?void 0:l.deleted)===!0,f=await e.refreshSessions(e.selectedAgentId),g=SD({sessions:f,currentSessionId:String(e.selectedSessionIdRef.current||"").trim()});return g?(e.setSelectedSessionId(g),await Promise.all([e.refreshChannelHistory(e.selectedAgentId,g),e.refreshSessionMessages(e.selectedAgentId,g),e.refreshSessionArchives(e.selectedAgentId,g),e.refreshPrompt(e.selectedAgentId,g)])):wD({setSelectedSessionId:e.setSelectedSessionId,setChannelHistory:e.setChannelHistory,setSessionMessages:e.setSessionMessages,setSessionArchives:e.setSessionArchives,setSelectedArchiveId:e.setSelectedArchiveId,setSessionArchiveMessages:e.setSessionArchiveMessages,setPrompt:e.setPrompt}),await Promise.all([e.refreshChatChannels(e.selectedAgentId),e.refreshOverview(e.selectedAgentId),e.refreshLogs(e.selectedAgentId),e.refreshLocalChat(e.selectedAgentId)]),e.showToast(d?`已删除 session: ${i}`:`session 不存在,已同步状态: ${i}`,"success"),d}catch(u){return e.showToast(`删除 session 失败: ${Le(u)}`,"error"),!1}finally{e.setDeletingSessionId("")}},[e]);return{sendConsoleUiMessage:t,clearSessionMessages:n,clearChatHistory:s,deleteChatSession:r}}function CD(e){const t=c.useCallback(async z=>{await W7({requestJson:e.requestJson,primaryModelId:z,selectedAgentId:e.selectedAgentId,refreshModel:e.refreshModel,showToast:e.showToast})},[e]),n=c.useCallback(async(z,N)=>{await eD({requestJson:e.requestJson,agentId:z,primaryModelId:N,selectedAgentId:e.selectedAgentId,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),s=c.useCallback(async(z,N)=>{await nD({requestJson:e.requestJson,agentId:z,options:N,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),r=c.useCallback(async z=>{await sD({requestJson:e.requestJson,input:z,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),a=c.useCallback(async()=>rD(e.requestJson),[e]),i=c.useCallback(async z=>oD(e.requestJson,z),[e]),l=c.useCallback(async z=>{await aD({requestJson:e.requestJson,agentId:z,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),u=c.useCallback(async z=>{await iD({requestJson:e.requestJson,agentId:z,selectedAgentId:e.selectedAgentId,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),d=c.useCallback(async z=>{await tD({requestJson:e.requestJson,agentId:z.agentId,executionMode:z.executionMode,modelId:z.modelId,localModel:z.localModel,agentType:z.agentType,selectedAgentId:e.selectedAgentId,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),f=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiModelProviderUpsert(),body:z,successMessage:`provider ${z.id} 已保存`,errorMessage:"provider 保存失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),g=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiModelProviderRemove(),body:{providerId:z},successMessage:`provider ${z} 已删除`,errorMessage:"provider 删除失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),m=c.useCallback(async z=>{try{const N=await e.requestJson(ve.uiModelProviderTest(),{method:"POST",body:JSON.stringify({providerId:z})});e.showToast(`provider ${z} 测试通过,发现 ${Number(N.modelCount||0)} 个模型`,"success")}catch(N){e.showToast(`provider 测试失败: ${Le(N)}`,"error")}},[e]),h=c.useCallback(async z=>cD({requestJson:e.requestJson,input:z,selectedAgentId:e.selectedAgentId,refreshModelPool:e.refreshModelPool,refreshModel:e.refreshModel,showToast:e.showToast}),[e]),x=c.useCallback(async z=>{var N,H,R,I,T,E;await Is({requestJson:e.requestJson,path:ve.uiModelItemUpsert(),body:{...z,temperature:((N=z.temperature)==null?void 0:N.trim())||void 0,maxTokens:((H=z.maxTokens)==null?void 0:H.trim())||void 0,topP:((R=z.topP)==null?void 0:R.trim())||void 0,frequencyPenalty:((I=z.frequencyPenalty)==null?void 0:I.trim())||void 0,presencePenalty:((T=z.presencePenalty)==null?void 0:T.trim())||void 0,anthropicVersion:((E=z.anthropicVersion)==null?void 0:E.trim())||void 0},successMessage:`model ${z.id} 已保存`,errorMessage:"model 保存失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),y=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiModelItemRemove(),body:{modelId:z},successMessage:`model ${z} 已删除`,errorMessage:"model 删除失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),w=c.useCallback(async(z,N)=>{await Is({requestJson:e.requestJson,path:ve.uiModelItemPause(),body:{modelId:z,isPaused:N},successMessage:`model ${z} 已${N?"暂停":"恢复"}`,errorMessage:"model 状态更新失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),b=c.useCallback(async(z,N)=>{try{await e.requestJson(ve.uiModelItemTest(),{method:"POST",body:JSON.stringify({modelId:z,prompt:String(N||"").trim()||void 0})}),e.showToast(`model ${z} 测试通过`,"success")}catch(H){e.showToast(`model 测试失败: ${Le(H)}`,"error")}},[e]),p=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiChannelAccountUpsert(),body:z,successMessage:`channel account ${z.id} 已确认`,errorMessage:"channel account 确认失败",after:async()=>{await Promise.all([e.refreshChannelAccounts(),e.refreshChatChannels(e.selectedAgentId)])},showToast:e.showToast})},[e]),v=c.useCallback(async z=>lD({requestJson:e.requestJson,input:z,showToast:e.showToast}),[e]),S=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiChannelAccountRemove(),body:{id:z},successMessage:`channel account ${z} 已删除`,errorMessage:"channel account 删除失败",after:async()=>{await Promise.all([e.refreshChannelAccounts(),e.refreshChatChannels(e.selectedAgentId)])},showToast:e.showToast})},[e]),j=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiEnvUpsert(),body:{scope:"global",key:String(z.key||"").trim(),description:String(z.description||"").trim(),value:String(z.value??"")},successMessage:`env ${String(z.key||"").trim()} 已保存`,errorMessage:"env 保存失败",after:async()=>{await e.refreshGlobalEnv()},showToast:e.showToast})},[e]),C=c.useCallback(async z=>{await B0({requestJson:e.requestJson,scope:"global",raw:z,refresh:e.refreshGlobalEnv,showToast:e.showToast})},[e]),A=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiEnvRemove(),body:{scope:"global",key:String(z||"").trim()},successMessage:`env ${String(z||"").trim()} 已删除`,errorMessage:"env 删除失败",after:async()=>{await e.refreshGlobalEnv()},showToast:e.showToast})},[e]),M=c.useCallback(async z=>{const N=String(z.agentId||"").trim();if(!N){e.showToast("当前没有可写入的 agent","error");return}await Is({requestJson:e.requestJson,path:ve.uiEnvUpsert(),body:{scope:"agent",agentId:N,key:String(z.key||"").trim(),description:String(z.description||"").trim(),value:String(z.value??"")},successMessage:`agent env ${String(z.key||"").trim()} 已保存`,errorMessage:"agent env 保存失败",after:async()=>{await e.refreshAgentEnv(N)},showToast:e.showToast})},[e]),O=c.useCallback(async(z,N)=>{const H=String(z||"").trim();if(!H){e.showToast("当前没有可删除的 agent env","error");return}await Is({requestJson:e.requestJson,path:ve.uiEnvRemove(),body:{scope:"agent",agentId:H,key:String(N||"").trim()},successMessage:`agent env ${String(N||"").trim()} 已删除`,errorMessage:"agent env 删除失败",after:async()=>{await e.refreshAgentEnv(H)},showToast:e.showToast})},[e]),P=c.useCallback(async(z,N)=>{const H=String(z||"").trim();if(!H)throw e.showToast("当前没有可写入的 agent","error"),new Error("agentId is required");await B0({requestJson:e.requestJson,scope:"agent",agentId:H,raw:N,refresh:async()=>e.refreshAgentEnv(H),showToast:e.showToast})},[e]),$=c.useCallback(async z=>uD({requestJson:e.requestJson,input:z,selectedAgentId:e.selectedAgentId}),[e]);return{switchModel:t,switchModelForAgent:n,updateAgentExecution:d,startAgentFromHistory:s,createAgent:r,pickAgentDirectory:a,inspectAgentDirectory:i,restartAgentFromHistory:l,stopAgentFromHistory:u,upsertModelProvider:f,removeModelProvider:g,testModelProvider:m,discoverModelProvider:h,upsertModelPoolItem:x,removeModelPoolItem:y,setModelPoolItemPaused:w,testModelPoolItem:b,upsertChannelAccount:p,probeChannelAccount:v,removeChannelAccount:S,upsertGlobalEnv:j,importGlobalEnv:C,removeGlobalEnv:A,upsertAgentEnv:M,removeAgentEnv:O,importAgentEnv:P,executeAgentCommand:$}}async function kD(e){return e(ve.authMe())}async function ND(e){return e(ve.authTokenList())}async function TD(e){return(await e.requestJson(ve.authTokenCreate(),{method:"POST",body:JSON.stringify(e.input)})).token}async function AD(e){await e.requestJson(ve.authTokenDelete(),{method:"POST",body:JSON.stringify({tokenId:e.tokenId})})}function ED(e){const{enabled:t,requestJson:n,showToast:s}=e,[r,a]=c.useState(null),[i,l]=c.useState([]),[u,d]=c.useState(!1),[f,g]=c.useState(null),m=c.useCallback(async()=>{if(!t){a(null),l([]);return}d(!0);try{const[w,b]=await Promise.all([kD(n),ND(n)]);a(w.user||null),l(Array.isArray(b.tokens)?b.tokens:[])}finally{d(!1)}},[t,n]),h=c.useCallback(async w=>{const b=await TD({requestJson:n,input:w});g(b),s(`已签发 token ${b.name}`,"success"),await m()},[m,n,s]),x=c.useCallback(async w=>{await AD({requestJson:n,tokenId:w.tokenId}),s("已删除 token","success"),await m()},[m,n,s]),y=c.useCallback(()=>{g(null)},[]);return c.useEffect(()=>{if(!t){a(null),l([]),g(null);return}m().catch(w=>{s(Le(w),"error")})},[t,m,s]),{accessUser:r,accessTokens:i,accessLoading:u,latestIssuedAccessToken:f,clearLatestIssuedAccessToken:y,refreshAccess:m,createAccessToken:h,deleteAccessToken:x}}function MD(){const e=Id(),[t,n]=c.useState(!(e!=null&&e.token)),[s,r]=c.useState(!1),[a,i]=c.useState(!!(e!=null&&e.token)),[l,u]=c.useState(String((e==null?void 0:e.username)||"").trim()),[d,f]=c.useState(!1),[g,m]=c.useState(!1),[h,x]=c.useState(""),[y,w]=c.useState([]),[b,p]=c.useState(""),[v,S]=c.useState(""),[j,C]=c.useState(null),[A,M]=c.useState(null),[O,P]=c.useState([]),[$,z]=c.useState([]),[N,H]=c.useState([]),[R,I]=c.useState([]),[T,E]=c.useState([]),[q,k]=c.useState([]),[D,B]=c.useState(""),[Q,Z]=c.useState([]),[te,se]=c.useState([]),[ie,oe]=c.useState([]),[pe,_]=c.useState(""),[Y,le]=c.useState([]),[ne,ue]=c.useState([]),[ae,xe]=c.useState([]),[ee,W]=c.useState(null),[X,G]=c.useState([]),[L,J]=c.useState([]),[me,ge]=c.useState([]),[U,ce]=c.useState([]),[F,K]=c.useState([]),[he,Te]=c.useState([]),[Se,Fe]=c.useState(null),[Ae,Re]=c.useState([]),[Ye,yt]=c.useState("连接中..."),[De,ot]=c.useState(!1),[_e,Je]=c.useState(!1),[jt,Ct]=c.useState(!1),[zt,Ce]=c.useState(!1),[rt,et]=c.useState(!1),[$e,Ht]=c.useState(""),[zn,ms]=c.useState(""),[Bs,In]=c.useState(null),Sn=c.useRef(null),Jn=c.useRef(""),vt=c.useRef(""),Ft=c.useRef(null),Es=c.useRef("unknown");c.useEffect(()=>{Jn.current=D},[D]),c.useEffect(()=>{vt.current=pe},[pe]);const Aa=c.useMemo(()=>y.find(de=>de.id===v)||null,[y,v]),Ue=c.useCallback((de,Oe="info")=>{In({message:de,type:Oe}),Sn.current&&window.clearTimeout(Sn.current),Sn.current=window.setTimeout(()=>{In(null),Sn.current=null},2200)},[]),Ms=c.useCallback(()=>{D0(),n(!1),r(!1),i(!1),u(""),f(!0),x(""),yt("需要 Bearer Token"),ot(!1)},[]),ye=c.useCallback(async(de,Oe={},tt)=>{try{return await Bu({path:de,options:Oe,selectedAgentId:v,preferredAgentId:tt})}catch(kt){throw Vj(kt)&&Ms(),kt}},[Ms,v]),{accessUser:Ea,accessTokens:Nf,accessLoading:Tf,latestIssuedAccessToken:Af,clearLatestIssuedAccessToken:Ef,refreshAccess:Mf,createAccessToken:Rf,deleteAccessToken:Of}=ED({enabled:a&&!t&&!d,requestJson:ye,showToast:Ue}),zf=c.useCallback(async de=>{var Oe,tt;m(!0),x("");try{const kt=String(de.token||"").trim();if(!kt)throw new Error("请先输入 Bearer Token");const $s=await Bu({path:ve.authMe(),selectedAgentId:"",options:{headers:{Authorization:/^Bearer\s+/i.test(kt)?kt:`Bearer ${kt}`}}}),Tc=kt.replace(/^Bearer\s+/i,"").trim(),Ra=String(((Oe=$s==null?void 0:$s.user)==null?void 0:Oe.username)||"").trim();m7({token:Tc,...Ra?{username:Ra}:{}}),n(!1),r(!1),i(!0),u(Ra),f(!1),await((tt=Ft.current)==null?void 0:tt.call(Ft))}catch(kt){throw D0(),i(!1),u(""),f(!0),x(Le(kt)),kt}finally{m(!1)}},[]),If=c.useCallback(()=>{Ms()},[Ms]),Df=c.useCallback(()=>{C(null),M(null),P([]),z([]),I([]),E([]),k([]),B(""),Z([]),se([]),oe([]),_(""),le([]),ue([]),xe([]),Fe(null),Re([])},[]),_f=c.useCallback(async de=>{const Oe=await S7({requestJson:ye,preferredAgentId:de,selectedAgentId:v});Oe.cityVersion&&p(Oe.cityVersion);const tt=Oe.list,kt=Oe.nextAgentId;return w(tt),{nextAgentId:kt,list:tt}},[ye,v]),Pr=c.useCallback(async de=>{de&&C(await j7(ye,de))},[ye]),Po=c.useCallback(async de=>{de&&P(await C7(ye,de))},[ye]),Ps=c.useCallback(async de=>{de&&z(await k7(ye,de))},[ye]),Vi=c.useCallback(async()=>{const de=await _0(ye);return H(de),de},[ye]),or=c.useCallback(async de=>{if(!de){I([]);return}const Oe=await _0(ye,de);return I(Oe),Oe},[ye]),ar=c.useCallback(async de=>{if(!de)return[];const Oe=await T7(ye,de);return E(Oe),Oe},[ye]),Nn=c.useCallback(async de=>{if(!de)return[];const Oe=await A7(ye,de);return k(Oe),Oe},[ye]),Yi=c.useCallback(async(de,Oe)=>{!de||!Oe||Z(await E7(ye,de,Oe))},[ye]),Ki=c.useCallback(async(de,Oe)=>{!de||!Oe||se(await M7(ye,de,Oe))},[ye]),$r=c.useCallback(async(de,Oe,tt)=>{if(!de||!Oe||!tt){_(""),le([]);return}if(Es.current==="unsupported"){_(""),le([]);return}try{const kt=await R7(ye,de,Oe,tt);Es.current="supported",_(tt),le(Array.isArray(kt.messages)?kt.messages:[])}catch(kt){const $s=Le(kt);if(mh($s)){Es.current="unsupported",_(""),le([]);return}throw kt}},[ye]),Ur=c.useCallback(async(de,Oe)=>{var Ra;if(!de||!Oe)return oe([]),_(""),le([]),[];if(Es.current==="unsupported")return oe([]),_(""),le([]),[];let tt=[];try{tt=await O7(ye,de,Oe),Es.current="supported"}catch(Ac){const PC=Le(Ac);if(!mh(PC))throw Ac;Es.current="unsupported",tt=[]}oe(tt);const kt=String(vt.current||"").trim(),$s=String(((Ra=tt[0])==null?void 0:Ra.archiveId)||"").trim(),Tc=tt.some(Ac=>String(Ac.archiveId||"").trim()===kt)?kt:$s;return Tc?(await $r(de,Oe,Tc),tt):(_(""),le([]),tt)},[$r,ye]),Yt=c.useCallback(async de=>{de&&ue(await z7(ye,de))},[ye]),gn=c.useCallback(async de=>{de&&xe(await I7(ye,de))},[ye]),Hr=c.useCallback(async de=>{W(await D7(ye,de))},[ye]),ir=c.useCallback(async de=>{G(await _7(ye,de))},[ye]),Kt=c.useCallback(async()=>{const de=await L7(ye);J(de.providers),ge(de.models)},[ye]),Xi=c.useCallback(async()=>{K(await B7(ye))},[ye]),Fr=c.useCallback(async de=>{if(!de){Te([]);return}Te(await P7(ye,de))},[ye]),kc=c.useCallback(async()=>{ce(await $7(ye))},[ye]),Ma=c.useCallback(async(de,Oe)=>{if(!de)return;const tt=String(Oe||Js).trim()||Js;Fe(await U7(ye,de,tt))},[ye]),Zi=c.useCallback(async de=>{de&&Re(await H7(ye,de))},[ye]),Nc=c.useCallback(async de=>{de&&M(await F7(ye,de))},[ye]),{refreshDashboard:lr,handleSessionChange:V}=vD({requestJson:ye,selectedAgentId:v,selectedSessionIdRef:Jn,setSelectedAgentId:S,setSelectedSessionId:B,setAgentEnvItems:Te,setTopbarError:ot,setTopbarStatus:yt,setLoading:Je,setChannelHistory:Z,setSessionMessages:se,setSessionArchives:oe,setSelectedArchiveId:_,setSessionArchiveMessages:le,setPrompt:Fe,clearPanelDataForNoAgent:Df,refreshAgents:_f,refreshGlobalPlugins:Vi,refreshPlugins:or,refreshModel:Hr,refreshModelPool:Kt,refreshChannelAccounts:kc,refreshGlobalEnv:Xi,refreshConfigStatus:ir,refreshAgentEnv:Fr,refreshChatChannels:ar,refreshSessions:Nn,refreshAuthorization:Nc,refreshOverview:Pr,refreshServices:Po,refreshSkills:Ps,refreshTasks:Yt,refreshLogs:gn,refreshLocalChat:Zi,refreshChannelHistory:Yi,refreshSessionMessages:Ki,refreshSessionArchives:Ur,refreshPrompt:Ma,showToast:Ue,setAuthRequired:f}),re=c.useCallback(async(de,Oe)=>{await q7({requestJson:ye,serviceName:de,action:Oe,selectedAgentId:v,refreshServices:Po,refreshSkills:Ps,showToast:Ue})},[Po,Ps,ye,v,Ue]),Ke=c.useCallback(async(de,Oe,tt)=>L0({requestJson:ye,pluginName:de,actionName:Oe,payload:tt,selectedAgentId:v,refreshPlugins:or,scope:"agent",showToast:Ue}),[or,ye,v,Ue]),It=c.useCallback(async(de,Oe,tt)=>L0({requestJson:ye,pluginName:de,actionName:Oe,payload:tt,selectedAgentId:v,refreshPlugins:or,refreshGlobalPlugins:Vi,scope:"global",showToast:Ue}),[Vi,or,ye,v,Ue]),jn=c.useCallback(async de=>N7(ye,de),[ye]),Rs=c.useCallback(async(de,Oe)=>{await V7({requestJson:ye,action:de,channel:Oe,chatChannels:T,selectedAgentId:v,refreshChatChannels:ar,refreshServices:Po,showToast:Ue})},[T,ar,Po,ye,v,Ue]),Kj=c.useCallback(async(de,Oe)=>{await Y7({requestJson:ye,channel:de,config:Oe,selectedAgentId:v,refreshDashboard:lr,showToast:Ue})},[lr,ye,v,Ue]),Xj=c.useCallback(async de=>{await K7({requestJson:ye,config:de,selectedAgentId:v,setAuthorization:M,showToast:Ue})},[ye,v,Ue]),Zj=c.useCallback(async de=>{await X7({requestJson:ye,input:de,selectedAgentId:v,setAuthorization:M,showToast:Ue})},[ye,v,Ue]),Jj=c.useCallback(async de=>Z7({requestJson:ye,query:de,selectedAgentId:v,refreshSkills:Ps,showToast:Ue}),[Ps,ye,v,Ue]),Qj=c.useCallback(async de=>J7({requestJson:ye,input:de,selectedAgentId:v,refreshSkills:Ps,showToast:Ue}),[Ps,ye,v,Ue]),Wj=c.useCallback(async de=>Q7({requestJson:ye,name:de,selectedAgentId:v,showToast:Ue}),[ye,v,Ue]),eC=c.useCallback(async de=>{await dD({requestJson:ye,title:de,selectedAgentId:v,refreshTasks:Yt,refreshLogs:gn,showToast:Ue})},[gn,Yt,ye,v,Ue]),tC=c.useCallback(async(de,Oe)=>fD({requestJson:ye,title:de,status:Oe,selectedAgentId:v,refreshTasks:Yt,refreshOverview:Pr,showToast:Ue}),[Pr,Yt,ye,v,Ue]),nC=c.useCallback(async de=>gD({requestJson:ye,title:de,selectedAgentId:v,refreshTasks:Yt,refreshOverview:Pr,refreshLogs:gn,showToast:Ue}),[gn,Pr,Yt,ye,v,Ue]),sC=c.useCallback(async(de,Oe=50)=>mD({requestJson:ye,title:de,limit:Oe,selectedAgentId:v,showToast:Ue}),[ye,v,Ue]),rC=c.useCallback(async(de,Oe)=>hD({requestJson:ye,title:de,timestamp:Oe,selectedAgentId:v,refreshLogs:gn,showToast:Ue}),[gn,ye,v,Ue]),oC=c.useCallback(async de=>pD({requestJson:ye,title:de,selectedAgentId:v,refreshLogs:gn,showToast:Ue}),[gn,ye,v,Ue]),aC=c.useCallback(async(de,Oe)=>xD({requestJson:ye,title:de,timestamp:Oe,selectedAgentId:v,showToast:Ue}),[ye,v,Ue]),{sendConsoleUiMessage:iC,clearSessionMessages:lC,clearChatHistory:cC,deleteChatSession:uC}=jD({requestJson:ye,selectedAgentId:v,chatInput:zn,sending:jt,clearingSessionMessages:zt,clearingChatHistory:rt,deletingSessionId:$e,selectedSessionIdRef:Jn,setSending:Ct,setClearingSessionMessages:Ce,setClearingChatHistory:et,setDeletingSessionId:Ht,setChatInput:ms,setSelectedSessionId:B,setChannelHistory:Z,setSessionMessages:se,setSessionArchives:oe,setSelectedArchiveId:_,setSessionArchiveMessages:le,setPrompt:Fe,refreshLocalChat:Zi,refreshChannelHistory:Yi,refreshSessionMessages:Ki,refreshSessionArchives:Ur,refreshPrompt:Ma,refreshLogs:gn,refreshOverview:Pr,refreshSessions:Nn,refreshChatChannels:ar,showToast:Ue}),{switchModel:dC,switchModelForAgent:fC,updateAgentExecution:gC,startAgentFromHistory:mC,createAgent:hC,pickAgentDirectory:pC,inspectAgentDirectory:xC,restartAgentFromHistory:bC,stopAgentFromHistory:yC,upsertModelProvider:vC,removeModelProvider:wC,testModelProvider:SC,discoverModelProvider:jC,upsertModelPoolItem:CC,removeModelPoolItem:kC,setModelPoolItemPaused:NC,testModelPoolItem:TC,upsertChannelAccount:AC,probeChannelAccount:EC,removeChannelAccount:MC,upsertGlobalEnv:RC,importGlobalEnv:OC,removeGlobalEnv:zC,upsertAgentEnv:IC,removeAgentEnv:DC,importAgentEnv:_C,executeAgentCommand:LC}=CD({requestJson:ye,selectedAgentId:v,refreshDashboard:lr,refreshModel:Hr,refreshModelPool:Kt,refreshChannelAccounts:kc,refreshChatChannels:ar,refreshGlobalEnv:Xi,refreshAgentEnv:Fr,showToast:Ue}),BC=c.useCallback(de=>{S(de),lr(de)},[lr]);return c.useEffect(()=>{Ft.current=lr},[lr]),c.useEffect(()=>{let de=!1;return(async()=>{const tt=Id(),kt=!!(tt!=null&&tt.token);if(i(kt),u(String((tt==null?void 0:tt.username)||"").trim()),kt){if(de)return;r(!1),f(!1),n(!1);return}try{const $s=await Bu({path:ve.authStatus(),selectedAgentId:""});if(!$s.initialized){if(de)return;r(!0),f(!0),n(!1),yt("需要先创建 Token"),ot(!1);return}if($s.requireToken&&!kt){if(de)return;r(!1),f(!0),n(!1),yt("需要 Bearer Token"),ot(!1);return}}catch{}de||(r(!1),f(!0),yt("需要 Bearer Token"),ot(!1),n(!1))})(),()=>{de=!0}},[]),c.useEffect(()=>{var Oe;if(t||d&&!a)return;(Oe=Ft.current)==null||Oe.call(Ft);const de=window.setInterval(()=>{var tt;d&&!a||(tt=Ft.current)==null||tt.call(Ft)},12e3);return()=>{window.clearInterval(de),Sn.current&&window.clearTimeout(Sn.current)}},[t,d,a]),{authInitializing:t,authBootstrapRequired:s,isAuthenticated:a,authUsername:l,authRequired:d,authSubmitting:g,authErrorMessage:h,agents:y,cityVersion:b,selectedAgentId:v,selectedAgent:Aa,overview:j,authorization:A,accessUser:Ea,accessTokens:Nf,accessLoading:Tf,latestIssuedAccessToken:Af,services:O,skills:$,plugins:N,agentPlugins:R,chatChannels:T,sessions:q,selectedSessionId:D,channelHistory:Q,sessionMessages:te,sessionArchives:ie,selectedArchiveId:pe,sessionArchiveMessages:Y,tasks:ne,logs:ae,model:ee,configStatus:X,modelProviders:L,modelPoolItems:me,channelAccounts:U,globalEnvItems:F,agentEnvItems:he,prompt:Se,localMessages:Ae,topbarStatus:Ye,topbarError:De,loading:_e,sending:jt,clearingSessionMessages:zt,clearingChatHistory:rt,deletingSessionId:$e,chatInput:zn,toast:Bs,setChatInput:ms,handleAgentChange:BC,handleSessionChange:V,refreshDashboard:lr,refreshAuthorization:Nc,refreshAccess:Mf,refreshChatChannels:ar,refreshPlugins:or,loadLocalModels:jn,refreshSkills:Ps,refreshSessions:Nn,refreshChannelHistory:Yi,refreshSessionMessages:Ki,refreshSessionArchives:Ur,loadSessionArchiveMessages:$r,refreshPrompt:Ma,refreshModel:Hr,refreshModelPool:Kt,refreshGlobalEnv:Xi,refreshAgentEnv:Fr,refreshConfigStatus:ir,refreshLocalChat:Zi,controlService:re,runGlobalPluginAction:It,runPluginAction:Ke,runChatChannelAction:Rs,configureChatChannel:Kj,saveAuthorizationConfig:Xj,runAuthorizationAction:Zj,clearLatestIssuedAccessToken:Ef,createAccessToken:Rf,deleteAccessToken:Of,runSkillFind:Jj,runSkillInstall:Qj,runSkillLookup:Wj,runTask:eC,setTaskStatus:tC,deleteTask:nC,loadTaskRuns:sC,deleteTaskRun:rC,clearTaskRuns:oC,loadTaskRunDetail:aC,sendConsoleUiMessage:iC,clearSessionMessages:lC,clearChatHistory:cC,deleteChatSession:uC,switchModel:dC,switchModelForAgent:fC,updateAgentExecution:gC,startAgentFromHistory:mC,createAgent:hC,pickAgentDirectory:pC,inspectAgentDirectory:xC,restartAgentFromHistory:bC,stopAgentFromHistory:yC,upsertModelProvider:vC,removeModelProvider:wC,testModelProvider:SC,discoverModelProvider:jC,upsertModelPoolItem:CC,removeModelPoolItem:kC,setModelPoolItemPaused:NC,testModelPoolItem:TC,upsertChannelAccount:AC,probeChannelAccount:EC,removeChannelAccount:MC,upsertGlobalEnv:RC,removeGlobalEnv:zC,importGlobalEnv:OC,upsertAgentEnv:IC,removeAgentEnv:DC,importAgentEnv:_C,executeAgentCommand:LC,constants:{CONSOLEUI_SESSION_ID:Js},uiHelpers:{formatTime:x7,statusBadgeVariant:p7},submitAuthToken:zf,logout:If}}function RD(e){return e instanceof Lu?e.message:e instanceof Error&&e.message||String(e)}function Ug(e,t){return{name:String(e.name||e.id||"agent").trim()||"agent",running:!1,statusText:"当前还没有对外可见的新动态",collectedAt:t,headline:"当前处于安静待命的状态",posture:"静候下一步",momentum:"安静",visibilityNote:"这里展示的是面向外部的概览状态,不包含内部上下文细节。",current:[{id:`idle:${e.id}`,kind:"idle",title:"当前处于安静待命",summary:"等待新的输入、触发或下一次启动。",status:"waiting",updatedAt:t,tags:["public","idle"]}],recent:[],signals:[{label:"状态节奏",value:"安静待命",tone:"neutral"},{label:"现场感受",value:"整体平稳",tone:"neutral"},{label:"活跃温度",value:"较为安静",tone:"neutral"}]}}function gu(e,t){return{id:e,name:t.name,running:t.running,headline:t.headline,posture:t.posture,momentum:t.momentum,statusText:t.statusText,collectedAt:t.collectedAt,currentCount:t.current.length,recentCount:t.recent.length,signalCount:t.signals.length,snapshot:t}}async function OD(e){const t=new Date().toISOString(),n=String(e.agent.id||"").trim();if(!n||e.agent.running!==!0)return gu(n||`idle:${t}`,Ug(e.agent,t));try{const s=await Bu({path:ve.workboardSnapshot(),selectedAgentId:e.selectedAgentId,preferredAgentId:n});if(!s.snapshot)return gu(n,Ug(e.agent,t));const r={name:s.snapshot.agent.name,running:s.snapshot.agent.running,statusText:s.snapshot.agent.statusText,collectedAt:s.snapshot.agent.collectedAt,headline:s.snapshot.summary.headline,posture:s.snapshot.summary.posture,momentum:s.snapshot.summary.momentum,visibilityNote:s.snapshot.summary.visibilityNote,current:s.snapshot.current||[],recent:s.snapshot.recent||[],signals:s.snapshot.signals||[]};return gu(n,r)}catch{const s=Ug({...e.agent},t);return s.statusText="当前状态暂时无法更新",s.headline="当前状态暂时不可见",s.posture="稍后再看",s.momentum="轻微中断",s.current=[{id:`issue:${n}`,kind:"idle",title:"公开状态暂时不可见",summary:"这位 agent 仍然在线,但当前公开板面没有返回最新状态。",status:"issue",updatedAt:t,tags:["public","issue"]}],s.signals=[{label:"状态节奏",value:"暂时中断",tone:"warning"},{label:"现场感受",value:"有些波动",tone:"warning"},{label:"活跃温度",value:"稍后再看",tone:"neutral"}],gu(n,s)}}function zD(e){return[...e].sort((t,n)=>t.running!==n.running?t.running?-1:1:t.currentCount!==n.currentCount?n.currentCount-t.currentCount:t.name.localeCompare(n.name))}function ID(e){const[t,n]=c.useState(null),[s,r]=c.useState(!1),[a,i]=c.useState(""),l=c.useCallback(async()=>{const u=Array.isArray(e.agents)?e.agents:[];if(!e.enabled||u.length===0){n(null),i(""),r(!1);return}r(!0);try{const d=await Promise.all(u.map(y=>OD({agent:y,selectedAgentId:e.selectedAgentId}))),f=zD(d),g=f.filter(y=>y.running).length,m=f.filter(y=>y.snapshot.current.some(w=>w.status==="active")).length,h=f.filter(y=>y.snapshot.momentum==="安静").length,x=new Date().toISOString();n({summary:{totalAgents:f.length,liveAgents:g,activeAgents:m,quietAgents:h},agents:f,collectedAt:x}),i("")}catch(d){i(RD(d))}finally{r(!1)}},[e.agents,e.enabled,e.selectedAgentId]);return c.useEffect(()=>{l()},[l]),c.useEffect(()=>{if(!e.enabled||e.agents.length===0)return;const u=window.setInterval(()=>{l()},5e3);return()=>window.clearInterval(u)},[e.agents.length,e.enabled,l]),{board:t,loading:s,errorMessage:a,refresh:l}}const DD=Dz();function P0(e){const t=String(e||"").trim().toLocaleLowerCase();return t&&t.replace(/[\s_]+/g,"-").replace(/[/?#]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Ko(e){const t=String(e||"").trim().toLocaleLowerCase();return t&&t.replace(/[\s_]+/g,"-").replace(/[/?#]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"agent"}function $0(e,t){const n=Ko(String((t==null?void 0:t.agentSegment)||"agent"));if(e==="globalOverview")return String((t==null?void 0:t.agentSegment)||"").trim()?`/global/agent/${encodeURIComponent(n)}`:"/global/overview";if(e==="globalWorkboard")return"/global/workboard";if(e==="globalApiKeys")return"/global/api-keys";if(e==="globalEnv")return"/global/env";if(e==="globalModel")return"/global/model";if(e==="globalChannelAccounts")return"/global/channel-accounts";if(e==="globalCommand")return"/global/command";if(e==="globalAgents")return"/global/agents";if(e==="globalPlugins")return"/global/plugins";if(e==="agentOverview")return`/${encodeURIComponent(n)}/overview`;if(e==="agentAuthorization")return`/${encodeURIComponent(n)}/authorization`;if(e==="agentPlugins")return`/${encodeURIComponent(n)}/plugins`;if(e==="agentSkills")return`/${encodeURIComponent(n)}/skills`;if(e==="agentServices")return`/${encodeURIComponent(n)}/services`;if(e==="agentCommand")return`/${encodeURIComponent(n)}/command`;if(e==="agentTasks"){const s=String((t==null?void 0:t.taskTitle)||"").trim();return s?`/${encodeURIComponent(n)}/tasks/${encodeURIComponent(s)}`:`/${encodeURIComponent(n)}/tasks`}if(e==="agentLogs")return`/${encodeURIComponent(n)}/logs`;if(e==="contextOverview"){const s=P0(String((t==null?void 0:t.channel)||""));return`/${encodeURIComponent(n)}/channel/${encodeURIComponent(s)}`}if(e==="contextWorkspace"){const s=String((t==null?void 0:t.sessionId)||"").trim(),r=P0(String((t==null?void 0:t.channel)||""));return s?`/${encodeURIComponent(n)}/channel/${encodeURIComponent(r)}/chat/${encodeURIComponent(s)}`:`/${encodeURIComponent(n)}/channel/${encodeURIComponent(r)}`}return"/global/overview"}function $a(e){const t=String(e||"/").trim()||"/",n=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;for(const[r,a]of Object.entries(DD))if(n===a)return{view:r};const s=n.split("/").filter(Boolean);if(s.length>=3){const r=String(s[0]||"").trim().toLowerCase(),a=String(s[1]||"").trim().toLowerCase();if(r==="global"&&a==="agent"){const i=decodeURIComponent(s.slice(2).join("/")).trim();if(i)return{view:"globalOverview",agentSegment:i}}}if(s.length>=2){const r=decodeURIComponent(s[0]||"").trim(),a=String(s[1]||"").trim().toLowerCase();if(r){if(a==="overview")return{view:"agentOverview",agentSegment:r};if(a==="authorization")return{view:"agentAuthorization",agentSegment:r};if(a==="plugins")return{view:"agentPlugins",agentSegment:r};if(a==="skills")return{view:"agentSkills",agentSegment:r};if(a==="services")return{view:"agentServices",agentSegment:r};if(a==="command")return{view:"agentCommand",agentSegment:r};if(a==="tasks"){const i=s.length>=3?decodeURIComponent(s.slice(2).join("/")):"";return{view:"agentTasks",agentSegment:r,taskTitle:i}}if(a==="logs")return{view:"agentLogs",agentSegment:r};if(a==="channel"){const i=s.length>=3?decodeURIComponent(String(s[2]||"").trim()):"";if(String(s[3]||"").trim().toLowerCase()==="chat"){const u=s.length>=5?decodeURIComponent(s.slice(4).join("/")):"";if(u)return{view:"contextWorkspace",agentSegment:r,channel:i,sessionId:u}}return{view:"contextOverview",agentSegment:r,channel:i}}if(a==="chat"){const i=s.length>=3?decodeURIComponent(s.slice(2).join("/")):"";return i?{view:"contextWorkspace",agentSegment:r,sessionId:i}:{view:"contextOverview",agentSegment:r}}}}return{view:"globalOverview"}}const U0="city.console-ui.context.debug-panels-collapsed";function _D(){const[e,t]=c.useState(()=>typeof window>"u"?"/global/overview":window.location.pathname),[n,s]=c.useState(()=>typeof window>"u"?"globalOverview":$a(window.location.pathname).view),[r,a]=c.useState(!1),[i,l]=c.useState(()=>typeof window>"u"?"":String($a(window.location.pathname).taskTitle||"").trim()),[u,d]=c.useState(""),[f,g]=c.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(U0)==="1"}catch{return!1}}),{agents:m,authInitializing:h,authBootstrapRequired:x,isAuthenticated:y,authRequired:w,authSubmitting:b,authErrorMessage:p,cityVersion:v,selectedAgentId:S,selectedAgent:j,overview:C,authorization:A,accessUser:M,accessTokens:O,accessLoading:P,latestIssuedAccessToken:$,services:z,skills:N,plugins:H,agentPlugins:R,chatChannels:I,sessions:T,selectedSessionId:E,channelHistory:q,sessionMessages:k,sessionArchives:D,selectedArchiveId:B,sessionArchiveMessages:Q,tasks:Z,logs:te,model:se,configStatus:ie,modelProviders:oe,modelPoolItems:pe,channelAccounts:_,globalEnvItems:Y,agentEnvItems:le,prompt:ne,topbarStatus:ue,topbarError:ae,loading:xe,sending:ee,clearingSessionMessages:W,clearingChatHistory:X,deletingSessionId:G,chatInput:L,toast:J,setChatInput:me,handleAgentChange:ge,handleSessionChange:U,refreshDashboard:ce,refreshSkills:F,refreshSessionArchives:K,controlService:he,runGlobalPluginAction:Te,runPluginAction:Se,runChatChannelAction:Fe,configureChatChannel:Ae,refreshAuthorization:Re,saveAuthorizationConfig:Ye,runAuthorizationAction:yt,clearLatestIssuedAccessToken:De,createAccessToken:ot,deleteAccessToken:_e,runSkillFind:Je,runSkillInstall:jt,runTask:Ct,setTaskStatus:zt,deleteTask:Ce,loadTaskRuns:rt,deleteTaskRun:et,clearTaskRuns:$e,loadTaskRunDetail:Ht,sendConsoleUiMessage:zn,clearSessionMessages:ms,clearChatHistory:Bs,deleteChatSession:In,loadSessionArchiveMessages:Sn,updateAgentExecution:Jn,startAgentFromHistory:vt,loadLocalModels:Ft,pickAgentDirectory:Es,inspectAgentDirectory:Aa,restartAgentFromHistory:Ue,stopAgentFromHistory:Ms,upsertModelProvider:ye,removeModelProvider:Ea,testModelProvider:Nf,discoverModelProvider:Tf,upsertModelPoolItem:Af,removeModelPoolItem:Ef,setModelPoolItemPaused:Mf,testModelPoolItem:Rf,upsertChannelAccount:Of,probeChannelAccount:zf,removeChannelAccount:If,upsertGlobalEnv:Df,removeGlobalEnv:_f,importGlobalEnv:Pr,upsertAgentEnv:Po,removeAgentEnv:Ps,importAgentEnv:Vi,executeAgentCommand:or,constants:ar,uiHelpers:Nn,submitAuthToken:Yi,logout:Ki}=MD(),$r=ID({agents:m,selectedAgentId:S,enabled:y&&!w}),Ur=c.useCallback(V=>{const re=String(V||"").trim();if(re){const Ke=m.find(It=>It.id===re);if(Ke)return Ko(Ke.name||Ke.id)}return j?Ko(j.name||j.id):S?Ko(S):"agent"},[m,j,S]),Yt=c.useCallback(V=>{const re=String(V||"").trim();if(!re)return"";const Ke=T.find(It=>String(It.sessionId||"").trim()===re);return ma(Ke||re)},[T]),gn=c.useMemo(()=>{const V=new Set;for(const jn of I){const Rs=String(jn.channel||"").trim().toLowerCase();Rs&&V.add(Rs)}for(const jn of T){const Rs=ma(jn);Rs&&V.add(Rs)}const re=["telegram","qq","feishu","consoleui","other"],Ke=re.filter(jn=>V.has(jn)),It=[...V].filter(jn=>!re.includes(jn)).sort((jn,Rs)=>jn.localeCompare(Rs));return[...Ke,...It]},[I,T]),Hr=c.useMemo(()=>{const V=String(u||"").trim().toLowerCase();return V&&gn.includes(V)?V:String(gn[0]||"").trim().toLowerCase()},[gn,u]),ir=c.useCallback(V=>{const re=Ko(String(V||""));if(!re)return"";const Ke=m.find(It=>{const jn=Ko(String(It.name||"")),Rs=Ko(String(It.id||""));return re===jn||re===Rs});return String((Ke==null?void 0:Ke.id)||"")},[m]),Kt=c.useCallback((V,re)=>{if(typeof window>"u")return;const Ke=V==="globalOverview"&&!!String((re==null?void 0:re.agentId)||"").trim(),It=$0(V,{sessionId:re==null?void 0:re.sessionId,taskTitle:re==null?void 0:re.taskTitle,channel:re==null?void 0:re.channel,agentSegment:Ke||V!=="globalOverview"?Ur(re==null?void 0:re.agentId):void 0});window.location.pathname!==It&&(re!=null&&re.replace?window.history.replaceState({},"",It):window.history.pushState({},"",It)),t(It),s(V),V==="agentTasks"?l(String((re==null?void 0:re.taskTitle)||"").trim()):V!=="contextWorkspace"&&l("")},[Ur]);c.useEffect(()=>{if(typeof window>"u"||r)return;const V=$a(window.location.pathname);t(window.location.pathname),s(V.view),l(String(V.taskTitle||"").trim()),d(String(V.channel||"").trim().toLowerCase());const re=!!String(V.agentSegment||"").trim();if(re&&m.length===0)return;const Ke=ir(V.agentSegment);if(re&&Ke&&Ke!==S){ge(Ke);return}if(V.view==="contextWorkspace"&&V.sessionId&&(!re||!Ke||Ke===S)){const It=String(V.channel||"").trim().toLowerCase();d(It||Yt(V.sessionId)),U(V.sessionId)}a(!0)},[m.length,U,ge,ir,r,S]),c.useEffect(()=>{if(typeof window>"u")return;const V=()=>{const re=$a(window.location.pathname);t(window.location.pathname),s(re.view),l(String(re.taskTitle||"").trim()),d(String(re.channel||"").trim().toLowerCase());const Ke=ir(re.agentSegment);if(Ke&&Ke!==S&&ge(Ke),re.view==="contextWorkspace"&&re.sessionId&&(!Ke||Ke===S)){const It=String(re.channel||"").trim().toLowerCase();d(It||Yt(re.sessionId)),U(re.sessionId)}};return window.addEventListener("popstate",V),()=>window.removeEventListener("popstate",V)},[U,ge,ir,S]),c.useEffect(()=>{if(typeof window>"u"||!r||!(n!=="globalOverview"&&n!=="globalWorkboard"&&n!=="globalApiKeys"&&n!=="globalEnv"&&n!=="globalModel"&&n!=="globalChannelAccounts"&&n!=="globalCommand"&&n!=="globalAgents"&&n!=="globalPlugins")||!S)return;const re=$0(n,{sessionId:n==="contextWorkspace"?E:void 0,taskTitle:n==="agentTasks"?i:void 0,channel:n==="contextOverview"?Hr:n==="contextWorkspace"?Yt(E):void 0,agentSegment:Ur(S)});window.location.pathname!==re&&window.history.replaceState({},"",re)},[n,Hr,Ur,Yt,r,S,E,i]),c.useEffect(()=>{if(n!=="agentTasks"||!i)return;Z.some(re=>String(re.title||"").trim()===i)||l("")},[n,i,Z]),c.useEffect(()=>{if(r){if(n==="agentServices"){Kt("agentOverview",{replace:!0});return}if(n==="agentCommand"){Kt("globalCommand",{replace:!0});return}if(n==="agentTasks"&&!i){Kt("agentOverview",{replace:!0});return}}},[n,Kt,r,i]),c.useEffect(()=>{d("")},[S]),c.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(U0,f?"1":"0")}catch{}},[f]),c.useEffect(()=>{if(n!=="contextOverview")return;const V=String(u||"").trim().toLowerCase();if(!!V&&gn.includes(V))return;const Ke=String(gn[0]||"").trim().toLowerCase();Ke&&d(Ke)},[n,gn,u]);const Xi=c.useMemo(()=>n!=="globalOverview"?!1:!!String($a(e).agentSegment||"").trim(),[n,e]),Fr=c.useMemo(()=>$a(e),[e]),kc=c.useMemo(()=>ir(Fr.agentSegment),[Fr.agentSegment,ir]);c.useEffect(()=>{String(Fr.agentSegment||"").trim()||S&&ge("")},[ge,Fr.agentSegment,S]);const Ma=()=>j&&j.running===!1?o.jsx("section",{children:o.jsx(Fz,{agent:j,model:se,onStart:V=>vt(V),onLoadLocalModels:V=>Ft(V),onUpdateExecution:V=>{S&&Jn({agentId:S,executionMode:V.executionMode,modelId:V.modelId,localModel:V.localModel,agentType:V.agentType})}})}):o.jsx("section",{className:"space-y-6",children:o.jsx(i7,{selectedAgent:j,overview:C,services:z,skills:N,tasks:Z,sessions:T,channelAccounts:_,consoleUiSessionId:ar.CONSOLEUI_SESSION_ID,configStatus:ie,model:se,onLoadLocalModels:V=>Ft(V),onUpdateExecution:V=>{S&&Jn({agentId:S,executionMode:V.executionMode,modelId:V.modelId,localModel:V.localModel,agentType:V.agentType})},onStartAgent:async()=>{S&&await vt(S)},onRestartAgent:async()=>{S&&await Ue(S)},onStopAgent:async()=>{S&&await Ms(S)},onOpenTask:V=>{const re=String(V||"").trim();re&&(l(re),Kt("agentTasks",{taskTitle:re}))},onOpenSession:V=>{const re=String(V||"").trim();re&&(Kt("contextWorkspace",{sessionId:re,channel:Yt(re)}),U(re))},onControlService:(V,re)=>he(V,re),chatChannels:I,onChatAction:(V,re)=>Fe(V,re)})}),Zi=()=>{switch(n){case"globalOverview":return Xi?Ma():o.jsx("section",{children:o.jsx(O0,{cityVersion:v,agents:m,modelPoolItems:pe,plugins:H,configStatus:ie,onPickAgentDirectory:()=>Es(),onInspectAgentDirectory:V=>Aa(V),onLoadLocalModels:V=>Ft(V),onStartAgent:V=>vt(V),onStartAgentWithInitialization:(V,re)=>vt(V,{initializeIfNeeded:!0,initialization:{projectRoot:V,agentName:re.agentName,executionMode:re.executionMode,modelId:re.modelId,localModel:re.localModel,agentType:re.agentType}}),onRestartAgent:V=>Ue(V),onStopAgent:V=>Ms(V)})});case"globalWorkboard":return o.jsx("section",{children:o.jsx(f7,{board:$r.board,loading:$r.loading,errorMessage:$r.errorMessage,onRefresh:()=>{$r.refresh()}})});case"globalApiKeys":return o.jsx("section",{children:o.jsx(Pz,{tokens:O,loading:P,latestIssuedToken:$,formatTime:V=>Nn.formatTime(V??void 0),onCreateToken:V=>ot(V),onDeleteToken:V=>_e(V),onClearLatestIssuedToken:De})});case"globalEnv":{const V=[...Y,...le].sort((re,Ke)=>{const It=String(re.scope||"global").localeCompare(String(Ke.scope||"global"));if(It!==0)return It;const jn=String(re.agentId||"").localeCompare(String(Ke.agentId||""));return jn!==0?jn:String(re.key||"").localeCompare(String(Ke.key||""))});return o.jsx("section",{children:o.jsx(bI,{title:"Env",description:"统一管理全局共享与 agent 私有 env,通过范围标签区分。",emptyText:"暂无 env,点击右上角 + 新建。",items:V,loading:xe,writable:!0,agentOptions:m.map(re=>({id:re.id,name:String(re.name||re.id||"").trim()||re.id})),onUpsert:re=>re.scope==="agent"?Po({agentId:String(re.agentId||"").trim(),key:re.key,description:re.description,value:re.value}):Df({key:re.key,description:re.description,value:re.value}),onRemove:re=>re.scope==="agent"?Ps(String(re.agentId||"").trim(),re.key):_f(re.key),onImport:re=>re.scope==="agent"?Vi(String(re.agentId||"").trim(),re.raw):Pr(re.raw)})})}case"agentOverview":return Ma();case"agentAuthorization":return o.jsx("section",{children:o.jsx(sI,{authorization:A,loading:xe,selectedAgent:j,formatTime:Nn.formatTime,onRefresh:()=>Re(S),onSaveConfig:V=>Ye(V),onRunAction:V=>yt(V)})});case"agentCommand":return o.jsx("section",{className:"flex min-h-0 flex-1",children:o.jsx(w0,{selectedAgentId:S,selectedAgentName:String((j==null?void 0:j.name)||"").trim()||"agent",agents:m,persistSelectionInUrl:!1,onExecute:V=>or(V)})});case"globalAgents":return o.jsx("section",{children:o.jsx(O0,{cityVersion:v,agents:m,modelPoolItems:pe,plugins:H,configStatus:ie,onPickAgentDirectory:()=>Es(),onInspectAgentDirectory:V=>Aa(V),onLoadLocalModels:V=>Ft(V),onStartAgent:V=>vt(V),onStartAgentWithInitialization:(V,re)=>vt(V,{initializeIfNeeded:!0,initialization:{projectRoot:V,agentName:re.agentName,executionMode:re.executionMode,modelId:re.modelId,localModel:re.localModel,agentType:re.agentType}}),onRestartAgent:V=>Ue(V),onStopAgent:V=>Ms(V)})});case"globalModel":return o.jsx("section",{children:o.jsx(SI,{model:se,providers:oe,poolItems:pe,loading:xe,onUpsertProvider:V=>void ye(V),onRemoveProvider:V=>void Ea(V),onTestProvider:V=>void Nf(V),onDiscoverProvider:V=>Tf(V),onUpsertModel:V=>Af(V),onRemoveModel:V=>void Ef(V),onPauseModel:(V,re)=>void Mf(V,re),onTestModel:(V,re)=>void Rf(V,re)})});case"globalChannelAccounts":return o.jsx("section",{children:o.jsx(gI,{items:_,loading:xe,onUpsert:V=>Of(V),onProbe:V=>zf(V),onRemove:V=>If(V)})});case"globalCommand":return o.jsx("section",{className:"flex min-h-0 flex-1",children:o.jsx(w0,{selectedAgentId:S,selectedAgentName:String((j==null?void 0:j.name)||"").trim()||"agent",agents:m,persistSelectionInUrl:!0,onExecute:V=>or(V)})});case"globalPlugins":return o.jsx("section",{children:o.jsx(E0,{scope:"global",plugins:H,formatTime:Nn.formatTime,statusBadgeVariant:Nn.statusBadgeVariant,onRunAction:(V,re,Ke)=>Te(V,re,Ke)})});case"agentPlugins":return o.jsx("section",{children:o.jsx(E0,{scope:"agent",plugins:R,hasRunningAgent:(j==null?void 0:j.running)===!0,selectedAgentName:String((j==null?void 0:j.name)||"").trim(),formatTime:Nn.formatTime,statusBadgeVariant:Nn.statusBadgeVariant,onRunAction:(V,re,Ke)=>Se(V,re,Ke)})});case"agentSkills":return o.jsx("section",{children:o.jsx(t7,{skills:N,loading:xe,selectedAgentId:S,onRefreshSkills:()=>F(S),onFindSkill:V=>Je(V),onInstallSkill:V=>jt(V)})});case"agentTasks":return o.jsx("section",{children:o.jsx(u7,{tasks:Z,statusBadgeVariant:Nn.statusBadgeVariant,formatTime:Nn.formatTime,onRunTask:V=>void Ct(V),onSetTaskStatus:(V,re)=>zt(V,re),onDeleteTask:V=>Ce(V),onLoadTaskRuns:(V,re)=>rt(V,re),onDeleteTaskRun:(V,re)=>et(V,re),onClearTaskRuns:V=>$e(V),onLoadTaskRunDetail:(V,re)=>Ht(V,re),selectedTaskTitle:i,onSelectTaskTitle:V=>{const re=String(V||"").trim();l(re),Kt("agentTasks",re?{taskTitle:re}:void 0)}})});case"agentLogs":return o.jsx("section",{children:o.jsx(e7,{logs:te,formatTime:Nn.formatTime})});case"contextOverview":return o.jsx("section",{children:o.jsx(RI,{sessions:T,selectedSessionId:E,chatChannels:I,channelAccounts:_,focusedChannel:Hr,formatTime:Nn.formatTime,onOpenSession:V=>{d(Yt(V)),Kt("contextWorkspace",{sessionId:V,channel:Yt(V)}),U(V)},onDeleteSession:V=>{In(V)},deletingSessionId:G,onChatAction:(V,re)=>void Fe(V,re),onChatConfigure:(V,re)=>void Ae(V,re)})});case"contextWorkspace":return o.jsx("section",{className:"h-full min-h-0",children:o.jsx(UI,{selectedSessionId:E,sessions:T,channelHistory:q,chatChannels:I,sessionMessages:k,sessionArchives:D,selectedArchiveId:B,sessionArchiveMessages:Q,prompt:ne,chatInput:L,debugPanelsCollapsed:f,sending:ee,clearingSessionMessages:W,clearingChatHistory:X,deletingSession:!!G,formatTime:Nn.formatTime,onChangeInput:me,onSendConsoleUiMessage:()=>void zn(),onClearSessionMessages:()=>{E&&ms(E)},onClearChatHistory:()=>{E&&Bs(E)},onDeleteSession:()=>{E&&In(E)},onRefreshArchives:()=>{!S||!E||K(S,E)},onSelectArchive:V=>{!S||!E||Sn(S,E,V)},onSelectSession:V=>{Kt("contextWorkspace",{sessionId:V,channel:Yt(V)}),U(V)}})});default:return null}},Nc=o.jsx("div",{className:"flex items-center gap-2",children:n==="contextWorkspace"?o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"size-8 rounded-[11px] text-muted-foreground hover:bg-secondary hover:text-foreground",onClick:()=>{g(V=>!V)},"aria-label":f?"展开 Debug Panels":"折叠 Debug Panels",title:f?"展开 Debug Panels":"折叠 Debug Panels",children:f?o.jsx(Cw,{className:"size-4"}):o.jsx(Fm,{className:"size-4"})}):null});return h||!y?o.jsx(aI,{checking:h,bootstrapRequired:x,submitting:b,errorMessage:p,onSubmit:Yi}):o.jsxs(Sz,{style:{"--sidebar-width":"18.5rem","--header-height":"3.5rem"},children:[o.jsx(Bz,{activeView:n,agents:m,selectedAgentId:S,routePathname:e,routeAgentId:kc,sessions:T,chatChannels:I,selectedSessionId:E,tasks:Z,selectedTaskTitle:i,selectedChatChannel:Hr,onViewChange:V=>{if(V==="contextWorkspace"){const re=E||ar.CONSOLEUI_SESSION_ID;d(Yt(re)),Kt("contextWorkspace",{sessionId:re,channel:Yt(re)}),U(re);return}V!=="contextOverview"&&d(""),Kt(V)},onAgentChange:V=>{ge(V),d(""),Kt("globalOverview",{agentId:V})},onAgentEnter:V=>{ge(V),d(""),Kt("agentOverview",{agentId:V})},onTaskOpen:V=>{d(""),l(V),Kt("agentTasks",{taskTitle:V})},onChannelOpen:V=>{const re=String(V||"").trim().toLowerCase();d(re),Kt("contextOverview",{channel:re})},onSessionOpen:V=>{d(Yt(V)),Kt("contextWorkspace",{sessionId:V,channel:Yt(V)}),U(V)},topbarStatus:ue,topbarError:ae,loading:xe,onRefresh:()=>void ce(),user:M,tokens:O,onLogout:Ki,variant:"sidebar"}),o.jsxs(kz,{children:[o.jsx(g7,{viewLabel:Iz(n),rightActions:Nc}),o.jsx("main",{className:Me("mainview-shell flex flex-1 min-h-0 flex-col bg-transparent",n==="contextWorkspace"?"gap-0 overflow-hidden px-3 pb-3 pt-1 md:px-4 md:pb-4 md:pt-1":"gap-4 overflow-y-auto overflow-x-hidden px-3 pb-3 pt-1 md:px-4 md:pb-4 md:pt-1"),children:Zi()})]}),J?o.jsx(d7,{message:J.message,type:J.type}):null]})}const Yj=document.getElementById("root");if(!Yj)throw new Error("Missing #root element");PT.createRoot(Yj).render(o.jsx(c.StrictMode,{children:o.jsx(Jr,{children:o.jsx(qz,{children:o.jsx(_D,{})})})}));
|
|
422
|
+
`})}function gz(e){var s;if(e.zones.length===0)return e.activeZoneId;const n=(Math.max(0,e.zones.findIndex(r=>r.id===e.activeZoneId))+e.direction+e.zones.length)%e.zones.length;return((s=e.zones[n])==null?void 0:s.id)||e.activeZoneId}function mz(e){const{board:t,loading:n,selectedAgentId:s,onRefresh:r,onSelectAgent:a,className:i}=e,l=oz({board:t,selectedAgentId:s}),u=c.useRef(null),d=c.useRef(null),[f,g]=c.useState("clusters"),[m,h]=c.useState(!0),[x,y]=c.useState("cruise"),[w,b]=c.useState(!1),[p,v]=c.useState(null),S=c.useRef(l==null?void 0:l.id),[j,C]=c.useState(()=>l?Fs(l):"engaged");c.useEffect(()=>{if(!(l!=null&&l.id)){S.current=void 0;return}l.id!==S.current&&(S.current=l.id,C(Fs(l)))},[l]),c.useEffect(()=>{if(!p)return;const k=window.setTimeout(()=>v(null),620);return()=>window.clearTimeout(k)},[p]),c.useEffect(()=>{const k=()=>{b(document.fullscreenElement===u.current)};return document.addEventListener("fullscreenchange",k),()=>document.removeEventListener("fullscreenchange",k)},[]);const A=_l(j),M=c.useMemo(()=>((t==null?void 0:t.agents)||[]).filter(k=>Fs(k)===j),[j,t]),O=c.useMemo(()=>((t==null?void 0:t.agents)||[]).filter(k=>Fs(k)===j),[j,t]),P=c.useMemo(()=>t?MO({board:t,activeZoneId:j,selectedAgentId:l==null?void 0:l.id}):null,[j,t,l==null?void 0:l.id]),$=c.useMemo(()=>P?f==="clusters"?P.actors.map((k,D)=>{const B=P.corridors.find(Q=>Q.id===`corridor-${k.id}`);return{id:k.id,anchor:k.overviewAnchor,swayX:6+D%3*2.5,swayY:4+D%4*1.7,phase:D*.9,speed:.8+D%5*.08,mode:"route",route:(B==null?void 0:B.points)||k.overviewRoute,dwellRatio:B==null?void 0:B.dwellRatio,snapSize:B==null?void 0:B.snapSize}}):P.actors.filter(k=>k.zoneId===j&&k.focusedAnchor).map((k,D)=>{var Z;const B=P.patrols.find(te=>te.id===k.focusedRouteId),Q=k.focusedAnchor||{x:$t/2,y:Pt/2};return{id:k.id,anchor:Q,swayX:9+D%3*2.2,swayY:6+D%4*1.6,phase:D*.82,speed:.95+D%5*.1,mode:"route",route:(B==null?void 0:B.points)||((Z=P.patrols[D%Math.max(P.patrols.length,1)])==null?void 0:Z.points)||[Q],dwellRatio:B==null?void 0:B.dwellRatio,snapSize:B==null?void 0:B.snapSize}}):[],[j,P,f]),z=rz({nodes:$,flowMode:x}),N=iz({viewportRef:d,isFullscreen:w}),H=c.useCallback((k,D)=>{v(B=>({key:((B==null?void 0:B.key)||0)+1,label:k,mode:D}))},[]),R=c.useCallback(k=>{H(_l(k).title,"enter"),C(k),g("agents"),h(!0);const D=az({board:t,zoneId:k});D&&(a==null||a(D.id))},[t,a,H]),I=c.useCallback(k=>{const D=((t==null?void 0:t.agents)||[]).find(Q=>Q.id===k);if(!D)return;const B=Fs(D);(f==="clusters"||B!==j)&&H(_l(B).title,"enter"),C(B),g("agents"),h(!0),a==null||a(k)},[j,t,a,f,H]),T=c.useCallback(()=>{H("World Atlas","world"),g("clusters")},[H]),E=c.useCallback(k=>{if(P){if(k.key==="ArrowLeft"||k.key==="ArrowRight"){k.preventDefault();const D=gz({zones:P.zones,activeZoneId:j,direction:k.key==="ArrowRight"?1:-1});C(D);return}if(k.key==="Enter"&&f==="clusters"){k.preventDefault(),R(j);return}k.key==="Escape"&&f==="agents"&&(k.preventDefault(),T())}},[j,T,P,R,f]),q=c.useCallback(async()=>{const k=u.current;if(k){if(document.fullscreenElement===k){await document.exitFullscreen();return}document.fullscreenElement&&await document.exitFullscreen(),await k.requestFullscreen()}},[]);return!t||!P?o.jsx("div",{className:Pe("grid min-h-72 place-items-center border-2 border-dashed border-border/70 bg-[linear-gradient(145deg,rgba(247,244,236,0.84),rgba(255,255,255,0.95))] text-sm text-muted-foreground",i),style:{clipPath:xs},children:n?"正在生成 workboard game world...":"当前没有可展示的 workboard game world。"}):o.jsxs("section",{className:Pe("min-h-full",i),children:[o.jsx(fz,{}),o.jsxs("section",{ref:u,tabIndex:0,onKeyDown:E,className:Pe("relative overflow-hidden bg-[linear-gradient(145deg,rgba(236,232,218,0.96),rgba(255,252,247,0.98)_42%,rgba(217,231,224,0.76))] outline-none focus-visible:ring-2 focus-visible:ring-foreground/30",w?"h-[100dvh] rounded-none":"border-2 border-border/70 p-2 shadow-[0_8px_0_rgba(17,17,19,0.12)]"),style:w?void 0:{clipPath:xs},children:[o.jsx("div",{className:"pointer-events-none absolute inset-0 z-10 bg-[linear-gradient(rgba(17,17,19,0.04)_1px,transparent_1px),linear-gradient(90deg,rgba(17,17,19,0.04)_1px,transparent_1px)] bg-[size:18px_18px] opacity-40"}),o.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-10 h-16 bg-[linear-gradient(180deg,transparent,rgba(17,17,19,0.08),transparent)]",style:{animation:"workboard-world-scan 4.5s steps(6, end) infinite"}}),o.jsx(cz,{board:t,stageLevel:f,activeZone:A,selected:l,flowMode:x,loading:n,isFullscreen:w,zones:P.zones,onSelectZone:R,onBackToAtlas:T,onToggleFlowMode:()=>y(k=>k==="cruise"?"turbo":"cruise"),onRefresh:r,onToggleFullscreen:q}),o.jsxs("div",{ref:d,className:Pe("z-20 grid w-full place-items-center",w?"absolute inset-0 overflow-hidden":"relative overflow-auto border-2 border-border/70 bg-[linear-gradient(145deg,rgba(251,250,247,0.96),rgba(245,248,245,0.88))]"),style:w?void 0:{minHeight:720,clipPath:xs},children:[o.jsx(lz,{scale:N,children:f==="clusters"?o.jsx(hO,{board:t,gameMap:P,activeZoneId:j,selectedAgentId:l==null?void 0:l.id,flowMode:x,motionFrames:z,onSelectZone:R,onSelectAgent:k=>I(k)}):o.jsx(tz,{zone:A,items:M,gameMap:P,selectedAgentId:l==null?void 0:l.id,motionFrames:z,flowMode:x,onSelectAgent:I})}),o.jsx(dz,{portal:p}),o.jsx(vO,{selected:l,activeZone:A,selectedPeers:O,stageLevel:f,collapsed:m,onToggleCollapsed:()=>h(k=>!k),onSelectAgent:I})]})]})]})}const _g=768;function hz(){const[e,t]=c.useState(void 0);return c.useEffect(()=>{const n=window.matchMedia(`(max-width: ${_g-1}px)`),s=()=>{t(window.innerWidth<_g)};return n.addEventListener("change",s),t(window.innerWidth<_g),()=>n.removeEventListener("change",s)},[]),!!e}function Me(...e){return aw(pp(e))}const pz="sidebar_state",xz=60*60*24*7,bz="16rem",yz="18rem",vz="3rem",wz="b",Mj=c.createContext(null);function xx(){const e=c.useContext(Mj);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}function Sz({defaultOpen:e=!0,open:t,onOpenChange:n,className:s,style:r,children:a,...i}){const l=hz(),[u,d]=c.useState(!1),[f,g]=c.useState(e),m=t??f,h=c.useCallback(b=>{const p=typeof b=="function"?b(m):b;n?n(p):g(p),document.cookie=`${pz}=${p}; path=/; max-age=${xz}`},[n,m]),x=c.useCallback(()=>l?d(b=>!b):h(b=>!b),[l,h,d]);c.useEffect(()=>{const b=p=>{p.key===wz&&(p.metaKey||p.ctrlKey)&&(p.preventDefault(),x())};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[x]);const y=m?"expanded":"collapsed",w=c.useMemo(()=>({state:y,open:m,setOpen:h,isMobile:l,openMobile:u,setOpenMobile:d,toggleSidebar:x}),[y,m,h,l,u,d,x]);return o.jsx(Mj.Provider,{value:w,children:o.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":bz,"--sidebar-width-icon":vz,...r},className:Me("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",s),...i,children:a})})}function jz({side:e="left",variant:t="sidebar",collapsible:n="offcanvas",className:s,children:r,dir:a,...i}){const{isMobile:l,state:u,openMobile:d,setOpenMobile:f}=xx();return n==="none"?o.jsx("div",{"data-slot":"sidebar",className:Me("flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",s),...i,children:r}):l?o.jsx(b6,{open:d,onOpenChange:f,...i,children:o.jsxs(w6,{dir:a,"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"w-(--sidebar-width) bg-sidebar/98 p-0 text-sidebar-foreground backdrop-blur-sm [&>button]:hidden",style:{"--sidebar-width":yz},side:e,children:[o.jsxs(S6,{className:"sr-only",children:[o.jsx(j6,{children:"Sidebar"}),o.jsx(C6,{children:"Displays the mobile sidebar."})]}),o.jsx("div",{className:"flex h-full w-full flex-col",children:r})]})}):o.jsxs("div",{className:"group peer hidden text-sidebar-foreground md:block","data-state":u,"data-collapsible":u==="collapsed"?n:"","data-variant":t,"data-side":e,"data-slot":"sidebar",children:[o.jsx("div",{"data-slot":"sidebar-gap",className:Me("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",t==="floating"||t==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),o.jsx("div",{"data-slot":"sidebar-container","data-side":e,className:Me("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",t==="floating"||t==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",s),...i,children:o.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:"flex size-full flex-col rounded-[20px] bg-sidebar/98 shadow-[0_1px_0_rgba(17,17,19,0.02),0_8px_24px_rgba(17,17,19,0.02)] backdrop-blur-sm group-data-[variant=floating]:rounded-[20px]",children:r})})]})}function Cz({className:e,onClick:t,...n}){const{toggleSidebar:s}=xx();return o.jsxs(be,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon-sm",className:Me(e),onClick:r=>{t==null||t(r),s()},...n,children:[o.jsx(C5,{}),o.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function kz({className:e,...t}){return o.jsx("main",{"data-slot":"sidebar-inset",className:Me("relative flex w-full flex-1 flex-col bg-secondary/70 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-[24px] md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",e),...t})}function Nz({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:Me("flex flex-col gap-2 p-2",e),...t})}function Tz({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-footer","data-sidebar":"footer",className:Me("flex flex-col gap-2 p-2",e),...t})}function Az({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:Me("no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t})}function ll({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-group","data-sidebar":"group",className:Me("relative flex w-full min-w-0 flex-col p-2",e),...t})}function cl({className:e,render:t,...n}){return Cp({defaultTagName:"div",props:zr({className:Me("flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",e)},n),render:t,state:{slot:"sidebar-group-label",sidebar:"group-label"}})}function ul({className:e,...t}){return o.jsx("div",{"data-slot":"sidebar-group-content","data-sidebar":"group-content",className:Me("w-full text-sm",e),...t})}function Ia({className:e,...t}){return o.jsx("ul",{"data-slot":"sidebar-menu","data-sidebar":"menu",className:Me("flex w-full min-w-0 flex-col gap-0",e),...t})}function Us({className:e,...t}){return o.jsx("li",{"data-slot":"sidebar-menu-item","data-sidebar":"menu-item",className:Me("group/menu-item relative",e),...t})}const Ez=rf("peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:p-0!"}},defaultVariants:{variant:"default",size:"default"}});function mr({render:e,isActive:t=!1,variant:n="default",size:s="default",tooltip:r,className:a,...i}){const{isMobile:l,state:u}=xx(),d=Cp({defaultTagName:"button",props:zr({className:Me(Ez({variant:n,size:s}),a)},i),render:r?o.jsx(Wr,{render:e}):e,state:{slot:"sidebar-menu-button",sidebar:"menu-button",size:s,active:t}});return r?(typeof r=="string"&&(r={children:r}),o.jsxs(Qr,{children:[d,o.jsx(eo,{side:"right",align:"center",hidden:u!=="collapsed"||l,...r})]})):d}function bx(e){const t=String(e||"").trim().toLowerCase();return t==="telegram"?"Telegram":t==="feishu"?"Feishu":t==="qq"?"QQ (dev)":t==="consoleui"?"Console UI":t||"-"}const Mz=new Set(["telegram","qq","feishu","consoleui"]);function Rj(e){return String(e||"").trim().toLowerCase()}function f0(e){const t=Rj(e);return t?t.startsWith("api:")?"api":t.startsWith("consoleui-")||t==="local_ui"?"consoleui":"other":"other"}function ma(e){if(typeof e=="string")return f0(e);const t=Rj(e.channel);return Mz.has(t)?t:t==="api"?"api":t&&t!=="other"?t:f0(e.sessionId)}function Oj(e){const t=ma(e);return t==="api"?"api":t==="other"?"other":"chat"}function Rz(e){return[...e].sort((t,n)=>{const s=Number(t.updatedAt||0),r=Number(n.updatedAt||0);return s!==r?r-s:t.sessionId.localeCompare(n.sessionId)})}function zj(e){const t=Rz(e),n={chat:[],api:[],other:[]};for(const r of t){const a=Oj(r);n[a].push(r)}return[{key:"chat",title:"chat:*",items:n.chat},{key:"api",title:"api:*",items:n.api},{key:"other",title:"other",items:n.other}].filter(r=>r.items.length>0)}function Oz(e,t){const n=String(t||"").trim().toLowerCase();return n?e.filter(s=>{const r=String(s.sessionId||"").toLowerCase(),a=String(s.chatId||"").toLowerCase(),i=String(s.chatTitle||"").toLowerCase(),l=String(s.lastRole||"").toLowerCase(),u=String(s.lastText||"").toLowerCase();return r.includes(n)||a.includes(n)||i.includes(n)||l.includes(n)||u.includes(n)}):e}const yx={globalOverview:{view:"globalOverview",scope:"global",title:"Overview",path:"/global/overview"},globalWorkboard:{view:"globalWorkboard",scope:"global",title:"Workboard",path:"/global/workboard"},globalApiKeys:{view:"globalApiKeys",scope:"global",title:"API Keys",path:"/global/api-keys"},globalEnv:{view:"globalEnv",scope:"global",title:"Env",path:"/global/env"},globalModel:{view:"globalModel",scope:"global",title:"Model",path:"/global/model"},globalChannelAccounts:{view:"globalChannelAccounts",scope:"global",title:"Channel Accounts",path:"/global/channel-accounts"},globalCommand:{view:"globalCommand",scope:"global",title:"Command",path:"/global/command"},globalAgents:{view:"globalAgents",scope:"global",title:"Agents",path:"/global/agents"},globalPlugins:{view:"globalPlugins",scope:"global",title:"Plugins",path:"/global/plugins"},agentOverview:{view:"agentOverview",scope:"agent",title:"Overview",path:"/agent/overview"},agentAuthorization:{view:"agentAuthorization",scope:"agent",title:"Authorization",path:"/agent/authorization"},agentPlugins:{view:"agentPlugins",scope:"agent",title:"Plugins",path:"/agent/plugins"},agentSkills:{view:"agentSkills",scope:"agent",title:"Skills",path:"/agent/skills"},agentServices:{view:"agentServices",scope:"agent",title:"Services",path:"/agent/services"},agentCommand:{view:"agentCommand",scope:"agent",title:"Command",path:"/agent/command"},agentTasks:{view:"agentTasks",scope:"agent",title:"Tasks",path:"/agent/tasks"},agentLogs:{view:"agentLogs",scope:"agent",title:"Logs",path:"/agent/logs"},contextOverview:{view:"contextOverview",scope:"context",title:"Overview",path:"/context/overview"}},zz={global:"Global",agent:"Agent",context:"Session"},Ij=["globalOverview","globalWorkboard","globalApiKeys","globalCommand","globalEnv","globalModel","globalChannelAccounts","globalAgents","globalPlugins","agentOverview","agentAuthorization","agentPlugins","agentSkills","agentServices","agentCommand","agentTasks","agentLogs","contextOverview"];function g0(e){return Ij.map(t=>yx[t]).filter(t=>t.scope===e)}function Iz(e){if(e==="contextWorkspace")return"Session / Workspace";const t=yx[e];return`${zz[t.scope]} / ${t.title}`}function Dz(){return Ij.reduce((e,t)=>(e[t]=yx[t].path,e),{})}const m0={globalOverview:o.jsx(Xc,{}),globalWorkboard:o.jsx(Gm,{}),globalApiKeys:o.jsx(qm,{}),globalEnv:o.jsx(qm,{}),globalModel:o.jsx(py,{}),globalChannelAccounts:o.jsx(zp,{}),globalCommand:o.jsx(Vm,{}),globalAgents:o.jsx(Xc,{}),globalPlugins:o.jsx(hy,{}),agentOverview:o.jsx(Xc,{}),agentAuthorization:o.jsx(Tw,{}),agentPlugins:o.jsx(hy,{}),agentSkills:o.jsx(Aw,{}),agentServices:o.jsx(py,{}),agentCommand:o.jsx(Vm,{}),agentTasks:o.jsx(Gm,{}),agentLogs:o.jsx(B5,{}),contextOverview:o.jsx(Xc,{})};function _z(e,t){if(!e)return t;if(e.running===!0)return!0;if(e.running===!1)return!1;if(e.enabled===!0)return!0;if(e.enabled===!1)return!1;const n=String(e.linkState||"").trim().toLowerCase();return["connected","disconnected","error"].includes(n)?!0:t}function Lz(e){return e.running===!0?!0:String(e.status||"").trim().toLowerCase()==="running"}function h0(e){return e.active?o.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center text-sidebar-foreground/60","aria-label":e.label,title:e.label,children:o.jsx(nt,{className:"size-3 animate-spin"})}):o.jsx("span",{"aria-hidden":"true",className:"inline-flex h-4 w-4 shrink-0"})}function Bz({activeView:e,agents:t,selectedAgentId:n,routePathname:s,routeAgentId:r,sessions:a,selectedSessionId:i,tasks:l,selectedTaskTitle:u,selectedChatChannel:d,chatChannels:f,onViewChange:g,onAgentChange:m,onAgentEnter:h,onSessionOpen:x,onTaskOpen:y,onChannelOpen:w,topbarStatus:b,topbarError:p,loading:v,onRefresh:S,...j}){var ge;const C=zj(a),A=c.useMemo(()=>C.find(U=>U.key==="chat")??null,[C]),M=c.useMemo(()=>C.filter(U=>U.key!=="chat"),[C]),O=c.useMemo(()=>[...(A==null?void 0:A.items)||[],...M.flatMap(U=>U.items)],[A,M]),P=c.useMemo(()=>{const U={},ce=Se=>{const Fe=String(Se||"").trim().toLowerCase();Fe&&(U[Fe]||(U[Fe]=[]))};for(const Se of O){const Fe=ma(Se);ce(Fe),U[Fe].push(Se)}for(const Se of f)ce(String(Se.channel||""));const F=["telegram","qq","feishu","consoleui","other"],K=F.filter(Se=>Object.prototype.hasOwnProperty.call(U,Se)),he=Object.keys(U).filter(Se=>!F.includes(Se)).sort((Se,Fe)=>Se.localeCompare(Fe));return[...K,...he].map(Se=>({channel:Se,items:U[Se]||[]}))},[f,O]),$=c.useMemo(()=>g0("global"),[]),z=c.useMemo(()=>$.filter(U=>U.view!=="globalAgents"),[$]),N=c.useMemo(()=>g0("agent"),[]),R=["globalOverview","globalWorkboard","globalApiKeys","globalCommand","globalEnv","globalModel","globalChannelAccounts","globalAgents","globalPlugins"].includes(e)?"agent-list":"agent-detail",[I,T]=c.useState("forward"),[E,q]=c.useState(""),[k,D]=c.useState({}),B=c.useRef(R),Q=c.useMemo(()=>{if(e!=="globalOverview")return!1;const U=s.split("/").filter(Boolean);return U.length>=3&&U[0]==="global"&&U[1]==="agent"},[e,s]),Z=c.useMemo(()=>{const U=s.split("/").filter(Boolean);return U.length>=2&&U[0]==="global"&&U[1]==="overview"},[s]),te=t.find(U=>U.id===n)??null,ie="rounded-[12px] text-sidebar-foreground/82 hover:bg-sidebar-accent hover:text-sidebar-foreground data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-foreground h-9 px-2.5 text-[13px]",oe="h-9 px-2.5 opacity-60 data-[slot=sidebar-menu-button]:cursor-default",pe="grid w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)_1.5rem] items-center gap-2",_="relative py-0.5",Y="absolute inset-y-0 left-1 z-10 my-auto h-6 w-6 rounded-[10px] text-sidebar-foreground/60 transition-colors hover:bg-sidebar-accent hover:text-sidebar-foreground active:translate-y-0",le=Me(ie,"h-8 w-full rounded-[12px] px-2.5 pl-8 text-[11px] font-medium uppercase tracking-[0.08em]","data-[active=true]:bg-sidebar-accent/75","hover:bg-sidebar-accent/35"),ne="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2",ue="inline-flex h-2 w-2 rounded-full",ae="min-w-0 overflow-hidden transition-[max-height,opacity] duration-200 ease-out",xe="min-w-0 pl-4",ee="min-w-0 gap-0 pl-1.5",W=Me(ie,"h-7 w-full min-w-0 rounded-[12px] px-2 text-[10px]","data-[active=true]:bg-sidebar-accent/75","hover:bg-sidebar-accent/45"),X="grid w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)_1rem] items-center gap-1.5",G="inline-flex size-4 items-center justify-center text-muted-foreground",L="min-w-0 truncate text-[10px] font-medium",J=String(d||"").trim().toLowerCase(),me=c.useMemo(()=>{const U=new Map;for(const ce of f){const F=String(ce.channel||"").trim().toLowerCase();F&&U.set(F,ce)}return U},[f]);return c.useEffect(()=>{B.current!==R&&(T(R==="agent-detail"?"forward":"back"),B.current=R)},[R]),c.useEffect(()=>{D({})},[n]),o.jsxs(jz,{collapsible:"offcanvas",className:"bg-transparent",...j,children:[o.jsx(Nz,{children:o.jsx("div",{className:"px-3 pb-2 pt-3",children:o.jsxs("div",{className:"flex h-9 max-w-full items-center gap-2 text-sidebar-foreground",children:[o.jsx(be,{size:"sm",variant:"ghost",className:Me("h-8 w-8 rounded-[11px] p-0 text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground","opacity-100"),onClick:()=>{R==="agent-detail"&&g("globalOverview")},"aria-label":R==="agent-detail"?"返回":"DOWNCITY",title:R==="agent-detail"?"返回":"DOWNCITY",children:R==="agent-detail"?o.jsx(Cw,{className:"size-4"}):o.jsx("img",{src:"/image.png",alt:"DOWNCITY",className:"size-4 shrink-0 object-cover"})}),o.jsx("span",{className:Me("inline-flex items-center gap-1.5 truncate","text-[0.92rem] font-medium tracking-[-0.03em]"),children:o.jsx("span",{children:R==="agent-detail"?(te==null?void 0:te.agentId)||"Agent":"DOWNCITY"})}),o.jsx("div",{className:"ml-auto",children:o.jsx(be,{type:"button",variant:"ghost",size:"icon",className:Me("size-8 rounded-[11px]",p?"text-destructive hover:bg-destructive/10":"text-sidebar-foreground/60 hover:bg-sidebar-accent hover:text-sidebar-foreground"),onClick:S,disabled:v,"aria-label":v?"刷新中":"刷新",title:b,children:o.jsx(xc,{className:Me("size-4",v&&"animate-spin")})})})]})})}),o.jsx(Az,{className:"relative gap-1.5 overflow-hidden",children:o.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:[o.jsxs("div",{className:Me("absolute inset-0 overflow-y-auto transition-all duration-200 ease-out",R==="agent-list"?"translate-x-0 opacity-100":I==="forward"?"-translate-x-6 opacity-0":"translate-x-6 opacity-0",R==="agent-list"?"pointer-events-auto":"pointer-events-none"),children:[o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Console"}),o.jsx(ul,{children:o.jsx(Ia,{children:z.map(U=>o.jsx(Us,{children:o.jsx(mr,{tooltip:U.title,isActive:U.view==="globalOverview"?e==="globalOverview"&&Z:e===U.view,onClick:()=>g(U.view),className:ie,children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:m0[U.view]}),o.jsx("span",{className:"truncate",children:U.title}),o.jsx("span",{})]})})},U.view))})})]}),o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Agents"}),o.jsx(ul,{children:o.jsxs(Ia,{children:[t.length===0?o.jsx(Us,{children:o.jsx(mr,{render:o.jsx("button",{type:"button",disabled:!0}),className:oe,children:o.jsx("span",{className:"text-xs text-muted-foreground",children:"无运行中的 agent"})})}):null,t.map(U=>{const ce=Q&&U.id===r,F=U.running===!0;return o.jsx(Us,{children:o.jsx(mr,{tooltip:U.id,isActive:ce,onMouseEnter:()=>q(U.id),onMouseLeave:()=>q(K=>K===U.id?"":K),onClick:()=>m(U.id),onDoubleClick:()=>h(U.id),className:Me(ie,!F&&"opacity-55"),children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(zp,{className:"size-4 shrink-0"})}),o.jsx("span",{className:"min-w-0",children:o.jsx("span",{className:"truncate",children:U.agentId||"unknown-agent"})}),F?o.jsxs("span",{className:"relative inline-flex h-6 w-6 items-center justify-center",children:[o.jsx("span",{className:Me("inline-flex h-2 w-2 shrink-0 rounded-full bg-emerald-500",E===U.id?"opacity-0":"opacity-100")}),o.jsx("span",{role:"button",tabIndex:0,className:Me("absolute inset-0 inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-[10px] p-0 text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground",E===U.id?"opacity-100":"pointer-events-none opacity-0"),"aria-label":"进入 Agent",title:"进入 Agent",onClick:K=>{K.stopPropagation(),h(U.id)},onKeyDown:K=>{K.key!=="Enter"&&K.key!==" "||(K.preventDefault(),K.stopPropagation(),h(U.id))},children:o.jsx(Fm,{className:"size-4"})})]}):o.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 justify-self-center rounded-full bg-muted-foreground/60"})]})})},U.id)})]})})]})]}),o.jsxs("div",{className:Me("absolute inset-0 overflow-y-auto transition-all duration-200 ease-out",R==="agent-detail"?"translate-x-0 opacity-100":I==="forward"?"translate-x-6 opacity-0":"-translate-x-6 opacity-0",R==="agent-detail"?"pointer-events-auto":"pointer-events-none"),children:[o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Agent"}),o.jsx(ul,{children:o.jsx(Ia,{children:N.filter(U=>U.view!=="agentTasks"&&U.view!=="agentServices"&&U.view!=="agentCommand").map(U=>o.jsx(Us,{children:o.jsx(mr,{tooltip:U.title,isActive:e===U.view,onClick:()=>g(U.view),className:ie,children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:m0[U.view]}),o.jsx("span",{className:"truncate",children:U.title}),o.jsx("span",{})]})})},U.view))})})]}),o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Chat"}),o.jsx(ul,{children:o.jsxs(Ia,{children:[O.length===0?o.jsx(Us,{children:o.jsx(mr,{render:o.jsx("button",{type:"button",disabled:!0}),className:oe,children:o.jsx("span",{className:"text-xs text-muted-foreground",children:"暂无聊天会话"})})}):null,P.map(U=>{const ce=me.get(U.channel),F=_z(ce,U.items.length>0),K=F&&U.items.length>0,he=K?!!k[U.channel]:!0,Te=String((ce==null?void 0:ce.linkState)||(ce==null?void 0:ce.statusText)||(U.channel==="consoleui"?"connected":"unknown")).trim().toLowerCase(),Se=F?Te==="connected"?"bg-emerald-500":Te==="disconnected"||Te==="error"||Te==="failed"?"bg-destructive":"bg-muted-foreground/60":"bg-muted-foreground/45",Fe=e==="contextOverview"&&J===U.channel;return o.jsxs(c.Fragment,{children:[o.jsxs(Us,{className:_,children:[o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Me(Y,!K&&"cursor-default opacity-35 hover:bg-transparent hover:text-sidebar-foreground/60"),disabled:!K,onClick:Ae=>{Ae.preventDefault(),Ae.stopPropagation(),K&&D(Re=>({...Re,[U.channel]:!Re[U.channel]}))},"aria-label":`${he?"展开":"收起"} ${U.channel}`,title:`${he?"展开":"收起"} ${U.channel}`,children:o.jsx(Fm,{className:Me("size-3.5 shrink-0 transform-gpu transition-transform duration-200 ease-out",he?"rotate-0":"rotate-90")})}),o.jsx(mr,{tooltip:`${U.channel} · ${Te}`,isActive:Fe,className:Me(le,!F&&"text-muted-foreground/55 hover:bg-sidebar-accent/20 hover:text-muted-foreground/70"),onClick:()=>{w(U.channel)},children:o.jsxs("span",{className:ne,children:[o.jsx("span",{className:"truncate",children:bx(U.channel)}),o.jsx("span",{className:Me(ue,Se),"aria-label":`link state: ${Te}`,title:Te})]})})]}),o.jsx(Us,{className:Me(ae,he?"pointer-events-none max-h-0 opacity-0":"max-h-[28rem] opacity-100"),children:o.jsx("div",{className:xe,children:o.jsx(Ia,{className:ee,children:U.items.map(Ae=>{const Re=String(Ae.sessionId||"").trim();if(!Re)return null;const Ye=String(Ae.chatTitle||"").trim(),yt=String(Ae.chatId||"").trim(),De=Ye&&(!yt||Ye!==yt)?Ye:"",ot=De||yt||Re,_e=e==="contextWorkspace"&&i===Re,Je=Ae.executing===!0;return o.jsx(Us,{className:"min-w-0",children:o.jsx(mr,{tooltip:De?`${De} · ${Re}`:Re,isActive:_e,onClick:()=>x(Re),className:W,children:o.jsxs("span",{className:X,children:[o.jsx("span",{className:G,children:o.jsx(b5,{className:"h-2.5 w-2.5"})}),o.jsx("span",{className:L,children:ot}),o.jsx(h0,{active:Je,label:"会话执行中"})]})})},Re)})})})})]},`chat-group:${U.channel}`)})]})})]}),o.jsxs(ll,{className:"py-1",children:[o.jsx(cl,{className:"px-3 text-[10px] font-medium tracking-[0.16em] text-sidebar-foreground/42",children:"Tasks"}),o.jsx(ul,{children:o.jsxs(Ia,{children:[l.length===0?o.jsx(Us,{children:o.jsx(mr,{render:o.jsx("button",{type:"button",disabled:!0}),className:oe,children:o.jsx("span",{className:"text-xs text-muted-foreground",children:"暂无任务"})})}):null,l.map(U=>{const ce=String(U.title||"").trim();if(!ce)return null;const F=Lz(U);return o.jsx(Us,{children:o.jsx(mr,{tooltip:ce,isActive:e==="agentTasks"&&u===ce,onClick:()=>y(ce),className:ie,children:o.jsxs("span",{className:pe,children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(Gm,{className:"size-4"})}),o.jsx("span",{className:"truncate",children:ce}),o.jsx(h0,{active:F,label:"任务执行中"})]})})},`task:${ce}`)})]})})]})]})]})}),o.jsx(Tz,{className:"px-3 pb-3 pt-1",children:o.jsxs(yj,{children:[o.jsxs(vj,{render:o.jsx("button",{type:"button",className:Me(ie,"flex w-full items-center justify-start gap-2 text-sidebar-foreground/82")}),children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(Z5,{className:"size-4"})}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:((ge=j.user)==null?void 0:ge.username)||"admin"}),o.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 rounded-full bg-emerald-500"})]}),o.jsx(wj,{side:"top",align:"start",className:"w-48 p-1.5",children:o.jsx("div",{className:"space-y-0.5",children:o.jsxs("button",{type:"button",onClick:j.onLogout,className:"flex w-full items-center gap-2 rounded-[10px] px-2.5 py-2 text-[13px] text-sidebar-foreground/82 hover:bg-sidebar-accent hover:text-sidebar-foreground transition-colors",children:[o.jsx(m5,{className:"size-4"}),o.jsx("span",{children:"清除 Token"})]})})})]})})]})}function wt(e){const{title:t,description:n,actions:s,children:r,className:a,bodyClassName:i}=e;return o.jsxs("section",{className:Me("space-y-3 rounded-[22px] bg-background px-4 py-4 shadow-[0_1px_0_rgba(17,17,19,0.03)] ring-1 ring-border/70",a),children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("div",{className:"min-w-0",children:o.jsx("div",{className:"flex h-8 items-center text-xs uppercase tracking-[0.12em] text-muted-foreground",children:t})}),s?o.jsx("div",{className:Me("flex shrink-0 items-center gap-2","[&_[data-slot=button]]:h-8","[&_[data-slot=input]]:h-8","[&_[data-slot=badge]]:h-8","[&_[data-slot=button]]:rounded-[11px]","[&_[data-slot=input]]:rounded-[11px]","[&_[data-slot=badge]]:rounded-[999px]"),children:s}):null]}),o.jsx("div",{className:Me("space-y-3",i),children:r})]})}function Pz(e){const{tokens:t,loading:n,onCreateToken:s,onDeleteToken:r,onClearLatestIssuedToken:a,latestIssuedToken:i,formatTime:l}=e,[u,d]=c.useState(!1),[f,g]=c.useState(""),[m,h]=c.useState(!1),[x,y]=c.useState(""),[w,b]=c.useState(!1),p=c.useMemo(()=>t.length,[t]),v=c.useCallback(async()=>{if(f.trim())try{h(!0),await s({name:f.trim()}),g("")}finally{h(!1)}},[s,f]),S=c.useCallback(async C=>{try{y(C),await r({tokenId:C})}finally{y("")}},[r]);c.useEffect(()=>{i&&(d(!0),b(!1))},[i]);const j=c.useCallback(async()=>{if(i!=null&&i.token)try{await navigator.clipboard.writeText(i.token),b(!0),setTimeout(()=>b(!1),2e3)}catch{}},[i]);return o.jsxs(o.Fragment,{children:[o.jsx(wt,{title:"API Keys",description:`${t.length} total · ${p} active`,actions:o.jsxs(be,{type:"button",size:"sm",className:"h-8 rounded-[11px]",onClick:()=>d(!0),disabled:n,children:[o.jsx(fa,{className:"mr-1 size-4"}),"新建"]}),children:t.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary py-6 text-center text-sm text-muted-foreground",children:"暂无 API Key"}):o.jsx("div",{className:"space-y-1",children:t.map(C=>o.jsxs("div",{className:"group flex items-center gap-3 rounded-[12px] px-3 py-2.5 hover:bg-secondary",children:[o.jsx("span",{className:"inline-flex size-4 items-center justify-center text-muted-foreground",children:o.jsx(qm,{className:"size-3.5"})}),o.jsx("span",{className:"truncate text-sm",children:C.name}),o.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:l(C.createdAt)}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"size-8 rounded-[10px] text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(C.id),disabled:x===C.id,children:x===C.id?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(er,{className:"size-4"})})]},C.id))})}),o.jsx($n,{open:u,onOpenChange:d,children:o.jsxs(Un,{className:"w-[min(92vw,400px)]",children:[o.jsx(Hn,{children:o.jsx(Fn,{children:i?"API Key 已创建":"新建 API Key"})}),i?o.jsxs("div",{className:"space-y-4 px-4 py-2",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"请保存此 API Key,它只会显示一次"}),o.jsxs("div",{className:"relative",children:[o.jsx("code",{className:"block break-all rounded-[12px] bg-secondary px-3 py-3 pr-10 text-xs",children:i.token}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"absolute right-1 top-1/2 size-7 -translate-y-1/2 rounded-[8px]",onClick:j,children:w?o.jsx(Ws,{className:"size-4 text-emerald-500"}):o.jsx(t5,{className:"size-4"})})]})]}):o.jsx("div",{className:"space-y-4 px-4 py-2",children:o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{className:"text-xs",children:"名称"}),o.jsx(lt,{value:f,onChange:C=>g(C.target.value),placeholder:"API Key 名称",onKeyDown:C=>C.key==="Enter"&&v(),autoFocus:!0})]})}),o.jsx(rs,{className:"gap-2",children:i?o.jsx(be,{size:"sm",onClick:()=>{a(),d(!1)},children:"完成"}):o.jsxs(o.Fragment,{children:[o.jsx(be,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"取消"}),o.jsxs(be,{size:"sm",disabled:!f.trim()||m,onClick:()=>void v(),children:[m&&o.jsx(nt,{className:"mr-2 size-4 animate-spin"}),"创建"]})]})})]})})]})}function lu(e){return o.jsx("div",{className:"min-w-0 truncate text-sm text-foreground",title:e.value,children:e.value||"-"})}function $z(e){if(e.executionMode==="api"||!e.executionMode)return{executionType:"api",agentType:"kimi"};if(e.executionMode==="local")return{executionType:"local",agentType:"kimi"};const t=String(e.agentType||"").trim();return t==="claude"||t==="codex"?{executionType:"acp",agentType:t}:{executionType:"acp",agentType:"kimi"}}function Uz(e){return e.executionMode==="api"?String(e.modelId||"").trim()||"-":e.executionMode==="local"?`local ${String(e.localModel||"-").trim()||"-"}`:`acp ${String(e.agentType||"-").trim()||"-"}`}function Hz(e,t){const n=new Set,s=String(t||"").trim();s&&n.add(s);for(const r of e){const a=String(r||"").trim();a&&n.add(a)}return Array.from(n)}function Fz(e){var z;const{agent:t,model:n,onStart:s,onLoadLocalModels:r,onUpdateExecution:a}=e,[i,l]=c.useState(!1);if(!t)return o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"未选择 Agent"});const u=Uz(t),d=Array.isArray(n==null?void 0:n.availableModels)?n.availableModels:[],f=String((n==null?void 0:n.agentPrimaryModelId)||(n==null?void 0:n.primaryModelId)||t.modelId||"").trim(),g=String(((z=d[0])==null?void 0:z.id)||"").trim(),m=f||g,h=String(t.localModel||"").trim(),x=$z({executionMode:t.executionMode,agentType:t.agentType}),[y,w]=c.useState(x.executionType),[b,p]=c.useState(x.agentType),[v,S]=c.useState(h),[j,C]=c.useState([]),[A,M]=c.useState(!1),O=String(t.projectRoot||t.id||"").trim()||"-",P=t.stoppedAt?new Date(t.stoppedAt).toLocaleString("zh-CN",{hour12:!1}):"-";c.useEffect(()=>{w(x.executionType),p(x.agentType)},[x]),c.useEffect(()=>{S(h)},[h]),c.useEffect(()=>{let N=!1;return(async()=>{try{M(!0);const H=await r(t.projectRoot||t.id);if(N)return;C(H)}finally{N||M(!1)}})(),()=>{N=!0}},[t.id,t.projectRoot,r]);const $=c.useMemo(()=>Hz(j,v||h),[h,j,v]);return o.jsxs("section",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 px-1 py-1",children:[o.jsx("div",{className:"min-w-0",children:o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("img",{src:"/image.png",alt:"bot",className:"mt-0.5 size-8 shrink-0 rounded-[4px] object-cover"}),o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx("div",{className:"truncate text-xl font-semibold leading-none text-foreground/74",children:t.agentId||"Unknown Agent"}),o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:O})]})]})}),o.jsx(be,{size:"icon-sm",variant:"secondary",disabled:i,title:i?"启动中":"启动","aria-label":i?"启动中":"启动",onClick:async()=>{try{l(!0),await Promise.resolve(s(t.id))}finally{l(!1)}},children:i?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(sa,{className:"size-4"})})]}),o.jsxs("section",{className:"rounded-[18px] bg-secondary/72 px-3.5 py-3 space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium w-full"}),children:o.jsx("span",{className:"truncate",children:y==="api"?"API":y==="local"?"Local":"ACP"})}),o.jsxs(wn,{className:"max-h-72 min-w-[18rem]",children:[o.jsx(bt,{onClick:()=>{w("api"),m&&(x.executionType==="api"&&m===f||a({executionMode:"api",modelId:m}))},children:"API"}),o.jsx(bt,{onClick:()=>{w("local");const N=String(v||h||$[0]||"").trim();N&&(x.executionType==="local"&&N===h||a({executionMode:"local",localModel:N}))},children:"Local"}),o.jsx(bt,{onClick:()=>{w("acp");const N=b||x.agentType||"kimi";x.executionType==="acp"&&x.agentType===N||a({executionMode:"acp",agentType:N})},children:"ACP"})]})]}),y==="api"?o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium w-full"}),children:o.jsx("span",{className:"truncate",children:m||"选择 execution.modelId"})}),o.jsx(wn,{className:"max-h-72 min-w-[18rem]",children:d.length===0?o.jsx(bt,{disabled:!0,children:"无可选模型"}):d.map(N=>{const H=String(N.id||"").trim();return H?o.jsx(bt,{onClick:()=>{H===f&&x.executionType==="api"||a({executionMode:"api",modelId:H})},children:`${H} · ${N.providerType||"-"}${N.isPaused?" · paused":""}`},H):null})})]}):y==="local"?o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("select",{value:v,className:"flex h-9 flex-1 rounded-[12px] border border-input bg-background px-3 font-mono text-[12px] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",onChange:N=>S(N.target.value),disabled:A||$.length===0,children:[$.length===0?o.jsx("option",{value:"",children:A?"正在读取本地模型":"没有发现本地 GGUF 模型"}):null,$.map(N=>o.jsx("option",{value:N,children:N},N))]}),o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 rounded-[12px] bg-background px-3 text-xs",disabled:!String(v||"").trim()||A,onClick:()=>{const N=String(v||"").trim();N&&(x.executionType==="local"&&N===h||a({executionMode:"local",localModel:N}))},children:"应用"})]}):y==="acp"?o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium w-full"}),children:o.jsx("span",{className:"truncate",children:`ACP · ${b}`})}),o.jsx(wn,{className:"max-h-72 min-w-[18rem]",children:["kimi","claude","codex"].map(N=>o.jsx(bt,{onClick:()=>{p(N),!(x.executionType==="acp"&&x.agentType===N)&&a({executionMode:"acp",agentType:N})},children:`ACP · ${N}`},N))})]}):o.jsx("div",{className:"text-xs text-muted-foreground",children:u})]}),o.jsxs("div",{className:"space-y-1 text-sm",children:[o.jsx(lu,{value:O}),o.jsx(lu,{value:String(t.host||"-")}),o.jsx(lu,{value:t.port?String(t.port):"-"}),o.jsx(lu,{value:P})]}),o.jsxs("div",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[o.jsx("span",{className:"size-1.5 rounded-full bg-muted-foreground/45"}),o.jsx("span",{children:"stopped"})]})]})]})}const Dj=c.createContext(null),Da={confirmText:"确认",cancelText:"取消",confirmVariant:"default"};function qz(e){const{children:t}=e,[n,s]=c.useState(null),r=c.useCallback(h=>{s(x=>x&&(x.resolve(h),null))},[]);c.useEffect(()=>()=>{s(h=>(h&&h.resolve(!1),null))},[]);const a=c.useCallback(h=>{const x=String(h.title||"").trim(),y={...h,title:x||"请确认操作",confirmText:String(h.confirmText||"").trim()||Da.confirmText,cancelText:String(h.cancelText||"").trim()||Da.cancelText,confirmVariant:h.confirmVariant||Da.confirmVariant};return new Promise(w=>{s(b=>(b&&b.resolve(!1),{options:y,resolve:w}))})},[]),i=c.useMemo(()=>({confirm:a}),[a]),l=n==null?void 0:n.options,u=!!n,d=String((l==null?void 0:l.confirmText)||Da.confirmText),f=String((l==null?void 0:l.cancelText)||Da.cancelText),g=(l==null?void 0:l.confirmVariant)||Da.confirmVariant,m=String((l==null?void 0:l.description)||"").trim();return o.jsxs(Dj.Provider,{value:i,children:[t,o.jsx($n,{open:u,onOpenChange:h=>{h||r(!1)},children:o.jsxs(Un,{showCloseButton:!1,className:"w-[min(92vw,30rem)] p-0",children:[o.jsxs(Hn,{className:"px-4 py-4",children:[o.jsx(Fn,{children:(l==null?void 0:l.title)||"请确认操作"}),m?o.jsx(os,{children:m}):null]}),o.jsxs(rs,{className:"bg-secondary px-4 py-3",children:[o.jsx(be,{type:"button",variant:"outline",onClick:()=>{r(!1)},children:f}),o.jsx(be,{type:"button",variant:g,onClick:()=>{r(!0)},children:d})]})]})})]})}function Ls(){const e=c.useContext(Dj);if(!e)throw new Error("useConfirmDialog must be used within <ConfirmDialogProvider>.");return e.confirm}const p0="role",_j=new Set(["default"]),x0=["default","member","admin"];function Mt(e){return String(e||"").trim()}function Lj(e){return Mt(e).toLowerCase().replace(/\s+/g,"-")}function vx(e){const t=e&&typeof e=="object"?e:{},n={};for(const[s,r]of Object.entries(t)){const a=Lj((r==null?void 0:r.roleId)||s);a&&(n[a]={roleId:a,name:Mt(r==null?void 0:r.name)||a,...Mt(r==null?void 0:r.description)?{description:Mt(r==null?void 0:r.description)}:{},permissions:[...new Set(((r==null?void 0:r.permissions)||[]).filter(Boolean))]})}return n}function Gz(e){return(Array.isArray(e==null?void 0:e.channels)?e.channels:[]).map(t=>Mt(t).toLowerCase()).filter(Boolean).filter((t,n,s)=>s.indexOf(t)===n)}function Vz(e){const t=(Array.isArray(e==null?void 0:e.permissions)?e.permissions:[]).map(r=>Mt(r)).filter(Boolean).filter((r,a,i)=>i.indexOf(r)===a),n=e!=null&&e.permissionLabels&&typeof e.permissionLabels=="object"?e.permissionLabels:{},s=e!=null&&e.permissionMeta&&typeof e.permissionMeta=="object"?e.permissionMeta:{};return t.map(r=>{const a=s[r];return{permission:r,name:Mt(a==null?void 0:a.name)||Mt(n[r])||r,description:Mt(a==null?void 0:a.description)}})}function Lg(e,t){return{roles:vx(e==null?void 0:e.roles),channels:t.reduce((n,s)=>(n[s]=JSON.parse(JSON.stringify(((e==null?void 0:e.channels)||{})[s]||{})),n),{})}}function zd(e,t){return e.channels[t]||{}}function Yz(e,t,n){return{...e,channels:{...e.channels,[t]:{...zd(e,t),...n}}}}function Kz(e){return Object.values(vx(e.roles)).sort((t,n)=>{const s=x0.indexOf(t.roleId),r=x0.indexOf(n.roleId);return s>=0||r>=0?s===-1?1:r===-1?-1:s-r:t.name.localeCompare(n.name)})}function Bj(e,t){var s;return Mt((s=t==null?void 0:t.userRoles)==null?void 0:s[e.userId])||Mt(t==null?void 0:t.defaultUserRoleId)||"default"}function Xz(e,t){var s;return Mt((s=t==null?void 0:t.userRoles)==null?void 0:s[e.userId])||void 0}function b0(e,t){return Array.isArray(e==null?void 0:e.permissions)&&e.permissions.includes(t)}function Zz(e){const t=Mt(e.chatType).toLowerCase();return t!==""&&t!=="private"&&t!=="p2p"&&t!=="c2c"}function dh(e,t){return t.includes(e)}function y0(e,t){const n=t.reduce((s,r)=>{const a=zd(e,r);return s[r]={defaultUserRoleId:Mt(a.defaultUserRoleId)||"default",userRoles:{...a.userRoles||{}}},s},{});return{roles:vx(e.roles),channels:n}}function Jz(e){var s;let t=0,n=0;for(const r of e.authorizationChannels)(Mt((s=e.channels[r])==null?void 0:s.defaultUserRoleId)||"default")===e.roleId&&(n+=1);for(const r of e.users){const a=Mt(r.channel).toLowerCase();if(!dh(a,e.authorizationChannels))continue;const i=e.channels[a];Bj(r,i)===e.roleId&&(t+=1)}return{users:t,defaults:n}}function Qz(e){return e==="telegram"?"border-sky-500/20 bg-sky-500/8 text-sky-700":e==="feishu"?"border-blue-500/20 bg-blue-500/8 text-blue-700":e==="consoleui"?"border-zinc-500/20 bg-zinc-500/8 text-zinc-700":"border-emerald-500/20 bg-emerald-500/8 text-emerald-700"}function Wz(e,t){return t?e.map(s=>Mt(s).toLowerCase()).join(" ").includes(t):!0}function fh(e){return!_j.has(e)}function eI(e,t){var n;return((n=t.find(s=>s.roleId===e))==null?void 0:n.name)||e}function tI(e,t){if(!fh(t))return e;const n={...e.roles};delete n[t];const s=Object.fromEntries(Object.entries(e.channels).map(([r,a])=>{const i=a||{},l=Object.fromEntries(Object.entries(i.userRoles||{}).filter(([,u])=>u!==t));return[r,{...i,defaultUserRoleId:Mt(i.defaultUserRoleId)===t?"default":Mt(i.defaultUserRoleId)||"default",userRoles:l}]}));return{roles:n,channels:s}}function nI(e,t){const n=Lj(e);if(n&&!t.some(r=>r.roleId===n))return n;let s=t.length+1;for(;t.some(r=>r.roleId===`${p0}-${s}`);)s+=1;return`${p0}-${s}`}function cu(e){return o.jsxs("div",{className:Me("inline-flex min-w-[7.5rem] items-center gap-2 rounded-full border px-3 py-1.5",e.tone==="success"?"border-emerald-500/20 bg-emerald-500/8 text-emerald-700":"border-border/70 bg-secondary/60 text-foreground"),children:[e.icon?o.jsx("span",{className:"text-muted-foreground",children:e.icon}):null,o.jsx("span",{className:"text-[10px] uppercase tracking-[0.12em] text-muted-foreground",children:e.label}),o.jsx("span",{className:"ml-auto text-sm font-semibold",children:e.value})]})}function v0(e){return o.jsx("span",{className:Me("inline-flex h-5 items-center rounded-full border px-2 text-[10px]",Qz(e.channel)),children:e.channel})}function sI(e){const{authorization:t,selectedAgent:n,formatTime:s,onRefresh:r,onSaveConfig:a,onRunAction:i}=e,l=Ls(),u=c.useMemo(()=>t==null?void 0:t.catalog,[t==null?void 0:t.catalog]),d=c.useMemo(()=>Gz(u),[u]),f=c.useMemo(()=>Vz(u),[u]),[g,m]=c.useState(()=>Lg(void 0,[])),[h,x]=c.useState(!1),[y,w]=c.useState(!1),[b,p]=c.useState("roles"),[v,S]=c.useState(""),[j,C]=c.useState("all"),[A,M]=c.useState("");c.useEffect(()=>{m(Lg(t==null?void 0:t.config,d))},[t==null?void 0:t.config,d]);const O=c.useMemo(()=>Array.isArray(t==null?void 0:t.users)?t.users:[],[t==null?void 0:t.users]),P=c.useMemo(()=>Array.isArray(t==null?void 0:t.chats)?t.chats:[],[t==null?void 0:t.chats]),$=c.useMemo(()=>Kz(g),[g]),z=c.useMemo(()=>y0(g,d),[d,g]),N=c.useMemo(()=>y0(Lg(t==null?void 0:t.config,d),d),[t==null?void 0:t.config,d]),H=c.useMemo(()=>JSON.stringify(z)!==JSON.stringify(N),[z,N]),R=c.useMemo(()=>P.filter(Zz).length,[P]),I=c.useMemo(()=>{const k=Mt(A).toLowerCase();return O.filter(D=>{const B=Mt(D.channel).toLowerCase();return!dh(B,d)||j!=="all"&&B!==j?!1:Wz([D.username,D.userId,D.lastChatId,D.lastChatTitle,D.lastChatType],k)})},[d,j,O,A]),T=c.useCallback(async()=>{try{x(!0),await a(z)}finally{x(!1)}},[z,a]),E=c.useCallback(()=>{const k=nI(v,$);m(D=>({...D,roles:{...D.roles,[k]:{roleId:k,name:Mt(v)||"New Role",description:"",permissions:[]}}})),S("")},[v,$]),q=c.useCallback(async k=>{!fh(k.roleId)||!await l({title:`删除角色 ${k.name}`,description:"删除后会回退到 default。",confirmText:"删除",confirmVariant:"destructive"})||m(B=>tI(B,k.roleId))},[l]);return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Authorization",description:Mt((n==null?void 0:n.agentId)||(n==null?void 0:n.id)||"未选择"),bodyClassName:"space-y-2.5",actions:o.jsxs(o.Fragment,{children:[o.jsxs(be,{type:"button",size:"sm",variant:"ghost",className:"rounded-[10px]",onClick:()=>void r(),children:[o.jsx(xc,{className:"mr-1 size-4"}),"Refresh"]}),o.jsx(be,{type:"button",size:"sm",className:"rounded-[10px]",disabled:h||!H,onClick:()=>void T(),children:h?"Saving":"Save"})]}),children:o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(cu,{label:"Roles",value:$.length,icon:o.jsx(Tw,{className:"size-3.5"})}),o.jsx(cu,{label:"Users",value:O.length,icon:o.jsx(Q5,{className:"size-3.5"})}),o.jsx(cu,{label:"Groups",value:R,icon:o.jsx(v5,{className:"size-3.5"})}),o.jsx(cu,{label:"Draft",value:H?"Pending":"Synced",tone:H?"default":"success",icon:o.jsx(q5,{className:"size-3.5"})}),o.jsxs(be,{type:"button",size:"sm",className:"ml-auto rounded-[10px]",onClick:()=>{p("roles"),w(!0)},children:[o.jsx(pd,{className:"mr-1 size-4"}),"Policy"]})]})}),o.jsxs(wt,{title:"Directory",description:"Users",bodyClassName:"space-y-2.5",children:[o.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between",children:[o.jsxs("div",{className:"relative min-w-[14rem]",children:[o.jsx(Wl,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{className:"h-9 rounded-[12px] bg-secondary/70 pl-9",value:A,onChange:k=>M(k.target.value),placeholder:"search user / chat / id"})]}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:["all",...d].map(k=>o.jsx(be,{type:"button",size:"sm",variant:"ghost",className:Me("rounded-[10px]",k===j?"bg-secondary":""),onClick:()=>C(k),children:k},`channel-filter:${k}`))})]}),o.jsx(x6,{className:"bg-border/70"}),I.length===0?o.jsx("div",{className:"rounded-[12px] bg-secondary/40 px-3 py-5 text-sm text-muted-foreground",children:"没有匹配的用户。"}):o.jsx("div",{className:"space-y-1.5",children:I.map(k=>{const D=Mt(k.channel).toLowerCase();if(!dh(D,d))return null;const B=zd(g,D),Q=Bj(k,B),Z=Xz(k,B),te=$.find(se=>se.roleId===Q);return o.jsx("article",{className:"rounded-[12px] border border-border/60 bg-secondary/25 px-3 py-2",children:o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0 flex-1 space-y-0.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:k.username||k.userId}),o.jsx(v0,{channel:D}),o.jsx(An,{variant:"secondary",className:"h-5 rounded-full px-1.5 text-[10px]",children:Z?"custom":"default"}),b0(te,"agent.manage")?o.jsx(An,{className:"h-5 rounded-full bg-emerald-600 px-1.5 text-[10px] text-white",children:"admin"}):null]}),o.jsx("div",{className:"font-mono text-[11px] text-muted-foreground",children:k.userId}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:`${k.lastChatTitle||k.lastChatId||"-"} · ${k.lastChatType||"-"} · ${s(k.lastSeenAt)}`})]}),o.jsx("select",{className:"h-9 min-w-[10.5rem] rounded-[10px] border border-transparent bg-background/90 px-3 text-sm outline-none transition focus-visible:ring-3 focus-visible:ring-ring/30",value:Q,onChange:se=>{i({action:"setUserRole",channel:D,userId:k.userId,roleId:se.target.value})},children:$.map(se=>o.jsx("option",{value:se.roleId,children:se.name},`${D}:user:${k.userId}:${se.roleId}`))})]})},`${k.channel}:${k.userId}`)})})]}),o.jsx($n,{open:y,onOpenChange:w,children:o.jsxs(Un,{className:"w-[min(96vw,920px)] p-0",children:[o.jsxs(Hn,{className:"border-b border-border/70 bg-secondary/35 px-4 py-3",children:[o.jsx(Fn,{children:"Policy"}),o.jsx(os,{className:"sr-only",children:"Authorization policy editor"})]}),o.jsxs(k6,{value:b,onValueChange:k=>p(k),className:"gap-0",children:[o.jsx("div",{className:"border-b border-border/70 px-4 py-2",children:o.jsxs(T6,{className:"rounded-[10px] bg-secondary/70 p-0.5",children:[o.jsx(e0,{value:"roles",className:"rounded-[8px] px-2.5 text-xs",children:"Roles"}),o.jsx(e0,{value:"defaults",className:"rounded-[8px] px-2.5 text-xs",children:"Defaults"})]})}),o.jsx(t0,{value:"roles",className:"max-h-[72vh] overflow-y-auto p-4",children:o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx(lt,{value:v,onChange:k=>S(k.target.value),placeholder:"new role id",className:"h-9 rounded-[12px] bg-secondary/70"}),o.jsx(be,{type:"button",size:"sm",className:"rounded-[10px] px-3",onClick:E,children:o.jsx(fa,{className:"size-4"})})]}),o.jsx(Jr,{children:o.jsx("div",{className:"space-y-2",children:$.map(k=>{const D=Jz({roleId:k.roleId,channels:g.channels,authorizationChannels:d,users:O});return o.jsxs("article",{className:"rounded-[12px] border border-border/70 bg-background/85 px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(lt,{value:k.name,className:"h-8 min-w-[10rem] flex-1 rounded-[10px] bg-secondary/60",onChange:B=>{const Q=B.target.value;m(Z=>({...Z,roles:{...Z.roles,[k.roleId]:{...Z.roles[k.roleId]||k,name:Q}}}))}}),o.jsx(An,{variant:"outline",className:"bg-background/90 font-mono text-[10px]",children:k.roleId}),o.jsx(An,{variant:"secondary",className:"bg-secondary text-[10px] text-muted-foreground",children:`${D.users}/${D.defaults}`}),_j.has(k.roleId)?o.jsx(An,{variant:"outline",className:"h-5 rounded-full px-1.5 text-[10px]",children:"reserved"}):null,o.jsx(be,{type:"button",variant:"ghost",size:"sm",className:"ml-auto rounded-[8px] px-2 text-destructive hover:bg-destructive/8 hover:text-destructive",disabled:!fh(k.roleId),onClick:()=>void q(k),children:o.jsx(er,{className:"size-4"})})]}),o.jsx("div",{className:"mt-2",children:o.jsx(lt,{value:k.description||"",className:"h-8 rounded-[10px] bg-secondary/60",onChange:B=>{const Q=B.target.value;m(Z=>({...Z,roles:{...Z.roles,[k.roleId]:{...Z.roles[k.roleId]||k,description:Q}}}))},placeholder:"description"})}),o.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:f.map(B=>{const Q=b0(k,B.permission);return o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:Me("inline-flex h-7 items-center rounded-[9px] border px-2 text-[11px] font-medium transition",Q?"border-foreground/10 bg-foreground text-background":"border-border/70 bg-background text-muted-foreground hover:bg-secondary/45 hover:text-foreground"),onClick:()=>{m(Z=>{const te=Z.roles[k.roleId]||k,se=new Set(te.permissions||[]);return se.has(B.permission)?se.delete(B.permission):se.add(B.permission),{...Z,roles:{...Z.roles,[k.roleId]:{...te,permissions:[...se]}}}})},children:B.name})}),B.description?o.jsx(eo,{children:B.description}):null]},`${k.roleId}:${B.permission}`)})})]},`role-card:${k.roleId}`)})})})]})}),o.jsx(t0,{value:"defaults",className:"max-h-[72vh] overflow-y-auto p-4",children:o.jsx("div",{className:"space-y-1.5",children:d.map(k=>{const D=zd(g,k),B=Mt(D.defaultUserRoleId)||"default",Q=$.find(Z=>Z.roleId===B);return o.jsx("article",{className:"rounded-[12px] border border-border/70 bg-secondary/28 px-3 py-2",children:o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(v0,{channel:k}),o.jsx("div",{className:"text-sm font-medium text-foreground",children:(Q==null?void 0:Q.name)||eI(B,$)})]}),o.jsx("select",{className:"h-8 min-w-[12rem] rounded-[10px] border border-transparent bg-background/90 px-3 text-sm outline-none transition focus-visible:ring-3 focus-visible:ring-ring/30",value:B,onChange:Z=>{m(te=>Yz(te,k,{defaultUserRoleId:Z.target.value}))},children:$.map(Z=>o.jsx("option",{value:Z.roleId,children:Z.name},`${k}:default-user:${Z.roleId}`))})]})},`channel-default:${k}`)})})})]}),o.jsx(rs,{className:"border-t border-border/70 bg-background px-4 py-3",children:o.jsx(be,{type:"button",variant:"outline",onClick:()=>w(!1),children:"Close"})})]})})]})}const Vn="h-8 w-8 rounded-[11px] bg-transparent text-muted-foreground hover:bg-foreground/8 hover:text-foreground",Ro="h-8 w-8 rounded-[11px] bg-transparent text-destructive hover:bg-foreground/8 hover:text-destructive",rI=new Set(["init","start","stop","console","agent","service","plugin","chat","skill","task","memory","asr","tts"]),gh=[{label:"Console",items:[{label:"Version",command:"-v",description:"查看 CLI 版本"},{label:"Start DC",command:"start",description:"启动 console 与 console ui"},{label:"Stop DC",command:"stop",description:"停止 console(含 agent)"},{label:"Console Status",command:"console status",description:"查看 console 与托管 agent 状态"},{label:"Console Agents",command:"console agents",description:"查看 console 托管 agent 列表"},{label:"UI Status",command:"console ui status",description:"查看 console UI 运行状态"},{label:"UI Restart",command:"console ui restart",description:"重启 console UI"}]},{label:"Agent",items:[{label:"Agent Create",command:"agent create .",description:"初始化当前目录为 agent 项目"},{label:"Agent Status",command:"agent status",description:"查看当前项目 agent 状态"},{label:"Agent Start",command:"agent start",description:"启动当前项目 agent"},{label:"Agent Foreground",command:"agent start --foreground",description:"以前台模式运行当前 agent"},{label:"Agent Restart",command:"agent restart",description:"重启当前项目 agent"},{label:"Agent Doctor",command:"agent doctor",description:"诊断并修复 daemon 状态文件"},{label:"Agent Doctor Fix",command:"agent doctor --fix",description:"自动清理僵尸 pid/meta"}]},{label:"Config & Model",items:[{label:"Config Get",command:"console config get",description:"读取当前 downcity.json 配置"},{label:"Config Primary",command:"console config get model.primary",description:"读取当前项目主模型绑定"},{label:"Config Alias",command:"console config alias --print",description:"打印 alias city 配置片段"},{label:"Model List",command:"console model list",description:"列出 provider 与模型池"},{label:"Model Create",command:"console model create",description:"交互式创建 provider 或 model"},{label:"Model Discover",command:"console model discover <providerId>",description:"探测 provider 可用模型"},{label:"Model Use",command:"console model use <modelId>",description:"绑定当前项目 model.primary"},{label:"Model Test",command:"console model test provider <providerId>",description:"测试 provider 连通性"}]},{label:"Service",items:[{label:"Service List",command:"service list",description:"列出 service 运行状态"},{label:"Service Chat",command:"service status chat",description:"查看 chat service 状态"},{label:"Service Task",command:"service status task",description:"查看 task service 状态"},{label:"Service Memory",command:"service status memory",description:"查看 memory service 状态"},{label:"Service Restart",command:"service restart chat",description:"重启 chat service"},{label:"Task Reload",command:"service command task reload",description:"触发 task scheduler 重载"}]},{label:"Chat",items:[{label:"Chat Status",command:"chat status",description:"查看 chat 渠道连接状态"},{label:"Chat Test",command:"chat test",description:"测试 chat 渠道连通性"},{label:"Chat Reconnect",command:"chat reconnect",description:"重连 chat 渠道"},{label:"Chat Context",command:"chat context",description:"查看当前会话上下文快照"},{label:"Chat History",command:"chat history --limit 30",description:"读取最近聊天历史"},{label:"Chat Send",command:'chat send --text "hello from city"',description:"向当前 chatKey 发送消息"}]},{label:"Task & Memory",items:[{label:"Task List",command:"task list",description:"列出任务定义"},{label:"Task Enabled",command:"task list --status enabled",description:"仅查看启用任务"},{label:"Task Run",command:'task run "<taskTitle>"',description:"手动执行指定任务"},{label:"Task Enable",command:'task enable "<taskTitle>"',description:"启用指定任务"},{label:"Task Disable",command:'task disable "<taskTitle>"',description:"禁用指定任务"},{label:"Memory Status",command:"memory status",description:"查看 memory backend 状态"},{label:"Memory Index",command:"memory index --force",description:"重建 memory 索引"},{label:"Memory Search",command:'memory search "<query>"',description:"检索记忆片段"}]},{label:"Skill / ASR / TTS",items:[{label:"Skill List",command:"skill list",description:"列出当前已学会 skills"},{label:"Skill Find",command:'skill find "<query>"',description:"查找缺失技能"},{label:"Skill Lookup",command:'skill lookup "<skillName>"',description:"读取技能 SKILL.md 内容"},{label:"ASR Models",command:"asr models",description:"列出内置语音识别模型目录"},{label:"Plugin List",command:"plugin list",description:"列出当前 agent 的 plugins"},{label:"ASR Status",command:"asr status",description:"查看 asr plugin 配置"},{label:"ASR On",command:"asr on SenseVoiceSmall",description:"启用 asr 并安装默认模型"},{label:"ASR Use",command:"asr use SenseVoiceSmall",description:"切换 active 语音识别模型"},{label:"ASR Off",command:"asr off",description:"关闭 asr plugin"},{label:"TTS Status",command:"tts status",description:"查看 tts plugin 配置"},{label:"TTS On",command:"tts on",description:"启用 tts plugin"},{label:"TTS Synthesize",command:'tts synthesize "hello from city"',description:"生成可发送的语音文件"}]}],oI=gh.flatMap(e=>e.items.map(t=>t.command));function w0(e){const{selectedAgentId:t,selectedAgentProjectId:n,agents:s=[],onSelectAgent:r,persistSelectionInUrl:a=!0,onExecute:i}=e,l=Ls(),[u,d]=c.useState(""),[f,g]=c.useState(""),[m,h]=c.useState(!1),[x,y]=c.useState([]),[w,b]=c.useState([]),[p,v]=c.useState(""),S=c.useRef(null),j=c.useRef(null),C=c.useRef(-1),A=c.useRef(""),M=c.useCallback(()=>{var te,se;const D=s.map(ie=>({id:String(ie.id||"").trim(),running:ie.running===!0})).filter(ie=>ie.id);if(D.length===0)return"";const B=(()=>{var oe;if(!a||typeof window>"u")return"";const ie=String(new URLSearchParams(window.location.search).get("agent")||"").trim();return ie&&((oe=D.find(pe=>pe.id===ie))==null?void 0:oe.id)||""})();if(B)return B;const Q=String(t||"").trim();if(Q&&D.some(ie=>ie.id===Q))return Q;const Z=((te=D.find(ie=>ie.running))==null?void 0:te.id)||"";return Z||((se=D[0])==null?void 0:se.id)||""},[s,a,t]);c.useEffect(()=>{const D=M();d(B=>B&&s.some(Q=>String(Q.id||"").trim()===B)?B:D)},[s,M]),c.useEffect(()=>{if(!a||typeof window>"u")return;const D=new URL(window.location.href),B=String(D.searchParams.get("agent")||"").trim();if(!u){if(!B)return;D.searchParams.delete("agent"),window.history.replaceState({},"",`${D.pathname}${D.search}${D.hash}`);return}B!==u&&(D.searchParams.set("agent",u),window.history.replaceState({},"",`${D.pathname}${D.search}${D.hash}`))},[u,a]);const O=c.useMemo(()=>s.find(D=>String(D.id||"")===u)??null,[u,s]),P=String((O==null?void 0:O.agentId)||n||u||"agent").trim()||"agent",$=c.useCallback(D=>{const B=String(D||"").trim();if(!B)return"";if(/^(?:city|downcity)(?:\s|$)/i.test(B))return B;const Q=String(B.split(/\s+/,1)[0]||"").trim().toLowerCase();return Q?Q.startsWith("-")||rI.has(Q)?`city ${B}`:B:""},[]),z=c.useCallback(D=>D.timedOut?{label:"timeout",badgeClassName:"bg-amber-500/12 text-amber-700 dark:text-amber-300",rowClassName:"border-amber-500/35"}:!!String(D.stderr||"").trim()||Number(D.exitCode??0)!==0?{label:"error",badgeClassName:"bg-destructive/10 text-destructive",rowClassName:"border-destructive/40"}:{label:"success",badgeClassName:"bg-emerald-500/12 text-emerald-700 dark:text-emerald-300",rowClassName:"border-emerald-500/35"},[]),N=c.useCallback(D=>{const B=String(D||"").trim();B&&(b(Q=>{const te=[...Q.filter(se=>se!==B),B];return te.length<=120?te:te.slice(te.length-120)}),C.current=-1,A.current="")},[]),H=c.useCallback(D=>{C.current=-1,A.current="",g(D)},[]),R=c.useCallback(D=>{if(w.length!==0){if(D==="up"){C.current===-1?(A.current=f,C.current=w.length-1):C.current=Math.max(0,C.current-1),g(w[C.current]||"");return}if(C.current!==-1){if(C.current>=w.length-1){C.current=-1,g(A.current);return}C.current+=1,g(w[C.current]||"")}}},[f,w]),I=c.useMemo(()=>{const D=[],B=new Set;for(let Q=w.length-1;Q>=0;Q-=1){const Z=String(w[Q]||"").trim();!Z||B.has(Z)||(B.add(Z),D.push(Z))}for(const Q of[...oI,"clear","cls"]){const Z=String(Q||"").trim();!Z||B.has(Z)||(B.add(Z),D.push(Z))}return D},[w]),T=c.useMemo(()=>{const D=String(f||"");if(!D.trim())return"";const B=D.toLowerCase();return I.find(Z=>{const te=Z.toLowerCase();return te===B?!1:te.startsWith(B)})||""},[f,I]),E=c.useMemo(()=>T?T.slice(f.length):"",[f,T]),q=c.useCallback(D=>{var ie,oe;if(!T||!E)return!1;if(D==="full")return g(T),!0;const B=((ie=E.match(/^\s*/))==null?void 0:ie[0])||"",Q=E.slice(B.length);if(!Q)return g(T),!0;const Z=Q.match(/^[^\s]+/),te=Z?Z[0]:Q,se=((oe=Q.slice(te.length).match(/^\s*/))==null?void 0:oe[0])||"";return g(pe=>`${pe}${B}${te}${se}`),!0},[T,E]),k=c.useCallback(async D=>{const B=String(D||"").trim(),Q=B.toLowerCase();if(Q==="clear"||Q==="cls"){y([]),v(""),g("");return}const Z=$(D);if(!(!Z||m||!u)){N(B),h(!0),v("");try{const te=await i({command:Z,timeoutMs:45e3,agentId:u});y(se=>[...se,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,result:te}]),g("")}catch(te){v(te instanceof Error?te.message:String(te))}finally{h(!1)}}},[u,i,N,$,m]);return c.useEffect(()=>{var D;(D=S.current)==null||D.scrollTo({top:S.current.scrollHeight,behavior:"smooth"})},[x.length,m]),o.jsxs(wt,{title:"Command",description:"在当前 agent 上直接执行命令,输出按会话顺序保留。",className:"flex h-full min-h-0 flex-1 flex-col overflow-hidden",bodyClassName:"flex min-h-0 flex-1 flex-col",actions:o.jsxs(o.Fragment,{children:[s.length>0?o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{variant:"outline",size:"sm",className:"h-8 gap-2 rounded-[11px] px-2.5 text-[12px] font-normal"}),children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",O!=null&&O.running?"bg-emerald-500":"bg-muted-foreground/40")}),o.jsx("span",{className:"max-w-[12rem] truncate",children:P}),o.jsx(XA,{className:"size-3.5 text-muted-foreground"})]}),o.jsx(wn,{align:"start",className:"w-56",children:o.jsxs(ih,{children:[o.jsx(lh,{className:"text-[11px] uppercase tracking-[0.1em] text-muted-foreground",children:"选择 agent"}),o.jsx(Md,{}),s.map(D=>{const B=String(D.id||"").trim();if(!B)return null;const Q=B===u;return o.jsxs(bt,{onClick:()=>{d(B),r==null||r(B)},className:"justify-between gap-2 text-[12px]",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2 truncate",children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",D.running?"bg-emerald-500":"bg-muted-foreground/40")}),o.jsx("span",{className:"truncate",children:D.agentId||B})]}),Q?o.jsx(Ws,{className:"size-3.5 shrink-0 text-primary"}):null]},B)})]})})]}):o.jsxs("div",{className:"inline-flex h-8 items-center gap-2 rounded-[11px] border border-border bg-transparent px-2.5 text-[12px] text-muted-foreground",children:[o.jsx("span",{className:"inline-flex size-1.5 rounded-full bg-muted-foreground/40"}),"未选择 agent"]}),o.jsx(be,{size:"icon",variant:"ghost",onClick:()=>{(async()=>await l({title:"清空输出",description:"确认清空当前命令输出记录吗?",confirmText:"清空",confirmVariant:"destructive"})&&y([]))()},disabled:m||x.length===0,className:Ro,"aria-label":"清空输出",title:"清空输出",children:o.jsx(er,{className:"size-4"})})]}),children:[o.jsx("div",{className:"min-h-0 flex-1 rounded-[20px] bg-secondary p-2",children:o.jsxs("div",{ref:S,className:"h-full overflow-auto rounded-[18px] px-3 py-3 font-mono text-[12px] leading-relaxed text-foreground/92",children:[x.length===0?o.jsxs("div",{className:"text-muted-foreground",children:[`# 当前 agent: ${P}`,o.jsx("br",{}),"# 输入命令并执行,输出会记录在这里"]}):x.map(D=>{const B=`exit=${String(D.result.exitCode??"-")} · ${D.result.durationMs}ms${D.result.timedOut?" · timeout":""}`,Q=z(D.result);return o.jsxs("div",{className:`mb-4 border-l-2 pl-3 last:mb-0 ${Q.rowClassName}`,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-foreground",children:`$ ${D.result.command}`}),o.jsx("span",{className:`inline-flex rounded-[10px] px-1.5 py-0.5 text-[10px] leading-none ${Q.badgeClassName}`,children:Q.label})]}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:`${D.result.cwd} · ${B}`}),D.result.stdout?o.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words text-foreground/95",children:D.result.stdout}):null,D.result.stderr?o.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words rounded-[10px] bg-destructive/6 px-2 py-1 text-destructive",children:D.result.stderr}):null]},D.id)}),m?o.jsx("div",{className:"text-primary/80",children:`$ ${$(f)||"(running...)"}`}):null]})}),o.jsxs("div",{className:"space-y-2 rounded-[20px] bg-secondary px-3 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(yn,{children:[o.jsx(vn,{disabled:m||!u,className:`inline-flex shrink-0 items-center justify-center disabled:pointer-events-none disabled:opacity-50 ${Vn}`,"aria-label":"常用命令",title:"常用命令",children:o.jsx(Vm,{className:"size-4"})}),o.jsx(wn,{align:"start",className:"w-[24rem]",children:gh.map((D,B)=>o.jsxs(c.Fragment,{children:[o.jsxs(ih,{children:[o.jsx(lh,{className:"text-[11px] uppercase tracking-[0.1em] text-muted-foreground",children:D.label}),D.items.map(Q=>o.jsx(bt,{onClick:()=>{H(Q.command),requestAnimationFrame(()=>{var Z;return(Z=j.current)==null?void 0:Z.focus()})},className:"items-start py-2",children:o.jsxs("span",{className:"grid min-w-0 gap-0.5",children:[o.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:Q.label}),o.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:Q.command}),o.jsx("span",{className:"truncate text-[11px] text-muted-foreground/90",children:Q.description})]})},`${D.label}:${Q.command}`))]}),B<gh.length-1?o.jsx(Md,{}):null]},D.label))})]}),o.jsxs("div",{className:"relative flex h-9 flex-1 items-center rounded-[14px] bg-background px-3",children:[o.jsx("span",{className:"mr-2 font-mono text-xs text-muted-foreground",children:"$"}),o.jsxs("div",{className:"relative flex-1",children:[E?o.jsxs("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 z-0 flex h-8 items-center overflow-hidden font-mono text-[12px]",children:[o.jsx("span",{className:"invisible whitespace-pre",children:f}),o.jsx("span",{className:"whitespace-pre text-muted-foreground/45",children:E})]}):null,o.jsx("input",{ref:j,value:f,onChange:D=>H(D.target.value),onKeyDown:D=>{if(D.key==="Enter"){D.preventDefault(),k(f);return}if(D.key==="Tab"){q("full")&&D.preventDefault();return}if(D.key==="ArrowRight"&&(D.ctrlKey||D.metaKey)){q("word")&&D.preventDefault();return}if(D.key==="ArrowUp"){D.preventDefault(),R("up");return}D.key==="ArrowDown"&&(D.preventDefault(),R("down"))},placeholder:"输入命令后按回车执行(CITY 命令可省略 city)",className:"relative z-10 h-8 w-full bg-transparent font-mono text-[12px] text-foreground outline-none placeholder:text-muted-foreground/80"})]})]}),o.jsx(be,{size:"sm",variant:"secondary",disabled:m||!u||!String(f||"").trim(),onClick:()=>void k(f),className:"h-9 px-3",children:"执行"})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-[11px] text-muted-foreground/80",children:[o.jsx("span",{children:"Tab 接受预测 · Ctrl/⌘ + → 接受下一个词 · ↑/↓ 浏览历史命令"}),u?null:o.jsx("span",{className:"text-destructive",children:"请先选择 agent"}),p?o.jsx("span",{className:"text-destructive",children:p}):null]})]})]})}function aI(e){const{checking:t,bootstrapRequired:n,submitting:s,errorMessage:r,onSubmit:a}=e,[i,l]=c.useState(""),u=c.useCallback(async d=>{d.preventDefault(),await a({token:i})},[a,i]);return o.jsx("div",{className:"flex min-h-screen w-full items-center justify-center bg-secondary/30 px-4",children:o.jsxs("section",{className:"w-full max-w-sm rounded-[22px] bg-background px-6 py-6 shadow-[0_1px_0_rgba(17,17,19,0.03)] ring-1 ring-border/70",children:[o.jsxs("div",{className:"mb-6",children:[o.jsx("h1",{className:"text-base font-medium text-foreground",children:t?"检查中":n?"先创建 Token":"输入 Token"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t?"验证访问权限...":n?"请先在本机终端执行 city token create":"Console UI Bearer Token"})]}),t?o.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-muted-foreground",children:[o.jsx(nt,{className:"h-4 w-4 animate-spin"}),o.jsx("span",{children:"检查认证状态"})]}):o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("label",{htmlFor:"token",className:"text-xs text-muted-foreground",children:"Bearer Token"}),o.jsx("textarea",{id:"token",value:i,onChange:d=>l(d.target.value),className:"min-h-[108px] w-full rounded-[11px] border border-input bg-transparent px-3 py-2 text-sm outline-none transition-colors focus:border-ring",disabled:s,placeholder:"支持直接粘贴 Bearer xxx 或纯 token"}),o.jsx("div",{className:"rounded-[11px] bg-secondary/50 px-3 py-2 text-xs leading-5 text-muted-foreground",children:"如何获取:在当前机器的终端执行 `city token create my-token`,或直接运行 `city token`。"})]}),n&&o.jsx("div",{className:"rounded-[11px] bg-secondary/70 px-3 py-2 text-xs text-muted-foreground",children:"先在当前机器的终端执行 `city token create my-token`,拿到 token 后再粘贴到这里。"}),r&&o.jsx("div",{className:"rounded-[11px] bg-destructive/10 px-3 py-2 text-xs text-destructive",children:r}),o.jsx(be,{type:"submit",className:"w-full",disabled:s||!i.trim(),children:s?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-2 h-4 w-4 animate-spin"}),"验证中..."]}):"进入 Console"})]})]})})}function S0(e){return e.required!==!0?null:o.jsx("span",{className:"text-destructive",children:"*"})}function Pj(e){const{field:t,value:n,onChange:s}=e;if(t.type==="select"){const r=Array.isArray(t.options)?t.options:[],a=String(n??""),i=r.find(l=>l.value===a)||r[0]||null;return o.jsxs("div",{className:"space-y-2",children:[o.jsxs(qt,{className:"text-xs text-muted-foreground",children:[t.label," ",S0(t)]}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3",disabled:t.disabled===!0}),children:[o.jsx("span",{children:(i==null?void 0:i.label)||t.placeholder||"请选择"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:r.map(l=>o.jsxs(bt,{onClick:()=>s(l.value),children:[a===l.value?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:l.label})]},`${t.key}:${l.value}`))})]}),t.description?o.jsx("div",{className:"text-[11px] leading-5 text-muted-foreground",children:t.description}):null]})}if(t.type==="boolean"){const r=n===!0;return o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:t.label}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsx("button",{type:"button",className:`h-10 rounded-[12px] border px-3 text-sm font-medium transition ${r?"border-border bg-background text-foreground":"border-transparent bg-transparent text-muted-foreground hover:border-border/60 hover:bg-background/70 hover:text-foreground"}`,disabled:t.disabled===!0,onClick:()=>s(!0),children:t.trueLabel||"是"}),o.jsx("button",{type:"button",className:`h-10 rounded-[12px] border px-3 text-sm font-medium transition ${r?"border-transparent bg-transparent text-muted-foreground hover:border-border/60 hover:bg-background/70 hover:text-foreground":"border-border bg-background text-foreground"}`,disabled:t.disabled===!0,onClick:()=>s(!1),children:t.falseLabel||"否"})]}),t.description?o.jsx("div",{className:"text-[11px] leading-5 text-muted-foreground",children:t.description}):null]})}return o.jsxs("div",{className:"space-y-2",children:[o.jsxs(qt,{className:"text-xs text-muted-foreground",children:[t.label," ",S0(t)]}),o.jsx(lt,{type:t.type==="secret"?"password":t.type==="number"?"number":"text",placeholder:t.placeholder,className:"h-10 rounded-[12px]",value:String(n??""),disabled:t.disabled===!0,onChange:r=>s(r.target.value)}),t.description?o.jsx("div",{className:"text-[11px] leading-5 text-muted-foreground",children:t.description}):null]})}const iI=[{label:"Telegram",value:"telegram"},{label:"Feishu",value:"feishu"},{label:"QQ (dev)",value:"qq"}];function lI(e){const t=String(e||"").trim();if(!t)return"-";const n=Date.parse(t);return!Number.isFinite(n)||Number.isNaN(n)?"-":new Date(n).toLocaleString("zh-CN",{hour12:!1})}function j0(){return{id:"",channel:"telegram",name:"",identity:"",owner:"",creator:"",domain:"",sandbox:!1,botToken:"",appId:"",appSecret:""}}function Xt(e){return String(e||"").trim()}function C0(e){return e.channel==="telegram"?Xt(e.botToken).length>0:Xt(e.appId).length>0&&Xt(e.appSecret).length>0}function cI(e){const{form:t,probeStatus:n}=e,s=[];return Xt(t.channel)||s.push("请选择 channel"),n!=="passed"&&s.push(n==="failed"?"测试未通过,请修复凭据后重试":"请先测试凭据并通过"),(!Xt(t.id)||!Xt(t.name))&&s.push("当前账户基础信息缺失,无法确认"),s}function k0(e){return String(e.channel||"").trim().toLowerCase()==="telegram"?e.hasBotToken===!0:e.hasAppId===!0&&e.hasAppSecret===!0}function Bg(e){return bx(e)}function uI(e){if(String(e.channel||"").trim().toLowerCase()==="telegram")return e.hasBotToken===!0?"token ready":"token missing";const n=e.hasAppId===!0,s=e.hasAppSecret===!0;return n&&s?"appId/appSecret ready":n||s?"credentials incomplete":"credentials missing"}function dI(e){return e==="telegram"?[{key:"botToken",label:"botToken",type:"secret",placeholder:"botToken",required:!0}]:e==="feishu"?[{key:"appId",label:"appId",type:"string",placeholder:"appId",required:!0},{key:"appSecret",label:"appSecret",type:"secret",placeholder:"appSecret",required:!0},{key:"domain",label:"domain",type:"string",placeholder:"domain(可选)"}]:e==="qq"?[{key:"appId",label:"appId",type:"string",placeholder:"appId",required:!0},{key:"appSecret",label:"appSecret",type:"secret",placeholder:"appSecret",required:!0},{key:"sandbox",label:"运行环境",type:"boolean",trueLabel:"测试环境",falseLabel:"生产环境",description:"QQ channel 当前为 dev 版本,建议优先在测试环境验证。"}]:[]}function fI(e){const t=[],n=String(e.identity||"").trim(),s=String(e.owner||"").trim(),r=String(e.creator||"").trim(),a=String(e.domain||"").trim(),i=String(e.channel||"").trim().toLowerCase();return n&&t.push(`Bot: ${n}`),s&&t.push(`Owner: ${s}`),r&&t.push(`Creator: ${r}`),i==="feishu"&&a&&t.push(`Domain: ${a}`),i==="qq"&&t.push(`Sandbox: ${e.sandbox===!0?"on":"off"}`),t.push(`Creds: ${uI(e)}`),t.join(" · ")}function gI(e){const{items:t,loading:n,onUpsert:s,onProbe:r,onRemove:a}=e,i=Ls(),[l,u]=c.useState(!1),[d,f]=c.useState(""),[g,m]=c.useState(j0),[h,x]=c.useState(""),[y,w]=c.useState({}),[b,p]=c.useState("idle"),[v,S]=c.useState(""),j=!!h,A=c.useMemo(()=>cI({form:g,probeStatus:b}),[g,b]).length===0,M=c.useCallback(E=>!!y[E],[y]),O=c.useCallback(async(E,q)=>{w(k=>({...k,[E]:!0}));try{await q()}finally{w(k=>({...k,[E]:!1}))}},[]),P=t.filter(E=>k0(E)).length,$=c.useMemo(()=>dI(g.channel),[g.channel]),z=c.useMemo(()=>{const E=d.trim().toLowerCase();return E?t.filter(q=>{const k=String(q.id||"").toLowerCase(),D=String(q.name||"").toLowerCase(),B=String(q.channel||"").toLowerCase();return k.includes(E)||D.includes(E)||B.includes(E)}):t},[t,d]),N=()=>{x(""),m(j0()),p("idle"),S(""),u(!0)},H=E=>{x(String(E.id||"").trim()),m({id:String(E.id||"").trim(),channel:String(E.channel||"telegram").trim().toLowerCase()||"telegram",name:String(E.name||"").trim(),identity:String(E.identity||"").trim(),owner:String(E.owner||"").trim(),creator:String(E.creator||"").trim(),domain:String(E.domain||"").trim(),sandbox:E.sandbox===!0,botToken:"",appId:"",appSecret:""}),p("idle"),S(""),u(!0)},R=()=>{u(!1)},I=async()=>{if(!C0(g))return;p("idle"),S("");const E=await r({channel:g.channel,botToken:Xt(g.botToken)||void 0,appId:Xt(g.appId)||void 0,appSecret:Xt(g.appSecret)||void 0,domain:Xt(g.domain)||void 0,sandbox:g.sandbox});if(!E){p("failed"),S("测试失败");return}p("passed"),S(String(E.message||"").trim()||"测试通过"),m(q=>({...q,id:j?q.id:String(E.accountId||"").trim()||q.id,name:String(E.name||"").trim()||q.name,identity:q.identity.trim()||String(E.identity||"").trim(),owner:q.owner.trim()||String(E.owner||"").trim(),creator:q.creator.trim()||String(E.creator||"").trim()}))},T=async()=>{A&&(await Promise.resolve(s({id:Xt(g.id),channel:Xt(g.channel),name:Xt(g.name),identity:Xt(g.identity)||void 0,owner:Xt(g.owner)||void 0,creator:Xt(g.creator)||void 0,domain:Xt(g.domain)||void 0,sandbox:g.sandbox,botToken:Xt(g.botToken)||void 0,appId:Xt(g.appId)||void 0,appSecret:Xt(g.appSecret)||void 0})),u(!1))};return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Channel Accounts",description:`已配置 ${t.length} 个,凭据完整 ${P} 个`,actions:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:`ready ${P}/${t.length}`}),o.jsx(lt,{value:d,onChange:E=>f(E.target.value),placeholder:"搜索账号",className:"w-[220px]"}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:N,disabled:n,"aria-label":"新建账号",title:"新建账号",children:o.jsx(fa,{className:"size-4"})})]}),children:z.length===0?o.jsx("div",{className:"rounded-[20px] bg-secondary/85 py-6 text-center text-sm text-muted-foreground",children:"暂无 channel account"}):o.jsx("div",{className:"space-y-2.5",children:z.map(E=>{const q=String(E.id||"").trim();if(!q)return null;const k=k0(E),D=fI(E),B=`${q}${D?` · ${D}`:""}`;return o.jsxs("div",{className:"group flex items-center gap-3 rounded-[18px] bg-transparent px-3.5 py-3 transition-colors hover:bg-secondary",children:[o.jsx("div",{className:`h-2.5 w-2.5 shrink-0 rounded-full ${k?"bg-emerald-500":"bg-zinc-400"}`}),o.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:E.name||q}),o.jsx(An,{variant:"secondary",className:"h-5 rounded-[10px] border-border/60 bg-secondary px-1.5 text-[11px] font-medium text-muted-foreground",children:Bg(E.channel||"")})]}),o.jsx("div",{className:"truncate text-xs text-muted-foreground/90",title:B,children:B})]}),o.jsx("div",{className:"hidden text-xs text-muted-foreground md:block",children:lI(E.updatedAt)}),o.jsxs("div",{className:"inline-flex items-center gap-1",children:[o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:()=>H(E),title:"编辑","aria-label":"编辑",children:o.jsx(hd,{className:"size-3.5"})}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Ro,onClick:()=>{(async()=>await i({title:"删除 Channel Account",description:`确认删除账号「${E.name||q}」吗?该操作不可恢复。`,confirmText:"删除",confirmVariant:"destructive"})&&await O(`bot:remove:${q}`,async()=>{await Promise.resolve(a(q))}))()},disabled:M(`bot:remove:${q}`),title:"删除","aria-label":"删除",children:M(`bot:remove:${q}`)?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(er,{className:"size-3.5"})})]})]},q)})})}),o.jsx($n,{open:l,onOpenChange:E=>E?u(!0):R(),children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:j?"编辑 Channel Account":"新建 Channel Account"}),o.jsx(os,{children:"填写必要凭据,先测试,通过后确认。"})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-4 overflow-y-auto px-4 pb-2",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Channel"}),j?o.jsx("div",{className:"rounded-[16px] bg-secondary px-3 py-2.5 text-sm text-foreground",children:Bg(g.channel)}):o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:Bg(g.channel)}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:iI.map(E=>o.jsxs(bt,{onClick:()=>{const q=String(E.value||"").trim()||"telegram";m(k=>({...k,channel:q,id:"",name:"",identity:"",owner:"",creator:"",botToken:"",appId:"",appSecret:"",domain:"",sandbox:!1})),p("idle"),S("")},children:[g.channel===E.value?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:E.label})]},E.value))})]})]}),o.jsxs("div",{className:"space-y-2.5 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Credentials"}),o.jsx("div",{className:`grid gap-2 ${g.channel==="telegram"?"":"md:grid-cols-2"}`,children:$.map(E=>{const q=E.key==="sandbox"?g.sandbox:String(g[E.key]||""),k=E.key==="sandbox"||E.key==="domain";return o.jsx("div",{className:k?"md:col-span-2":"",children:o.jsx(Pj,{field:E,value:q,onChange:D=>{m(B=>({...B,[E.key]:D})),p("idle"),S("")}})},`${g.channel}:${E.key}`)})})]})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:R,children:"取消"}),o.jsxs(be,{size:"sm",variant:"secondary",className:"h-9 rounded-[12px] px-4",disabled:!C0(g)||M("bot:probe")||M("bot:confirm"),onClick:()=>{O("bot:probe",async()=>{await I()})},children:[M("bot:probe")?o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}):o.jsx(Aw,{className:"mr-1 size-3.5"}),"测试"]}),o.jsxs(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!A||M("bot:confirm"),onClick:()=>{O("bot:confirm",async()=>{await T()})},children:[M("bot:confirm")?o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}):null,"下一步:确认"]})]})]})})]})}function mI(e){const t=String(e||"").trim();if(!t)return"-";const n=Date.parse(t);return!Number.isFinite(n)||Number.isNaN(n)?"-":new Date(n).toLocaleString("zh-CN",{hour12:!1})}function to(e){return String(e||"").trim().toUpperCase()}function hI(e){return/^[A-Z_][A-Z0-9_]*$/.test(to(e))}function pI(e){const t=String(e||"").split(/\r?\n/),n=new Set;let s=0,r=0;for(const a of t){const i=String(a||"").trim();if(!i||i.startsWith("#"))continue;s+=1;const u=i.replace(/^export\s+/,"").match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);if(!u){r+=1;continue}n.add(to(u[1]))}return s===0||r>0?[]:[...n]}function xI(e){return e==="clipboard"?{title:"剪贴板导入",description:"读取当前剪贴板中的 .env 文本,预览后确认导入。"}:{title:"手动输入",description:"手动填写单个 key 和 value,适合补充或精确编辑。"}}function uu(e){return e?"rounded-[12px] border border-border bg-background text-foreground":"rounded-[12px] border border-transparent bg-transparent text-muted-foreground hover:border-border/60 hover:bg-background/70 hover:text-foreground"}function bI(e){const{title:t,description:n,emptyText:s,items:r,loading:a,writable:i=!0,agentOptions:l=[],onUpsert:u,onImport:d,onRemove:f}=e,g=Ls(),[m,h]=c.useState(""),[x,y]=c.useState(""),[w,b]=c.useState(""),[p,v]=c.useState("global"),[S,j]=c.useState(""),[C,A]=c.useState(""),[M,O]=c.useState("global"),[P,$]=c.useState(""),[z,N]=c.useState(!1),[H,R]=c.useState("manual"),[I,T]=c.useState(""),[E,q]=c.useState([]),[k,D]=c.useState(!1),B=to(m),Q=l.length>0,Z=Q&&p==="agent",te=!!C,se=i&&E.length>0&&(!Z||!!String(S||"").trim()),ie=i&&B.length>0&&hI(B)&&(!Z||!!String(S||"").trim()),oe=xI(H),pe=c.useMemo(()=>{const W=new Map;for(const X of l){const G=String(X.id||"").trim();G&&W.set(G,String(X.name||X.id||"").trim()||G)}return W},[l]),_=c.useCallback(()=>{h(""),y(""),b(""),v("global"),j(""),A(""),O("global"),R("manual"),T(""),q([]),D(!1)},[]),Y=c.useCallback(()=>{(async()=>{var X;if(D(!1),T(""),q([]),typeof navigator>"u"||!((X=navigator.clipboard)!=null&&X.readText)){D(!0);return}$("clipboard:read");try{const G=await navigator.clipboard.readText(),L=pI(G);T(G),q(L)}catch{T(""),q([])}finally{D(!0),$("")}})()},[]),le=c.useCallback(()=>{i&&(_(),N(!0),d&&Y())},[Y,d,_,i]),ne=c.useCallback(W=>{i&&(A(String(W.key||"").trim()),O(W.scope||"global"),h(String(W.key||"").trim()),y(String(W.value??"")),b(String(W.description??"")),v(W.scope||"global"),j(String(W.agentId||"").trim()),N(!0))},[i]),ue=c.useCallback(async()=>{if(!ie||!u)return;const W=to(m);$(`save:${W}`);try{await Promise.resolve(u({scope:p,agentId:S||void 0,key:W,description:String(w||"").trim(),value:String(x??"")})),_(),N(!1)}finally{$("")}},[ie,S,w,m,p,x,u,_]),ae=c.useCallback(async()=>{if(!(!se||!d)){$("import:submit");try{await Promise.resolve(d({scope:p,agentId:S||void 0,raw:I})),_(),N(!1)}finally{$("")}}},[se,I,S,p,d,_]),xe=c.useCallback(async W=>{if(!f)return;const X=to(W.key),G=String(W.agentId||"").trim(),L=W.scope||"global";if(await g({title:"删除 Env",description:`确认删除环境变量「${X}」吗?该操作不可恢复。`,confirmText:"删除",confirmVariant:"destructive"})){$(`remove:${L}:${G}:${X}`);try{await Promise.resolve(f({scope:L,agentId:G||void 0,key:X})),X===to(C)&&_()}finally{$("")}}},[g,C,f,_]),ee=r.filter(W=>String(W.value??"").length>0).length;return o.jsxs(wt,{title:t,description:`${n} 共 ${r.length} 个条目,非空值 ${ee} 个。`,actions:i?o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx(be,{type:"button",size:"icon",className:"h-8 w-8 rounded-[12px]",onClick:le,disabled:a,"aria-label":"新建 Env"}),children:o.jsx(fa,{className:"size-4"})}),o.jsx(eo,{children:"新建 Env"})]})}):null,children:[r.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary py-6 text-center text-sm text-muted-foreground",children:s}):o.jsx("div",{className:"space-y-2",children:r.map(W=>{const X=to(W.key),G=String(W.value??""),L=String(W.description||"").trim(),J=G?`${"*".repeat(Math.min(G.length,12))} (${G.length})`:"(empty)",me=W.scope||"global",ge=String(W.agentId||"").trim(),U=P===`remove:${me}:${ge}:${X}`,ce=ge?pe.get(ge)||ge:"",F=me==="agent"?"Agent":"Global",K=[ce,J].filter(Boolean).join(" · ");return o.jsx("article",{className:"rounded-[16px] bg-transparent px-3.5 py-2 transition-colors hover:bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"truncate text-sm",children:[o.jsx("span",{className:"font-mono font-semibold text-foreground",children:X}),o.jsx("span",{className:"ml-2 inline-flex h-5 items-center rounded-full bg-secondary px-2 text-[10px] font-medium text-muted-foreground align-middle",children:F}),K?o.jsx("span",{className:"ml-2 truncate font-mono text-xs text-muted-foreground",children:K}):null]}),L?o.jsx("div",{className:"mt-1 truncate text-xs text-muted-foreground",children:L}):null]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx("span",{className:"hidden text-[11px] text-muted-foreground md:inline",children:mI(W.updatedAt)}),i?o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:()=>ne(W),title:"编辑","aria-label":"编辑",children:o.jsx(hd,{className:"size-3.5"})}):null,i?o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Ro,onClick:()=>{xe({scope:me,agentId:ge,key:X})},disabled:U,title:"删除","aria-label":"删除",children:U?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(er,{className:"size-3.5"})}):null]})]})},`${String(W.scope||"global")}:${String(W.agentId||"")}:${X}`)})}),o.jsx($n,{open:z,onOpenChange:W=>{N(W),W||_()},children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:C?"编辑 Env":"新建 Env"}),o.jsx(os,{className:"text-xs leading-5",children:C?"更新当前环境变量。":`${oe.title}。${oe.description}`})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-3 overflow-y-auto px-4 pb-2",children:[te?null:o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("button",{type:"button",className:`${uu(H==="manual")} px-3 py-3 text-left transition`,onClick:()=>R("manual"),children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[o.jsx(u5,{className:"size-4"}),"手动输入"]}),o.jsx("div",{className:"mt-1 text-[11px] leading-5 text-muted-foreground",children:"单条创建"})]}),o.jsxs("button",{type:"button",className:`${uu(H==="clipboard")} px-3 py-3 text-left transition`,onClick:()=>{R("clipboard"),!k&&d&&Y()},disabled:!d,children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[o.jsx(JA,{className:"size-4"}),"剪贴板导入"]}),o.jsx("div",{className:"mt-1 text-[11px] leading-5 text-muted-foreground",children:"批量导入"})]})]}),Q?o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"范围"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"scope help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"Global 为共享,Agent 为单个 agent 私有"})]})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsx("button",{type:"button",className:`${uu(p==="global")} h-10 px-3 text-sm font-medium transition`,onClick:()=>v("global"),disabled:!!C&&M!=="global",children:"Global"}),o.jsx("button",{type:"button",className:`${uu(p==="agent")} h-10 px-3 text-sm font-medium transition`,onClick:()=>v("agent"),disabled:!!C&&M!=="agent",children:"Agent"})]})]}):null,Z?o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Agent"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"agent help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"写入所选 agent 的私有 env"})]})})]}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:pe.get(S)||"选择目标 agent"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[16rem]",children:l.map(W=>{const X=String(W.id||"").trim(),G=String(W.name||W.id||"").trim()||X;return X?o.jsxs(bt,{onClick:()=>j(X),children:[S===X?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{className:"truncate",title:X,children:G})]},X):null})})]})]}):null,te||H==="manual"?o.jsxs("div",{className:"space-y-4 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs(qt,{className:"text-xs text-muted-foreground",children:["Key ",o.jsx("span",{className:"text-destructive",children:"*"})]}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"key help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"使用标准环境变量格式,如 `OPENAI_API_KEY`"})]})})]}),o.jsx(lt,{placeholder:"OPENAI_API_KEY",className:"h-10 rounded-[12px]",value:m,onChange:W=>h(to(W.target.value))}),!ie&&B?o.jsx("div",{className:"text-[11px] text-destructive",children:"Key 格式不合法"}):null]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Description"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"description help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"描述这个环境变量的用途,`city keys` 会读取这里"})]})})]}),o.jsx(lt,{placeholder:"例如:MinerU 服务 API Key",className:"h-10 rounded-[12px]",value:w,onChange:W=>b(W.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Value"}),o.jsx(Jr,{children:o.jsxs(Qr,{children:[o.jsx(Wr,{render:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":"value help"}),children:o.jsx(ol,{className:"size-3.5"})}),o.jsx(eo,{children:"留空会保存为空字符串"})]})})]}),o.jsx(jf,{placeholder:C?"输入新的 value 覆盖当前值":"env value",className:"min-h-[112px] rounded-[12px]",value:x,onChange:W=>y(W.target.value)})]})]}):null,!te&&H==="clipboard"?o.jsxs("div",{className:"space-y-3 rounded-[18px] bg-secondary p-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"剪贴板"}),o.jsx("div",{className:"mt-1 text-[11px] leading-5 text-muted-foreground",children:"支持粘贴标准 `.env` 文本。"})]}),o.jsx(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[10px] px-3",onClick:Y,disabled:P==="clipboard:read",children:P==="clipboard:read"?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}),"检测中"]}):"重新读取"})]}),o.jsx("div",{className:"rounded-[12px] bg-background px-3 py-2 text-[11px] text-muted-foreground",children:p==="agent"?`导入到 Agent · ${pe.get(S)||"未选择"}`:"导入到 Global"}),o.jsx("div",{className:"rounded-[12px] bg-background px-3 py-2",children:o.jsx("pre",{className:"max-h-[140px] overflow-auto whitespace-pre-wrap break-all font-mono text-[11px] leading-5 text-muted-foreground",children:I||"剪贴板内容会显示在这里。"})}),k?E.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-sm text-foreground",children:["检测到 ",E.length," 个 env 键"]}),o.jsx("div",{className:"flex flex-wrap gap-2",children:E.map(W=>o.jsx("span",{className:"inline-flex h-7 items-center rounded-full bg-background px-3 font-mono text-xs text-foreground",children:W},W))})]}):o.jsx("div",{className:"text-sm text-muted-foreground",children:"当前剪贴板不是有效的 `.env` 文本,请先复制类似 `KEY=value` 的内容。"}):o.jsx("div",{className:"text-sm text-muted-foreground",children:"正在读取剪贴板..."})]}):null]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>N(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:te||H==="manual"?!ie||a||P.startsWith("save:"):!se||a||P==="import:submit"||P==="clipboard:read",onClick:()=>{if(!te&&H==="clipboard"){ae();return}ue()},children:P.startsWith("save:")?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}),"保存中..."]}):P==="import:submit"?o.jsxs(o.Fragment,{children:[o.jsx(nt,{className:"mr-1 size-3.5 animate-spin"}),"导入中..."]}):!te&&H==="clipboard"?"确认导入":C?"保存":"创建"})]})]})})]})}const yI=["openai","anthropic","deepseek","gemini","open-compatible","open-responses","moonshot-cn","moonshot-ai","kimi-code","xai","huggingface","openrouter"];function N0(e){const t=String(e||"").trim();if(!t)return"-";const n=Date.parse(t);return!Number.isFinite(n)||Number.isNaN(n)?"-":new Date(n).toLocaleString("zh-CN",{hour12:!1})}function vI(e){return String(e||"").trim()}function wI(e,t){return t?`${t}${e}`:e}function T0(e){return o.jsx("button",{type:"button",className:`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${Vn}`,onClick:e.onClick,disabled:e.disabled||e.loading,title:e.label,"aria-label":e.label,children:e.loading?o.jsx(nt,{className:"size-4 animate-spin"}):e.icon})}function Yr(e){return o.jsx("button",{type:"button",className:`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${e.danger?Ro:Vn}`,onClick:e.onClick,disabled:e.disabled||e.loading,title:e.label,"aria-label":e.label,children:e.loading?o.jsx(nt,{className:"size-3.5 animate-spin"}):e.icon})}function SI(e){const{model:t,providers:n,poolItems:s,loading:r,onUpsertProvider:a,onRemoveProvider:i,onTestProvider:l,onDiscoverProvider:u,onUpsertModel:d,onRemoveModel:f,onPauseModel:g,onTestModel:m}=e,h=Ls(),[x,y]=c.useState({id:"",type:"openai",baseUrl:"",apiKey:"",hasExistingApiKey:!1,apiKeyMasked:""}),[w,b]=c.useState({id:"",providerId:"",name:"",temperature:"",maxTokens:"",topP:"",frequencyPenalty:"",presencePenalty:"",anthropicVersion:""}),[p,v]=c.useState(""),[S,j]=c.useState(""),[C,A]=c.useState(""),[M,O]=c.useState(!1),[P,$]=c.useState(!1),[z,N]=c.useState(!1),[H,R]=c.useState("Reply with exactly: OK"),[I,T]=c.useState(""),[E,q]=c.useState(!1),[k,D]=c.useState(""),[B,Q]=c.useState(""),[Z,te]=c.useState(""),[se,ie]=c.useState([]),[oe,pe]=c.useState([]),[_,Y]=c.useState({}),le=c.useCallback(F=>!!_[F],[_]),ne=c.useCallback(async(F,K)=>{Y(he=>({...he,[F]:!0}));try{await K()}finally{Y(he=>({...he,[F]:!1}))}},[]),ue=c.useMemo(()=>n.map(F=>String(F.id||"").trim()).filter(Boolean),[n]),ae=c.useMemo(()=>new Set(s.map(F=>String(F.id||"").trim()).filter(Boolean)),[s]),xe=c.useMemo(()=>{const F=p.trim().toLowerCase();return F?n.filter(K=>{const he=String(K.id||"").toLowerCase(),Te=String(K.type||"").toLowerCase(),Se=String(K.baseUrl||"").toLowerCase();return he.includes(F)||Te.includes(F)||Se.includes(F)}):n},[p,n]),ee=c.useMemo(()=>{const F=S.trim().toLowerCase();return F?s.filter(K=>{const he=String(K.id||"").toLowerCase(),Te=String(K.providerId||"").toLowerCase(),Se=String(K.name||"").toLowerCase();return he.includes(F)||Te.includes(F)||Se.includes(F)}):s},[S,s]),W=c.useMemo(()=>se.map(F=>{const K=vI(F);if(!K)return null;const he=wI(K,Z),Te=ae.has(he),Se=oe.includes(K);return{remoteName:K,targetModelId:he,exists:Te,checked:Se}}).filter(F=>!!F),[Z,se,ae,oe]),X=c.useMemo(()=>{const F=k.trim().toLowerCase();return F?W.filter(K=>K.remoteName.toLowerCase().includes(F)||K.targetModelId.toLowerCase().includes(F)):W},[k,W]),G=c.useMemo(()=>X.filter(F=>!F.exists),[X]),L=c.useMemo(()=>G.map(F=>F.remoteName),[G]),J=L.length>0&&L.every(F=>oe.includes(F)),me=x.id.trim().length>0&&x.type.trim().length>0,ge=w.id.trim().length>0&&w.providerId.trim().length>0&&w.name.trim().length>0,U=c.useCallback(()=>{y({id:"",type:"openai",baseUrl:"",apiKey:"",hasExistingApiKey:!1,apiKeyMasked:""})},[]),ce=c.useCallback(()=>{b({id:"",providerId:"",name:"",temperature:"",maxTokens:"",topP:"",frequencyPenalty:"",presencePenalty:"",anthropicVersion:""})},[]);return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Providers",description:"配置可用的模型 Provider,支持自定义 baseUrl 与 API Key。",actions:o.jsxs(o.Fragment,{children:[o.jsx(lt,{value:p,onChange:F=>v(F.target.value),placeholder:"筛选 provider",className:"w-[220px]"}),o.jsx(lt,{placeholder:"发现前缀",value:C,onChange:F=>A(F.target.value),className:"w-40"}),o.jsx(T0,{label:"新增 Provider",icon:o.jsx(fa,{className:"size-4"}),onClick:()=>{U(),O(!0)},disabled:r})]}),children:xe.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-3 py-3 text-sm text-muted-foreground",children:"没有 provider"}):o.jsx("div",{className:"space-y-2",children:xe.map(F=>{const K=String(F.id||"").trim();return K?o.jsxs("article",{className:"group flex flex-col gap-3 rounded-[16px] bg-transparent px-3 py-3 transition-colors hover:bg-secondary lg:flex-row lg:items-center lg:justify-between",children:[o.jsx("div",{className:"min-w-0 flex-1 text-[11px] text-muted-foreground",children:o.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[o.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:K}),o.jsx("span",{className:"rounded-full bg-secondary px-2 py-0.5 text-[11px] text-muted-foreground",children:F.type||"-"}),o.jsx("span",{className:"truncate",title:F.baseUrl||"",children:F.baseUrl||"-"}),o.jsx("span",{children:F.hasApiKey?F.apiKeyMasked||"configured":"empty"}),o.jsx("span",{children:N0(F.updatedAt)})]})}),o.jsxs("div",{className:"inline-flex items-center gap-1 opacity-100 transition-opacity lg:opacity-0 lg:group-hover:opacity-100 lg:group-focus-within:opacity-100",children:[o.jsx(Yr,{label:"编辑",icon:o.jsx(hd,{className:"size-3.5"}),onClick:()=>{y({id:K,type:String(F.type||"openai"),baseUrl:String(F.baseUrl||""),apiKey:"",hasExistingApiKey:F.hasApiKey===!0,apiKeyMasked:String(F.apiKeyMasked||"")}),O(!0)}}),o.jsx(Yr,{label:"测试",icon:o.jsx(sa,{className:"size-3.5"}),onClick:()=>{ne(`provider:test:${K}`,async()=>{await Promise.resolve(l(K))})},loading:le(`provider:test:${K}`)}),o.jsx(Yr,{label:"发现",icon:o.jsx(Ym,{className:"size-3.5"}),onClick:()=>{ne(`provider:discover:${K}`,async()=>{const he=C.trim(),Te=await Promise.resolve(u({providerId:K,autoAdd:!1,prefix:he||void 0}));if(!Te)return;const Se=Array.isArray(Te.discoveredModels)?Te.discoveredModels:[];Q(K),te(he),ie(Se),D(""),pe([]),q(!0)})},loading:le(`provider:discover:${K}`)}),o.jsx(Yr,{label:"删除",icon:o.jsx(er,{className:"size-3.5"}),onClick:()=>{(async()=>await h({title:"删除 Provider",description:`确认删除 provider「${K}」吗?关联模型也可能受影响。`,confirmText:"删除",confirmVariant:"destructive"})&&await ne(`provider:delete:${K}`,async()=>{await Promise.resolve(i(K))}))()},loading:le(`provider:delete:${K}`),danger:!0})]})]},K):null})})}),o.jsx(wt,{title:"Models",description:`current ${String((t==null?void 0:t.agentPrimaryModelId)||"-")} · provider ${String((t==null?void 0:t.providerType)||"-")} · providers ${n.length} · models ${s.length}`,actions:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:`${ee.length} items`}),o.jsx(lt,{value:S,onChange:F=>j(F.target.value),placeholder:"筛选 model",className:"w-[220px]"}),o.jsx(T0,{label:"新增 Model",icon:o.jsx(fa,{className:"size-4"}),onClick:()=>{ce(),$(!0)},disabled:r}),n.length>0&&o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",size:"sm",className:"inline-flex items-center gap-1.5 h-8 rounded-[11px] px-3",disabled:r}),children:[o.jsx(Ym,{className:"size-3.5"}),o.jsx("span",{className:"text-xs",children:"发现并添加"}),o.jsx(kr,{className:"size-3"})]}),o.jsx(wn,{className:"min-w-[14rem]",children:n.map(F=>{const K=String(F.id||"").trim();return K?o.jsxs(bt,{onClick:()=>{ne(`provider:discover:${K}`,async()=>{const he=C.trim(),Te=await Promise.resolve(u({providerId:K,autoAdd:!1,prefix:he||void 0}));if(!Te)return;const Se=Array.isArray(Te.discoveredModels)?Te.discoveredModels:[];Q(K),te(he),ie(Se),D(""),pe([]),q(!0)})},children:[o.jsx("span",{children:K}),o.jsx("span",{className:"ml-auto text-[11px] text-muted-foreground",children:F.type||"-"})]},K):null})})]})]}),children:ee.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-3 py-3 text-sm text-muted-foreground",children:"没有 model"}):o.jsx("div",{className:"space-y-2",children:ee.map(F=>{const K=String(F.id||"").trim();if(!K)return null;const he=F.isPaused===!0;return o.jsxs("article",{className:"group flex flex-col gap-3 rounded-[16px] bg-transparent px-3 py-3 transition-colors hover:bg-secondary lg:flex-row lg:items-center lg:justify-between",children:[o.jsx("div",{className:"min-w-0 flex-1 text-[11px] text-muted-foreground",children:o.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[o.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:K}),o.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] ${he?"bg-secondary text-muted-foreground":"bg-emerald-500/12 text-emerald-700"}`,children:[o.jsx("span",{className:`size-1.5 rounded-full ${he?"bg-muted-foreground/70":"bg-emerald-600"}`}),o.jsx("span",{children:he?"paused":"active"})]}),o.jsx("span",{children:F.providerId||"-"}),o.jsx("span",{className:"truncate",children:F.name||"-"}),o.jsx("span",{children:`temp ${F.temperature??"-"}`}),o.jsx("span",{children:`max ${F.maxTokens??"-"}`}),o.jsx("span",{children:`topP ${F.topP??"-"}`}),o.jsx("span",{children:N0(F.updatedAt)})]})}),o.jsxs("div",{className:"inline-flex items-center gap-1 opacity-100 transition-opacity lg:opacity-0 lg:group-hover:opacity-100 lg:group-focus-within:opacity-100",children:[o.jsx(Yr,{label:"编辑",icon:o.jsx(hd,{className:"size-3.5"}),onClick:()=>{b({id:K,providerId:String(F.providerId||""),name:String(F.name||""),temperature:F.temperature===void 0?"":String(F.temperature),maxTokens:F.maxTokens===void 0?"":String(F.maxTokens),topP:F.topP===void 0?"":String(F.topP),frequencyPenalty:F.frequencyPenalty===void 0?"":String(F.frequencyPenalty),presencePenalty:F.presencePenalty===void 0?"":String(F.presencePenalty),anthropicVersion:String(F.anthropicVersion||"")}),$(!0)}}),o.jsx(Yr,{label:"测试",icon:o.jsx(sa,{className:"size-3.5"}),onClick:()=>{T(K),N(!0)}}),o.jsx(Yr,{label:he?"恢复":"暂停",icon:he?o.jsx(sa,{className:"size-3.5"}):o.jsx(Nw,{className:"size-3.5"}),onClick:()=>{ne(`model:pause:${K}`,async()=>{await Promise.resolve(g(K,!he))})},loading:le(`model:pause:${K}`)}),o.jsx(Yr,{label:"删除",icon:o.jsx(er,{className:"size-3.5"}),onClick:()=>{(async()=>await h({title:"删除 Model",description:`确认删除模型「${K}」吗?该操作不可恢复。`,confirmText:"删除",confirmVariant:"destructive"})&&await ne(`model:delete:${K}`,async()=>{await Promise.resolve(f(K))}))()},loading:le(`model:delete:${K}`),danger:!0})]})]},K)})})}),o.jsx($n,{open:E,onOpenChange:q,children:o.jsxs(Un,{className:"w-[min(92vw,720px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"发现模型"}),o.jsx(os,{children:"从 provider 拉取可用模型,并按需添加到本地模型池。"})]}),se.length===0?o.jsx("div",{className:"px-4 pb-2 text-sm text-muted-foreground",children:"未发现可用模型"}):o.jsx("div",{className:"max-h-[58vh] space-y-3 overflow-auto px-4 pb-2",children:o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-[18px] bg-secondary/85 px-3 py-2.5 text-xs text-muted-foreground",children:[o.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[o.jsx("span",{children:`provider ${B||"-"}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`prefix ${Z||"(none)"}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`发现 ${W.length}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`可添加 ${W.filter(F=>!F.exists).length}`}),o.jsx("span",{children:"·"}),o.jsx("span",{children:`已选 ${oe.length}`})]}),o.jsx("div",{className:"text-[11px]",children:`当前结果 ${X.length} 项`})]}),o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"flex flex-col gap-2 rounded-[14px] bg-transparent px-2 py-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("div",{className:"relative min-w-0 flex-1",children:[o.jsx(Wl,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{value:k,onChange:F=>D(F.target.value),placeholder:"搜索模型名或目标 ID",className:"h-10 border-0 bg-background pl-9 shadow-none"})]}),o.jsx(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[11px] px-3",disabled:L.length===0,onClick:()=>pe(F=>{if(J)return F.filter(he=>!L.includes(he));const K=new Set(F);return L.forEach(he=>K.add(he)),Array.from(K)}),children:J?"取消全选":"全选结果"}),o.jsx(be,{type:"button",size:"sm",variant:"ghost",className:"h-8 rounded-[11px] px-3",disabled:oe.length===0,onClick:()=>pe([]),children:"清空"})]}),X.length===0?o.jsx("div",{className:"rounded-[14px] bg-transparent px-3 py-6 text-center text-sm text-muted-foreground",children:"没有匹配的模型"}):o.jsx("div",{className:"space-y-1",children:X.map(F=>o.jsxs("label",{className:Me("flex items-center justify-between gap-3 rounded-[14px] px-3 py-2.5 text-sm transition-colors",F.exists?"bg-transparent opacity-65":"cursor-pointer bg-transparent hover:bg-background"),children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(m6,{checked:F.checked,disabled:F.exists,className:"size-4 rounded-[5px]",onCheckedChange:K=>{pe(he=>K?he.includes(F.remoteName)?he:[...he,F.remoteName]:he.filter(Te=>Te!==F.remoteName))}}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:F.remoteName}),o.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:F.targetModelId})]})]}),o.jsx("div",{className:"shrink-0 text-[11px] text-muted-foreground",children:F.exists?"已存在":F.checked?"已选中":"可添加"})]},`discover:${F.remoteName}`))})]})})]})}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>q(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:oe.length===0||r||le("discover:add"),onClick:()=>{ne("discover:add",async()=>{for(const F of oe){const K=String(F||"").trim();if(!K)continue;const he=Z?`${Z}${K}`:K;ae.has(he)||await Promise.resolve(d({id:he,providerId:B,name:K}))}q(!1)})},children:le("discover:add")?"添加中...":"添加选中"})]})]})}),o.jsx($n,{open:M,onOpenChange:O,children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"Provider"}),o.jsx(os,{className:"sr-only",children:"Provider editor dialog"})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-3 overflow-y-auto px-4 pb-2",children:[o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Provider"}),o.jsx(lt,{placeholder:"provider id",className:"h-10 rounded-[12px]",value:x.id,onChange:F=>y(K=>({...K,id:F.target.value}))}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:x.type||"provider type"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:yI.map(F=>o.jsxs(bt,{onClick:()=>y(K=>({...K,type:F})),children:[x.type===F?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:F})]},F))})]})]}),o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Connection"}),o.jsx(lt,{placeholder:"base url (optional)",className:"h-10 rounded-[12px]",value:x.baseUrl,onChange:F=>y(K=>({...K,baseUrl:F.target.value}))}),o.jsx(lt,{placeholder:x.hasExistingApiKey?"留空保留当前 API Key":"api key (optional)",className:"h-10 rounded-[12px]",value:x.apiKey,onChange:F=>y(K=>({...K,apiKey:F.target.value}))}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:x.hasExistingApiKey?`已配置:${x.apiKeyMasked||"configured"}`:"未配置 API Key"})]})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>O(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!me||r||le("provider:save"),onClick:()=>{ne("provider:save",async()=>{await Promise.resolve(a({id:x.id.trim(),type:x.type.trim(),baseUrl:x.baseUrl.trim()||void 0,apiKey:x.apiKey||void 0})),O(!1)})},children:le("provider:save")?"保存中...":"保存"})]})]})}),o.jsx($n,{open:z,onOpenChange:N,children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"测试 Model"}),o.jsx(os,{className:"sr-only",children:"Model test dialog"})]}),o.jsxs("div",{className:"space-y-3 overflow-y-auto px-4 pb-2",children:[o.jsx("div",{className:"rounded-[18px] bg-secondary px-3 py-2 text-xs text-muted-foreground",children:`model ${I||"-"}`}),o.jsx(jf,{className:"min-h-[112px] rounded-[12px]",value:H,onChange:F=>R(F.target.value),placeholder:"输入测试 prompt"})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>N(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!I||r||le(`model:test:${I}`),onClick:()=>{ne(`model:test:${I}`,async()=>{await Promise.resolve(m(I,H)),N(!1)})},children:le(`model:test:${I}`)?"测试中...":"运行测试"})]})]})}),o.jsx($n,{open:P,onOpenChange:$,children:o.jsxs(Un,{className:"w-[min(92vw,560px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"Model"}),o.jsx(os,{className:"sr-only",children:"Model editor dialog"})]}),o.jsxs("div",{className:"max-h-[62vh] space-y-3 overflow-y-auto px-4 pb-2",children:[o.jsxs("div",{className:"space-y-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(qt,{className:"text-xs text-muted-foreground",children:"Model"}),o.jsx(lt,{placeholder:"model id",className:"h-10 rounded-[12px]",value:w.id,onChange:F=>b(K=>({...K,id:F.target.value}))}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",variant:"outline",className:"h-10 w-full justify-between rounded-[12px] px-3"}),children:[o.jsx("span",{children:w.providerId||"provider"}),o.jsx(kr,{className:"size-4 shrink-0 text-muted-foreground"})]}),o.jsx(wn,{className:"min-w-[12rem]",children:ue.map(F=>o.jsxs(bt,{onClick:()=>b(K=>({...K,providerId:F})),children:[w.providerId===F?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{children:F})]},F))})]}),o.jsx(lt,{placeholder:"upstream model name",className:"h-10 rounded-[12px]",value:w.name,onChange:F=>b(K=>({...K,name:F.target.value}))})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 rounded-[18px] bg-secondary p-3",children:[o.jsx(lt,{placeholder:"temperature",className:"h-10 rounded-[12px]",value:w.temperature,onChange:F=>b(K=>({...K,temperature:F.target.value}))}),o.jsx(lt,{placeholder:"max tokens",className:"h-10 rounded-[12px]",value:w.maxTokens,onChange:F=>b(K=>({...K,maxTokens:F.target.value}))}),o.jsx(lt,{placeholder:"top p",className:"h-10 rounded-[12px]",value:w.topP,onChange:F=>b(K=>({...K,topP:F.target.value}))}),o.jsx(lt,{placeholder:"anthropic version",className:"h-10 rounded-[12px]",value:w.anthropicVersion,onChange:F=>b(K=>({...K,anthropicVersion:F.target.value}))}),o.jsx(lt,{placeholder:"frequency penalty",className:"col-span-2 h-10 rounded-[12px]",value:w.frequencyPenalty,onChange:F=>b(K=>({...K,frequencyPenalty:F.target.value}))}),o.jsx(lt,{placeholder:"presence penalty",className:"col-span-2 h-10 rounded-[12px]",value:w.presencePenalty,onChange:F=>b(K=>({...K,presencePenalty:F.target.value}))})]})]}),o.jsxs(rs,{className:"gap-2 sm:justify-end",children:[o.jsx(be,{size:"sm",variant:"outline",className:"h-9 rounded-[12px] px-4",onClick:()=>$(!1),children:"取消"}),o.jsx(be,{size:"sm",className:"h-9 rounded-[12px] px-4",disabled:!ge||r||le("model:save"),onClick:()=>{ne("model:save",async()=>{await Promise.resolve(d({id:w.id.trim(),providerId:w.providerId.trim(),name:w.name.trim(),temperature:w.temperature,maxTokens:w.maxTokens,topP:w.topP,frequencyPenalty:w.frequencyPenalty,presencePenalty:w.presencePenalty,anthropicVersion:w.anthropicVersion})),$(!1)})},children:le("model:save")?"保存中...":"保存"})]})]})})]})}function oa(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function wx(e){const t=e.detail;return oa(t)?t:void 0}function jI(e){const t=wx(e);if(!t)return{};const n=t.config;return oa(n)?n:{}}function CI(e){const t=String(e||"").trim().toLowerCase();return t==="string"||t==="boolean"||t==="number"||t==="secret"||t==="enum"?t:"string"}function kI(e){const t=String(e||"").trim().toLowerCase();return t==="ship_json"||t==="bot_account"||t==="env_fallback"?t:"ship_json"}function NI(e){if(!Array.isArray(e))return;const t=e.map(n=>{if(!oa(n))return null;const s=String(n.value||"").trim();if(!s)return null;const r=String(n.label||s).trim()||s,a=String(n.description||"").trim();return{value:s,label:r,description:a}}).filter(n=>!!n);return t.length>0?t:void 0}function TI(e){if(!oa(e))return null;const t=String(e.key||"").trim();if(!t)return null;const n=String(e.label||t).trim()||t,s=String(e.description||"").trim(),r=CI(e.type);return{key:t,label:n,description:s,type:r,source:kI(e.source),required:e.required===!0,nullable:e.nullable===!0,writable:e.writable===!0,restartRequired:e.restartRequired===!0,defaultValue:typeof e.defaultValue=="string"||typeof e.defaultValue=="number"||typeof e.defaultValue=="boolean"||e.defaultValue===null?e.defaultValue:void 0,example:typeof e.example=="string"||typeof e.example=="number"||typeof e.example=="boolean"||e.example===null?e.example:void 0,options:NI(e.options)}}function Pg(e){return Array.isArray(e)?e.map(t=>TI(t)).filter(t=>!!t):[]}function AI(e){const t=wx(e);if(!t)return null;const n=t.configuration;if(!oa(n))return null;const s=oa(n.fields)?n.fields:{};return{channel:String(n.channel||e.channel||"").trim(),title:String(n.title||`${String(e.channel||"").trim()} Configuration`).trim(),description:String(n.description||"").trim(),version:String(n.version||"1.0.0").trim(),capabilities:oa(n.capabilities)?{canToggleEnabled:n.capabilities.canToggleEnabled===!0,canBindChannelAccount:n.capabilities.canBindChannelAccount===!0,canConfigure:n.capabilities.canConfigure===!0}:void 0,fields:{ship:Pg(s.ship),channelAccount:Pg(s.channelAccount),envFallback:Pg(s.envFallback)}}}const EI={feishu:"https://downcity.ai/zh/docs/services/chat/feishu"};function _a(e){return String(e||"").trim()||null}function $j(e){const t=String(e.chatTitle||"").trim(),n=String(e.chatId||"").trim();return t&&(!n||t!==n)?{value:t,source:"title"}:n?{value:n,source:"chat_id"}:{value:String(e.sessionId||"").trim()||"unknown",source:"session_id"}}function MI(e){const t=$j(e);return JSON.stringify({sessionId:_a(e.sessionId),channel:_a(ma(e)),chatId:_a(e.chatId),chatTitle:_a(e.chatTitle),chatDisplayName:_a(t.value),chatDisplayNameSource:t.source,chatType:_a(e.chatType),threadId:typeof e.threadId=="number"&&Number.isFinite(e.threadId)?e.threadId:null},null,2)}function RI(e){const{sessions:t,chatChannels:n,channelAccounts:s,selectedSessionId:r,focusedChannel:a,formatTime:i,onOpenSession:l,onDeleteSession:u,deletingSessionId:d,onChatAction:f,onChatConfigure:g}=e,m=Ls(),[h,x]=c.useState(""),[y,w]=c.useState("all"),b=String(a||"").trim().toLowerCase(),p=c.useMemo(()=>b?t.filter(k=>ma(k)===b):[],[t,b]),v=c.useMemo(()=>b?n.filter(k=>String(k.channel||"").trim().toLowerCase()===b):[],[n,b]),S=Oz(p,h),C=zj(S).filter(k=>y==="all"?!0:k.key===y).flatMap(k=>k.items),A=v[0]||null,M=String((A==null?void 0:A.channel)||"").trim(),O=bx(M),P=String((A==null?void 0:A.linkState)||"unknown").trim().toLowerCase(),$=c.useMemo(()=>{if(!A)return;const k=wx(A);return k||void 0},[A]),z=c.useMemo(()=>A?jI(A):{},[A]),N=c.useMemo(()=>A?AI(A):null,[A]),H=c.useMemo(()=>{var k;return A?M==="consoleui"||($==null?void 0:$.readonly)===!0||((k=N==null?void 0:N.capabilities)==null?void 0:k.canConfigure)===!1:!1},[A,M,N,$]),R=c.useMemo(()=>String(z.channelAccountId||"").trim(),[z]),I=c.useMemo(()=>{const k=String(M||"").trim().toLowerCase();return!k||k==="consoleui"?[]:s.filter(D=>String(D.channel||"").trim().toLowerCase()===k)},[M,s]),T=c.useMemo(()=>{const k=String(M||"").trim().toLowerCase();return k&&EI[k]||null},[M]),E=c.useMemo(()=>{if(!R)return"config";const k=I.find(D=>String(D.id||"").trim()===R);return k&&String(k.name||k.id||"config").trim()||"config"},[R,I]),q=c.useCallback(k=>{if(!M||H)return;const D=String(k||"").trim(),B=D==="__none__"?"":D;B!==R&&g(M,{channelAccountId:B||null})},[R,M,H,g]);return o.jsxs("div",{className:"space-y-5",children:[A?o.jsx(wt,{title:"Channel Runtime",description:`当前 channel:${O||"unknown"} · account ${E}`,children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 px-1 py-1",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-xl font-semibold leading-none text-foreground",children:O||"unknown"}),M==="qq"?o.jsx("div",{className:"mt-2 rounded-[12px] border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-xs leading-5 text-amber-950",children:"QQ channel 当前为 dev 版本,建议仅用于测试与验证。"}):null,o.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:`size-1.5 rounded-full ${P==="connected"?"bg-emerald-500":P==="disconnected"||P==="error"?"bg-destructive":"bg-muted-foreground/60"}`}),o.jsx("span",{children:`link ${P||"-"}`})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[M!=="consoleui"?o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{size:"sm",variant:"outline",className:"h-8 min-w-[9.5rem] max-w-[12rem] justify-between gap-1 px-2.5 text-[11px]",disabled:H}),children:[o.jsx("span",{className:"truncate",children:E}),o.jsx(kr,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),o.jsxs(wn,{className:"min-w-[12rem]",children:[o.jsxs(bt,{onClick:()=>q("__none__"),children:[R?o.jsx("span",{className:"inline-block w-4"}):o.jsx(Ws,{className:"size-4"}),o.jsx("span",{children:"no binding"})]}),I.map(k=>{const D=String(k.id||"").trim();if(!D)return null;const B=String(k.name||"").trim()||D,Q=D===R;return o.jsxs(bt,{onClick:()=>q(D),children:[Q?o.jsx(Ws,{className:"size-4"}):o.jsx("span",{className:"inline-block w-4"}),o.jsx("span",{className:"truncate",children:B})]},D)})]})]}):null,o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||A.enabled===!0,onClick:()=>f("open",M),children:"open"}),o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||A.enabled!==!0,onClick:()=>f("close",M),children:"close"}),o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||!(A.enabled===!0&&A.configured===!0),onClick:()=>f("test",M),children:"test"}),o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]",disabled:H||!(A.enabled===!0&&A.configured===!0),onClick:()=>f("reconnect",M),children:"reconnect"})]})]}),T?o.jsx("div",{className:"flex items-center justify-start px-1 pb-1",children:o.jsxs("a",{href:T,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[o.jsx("span",{children:"查看飞书接入文档"}),o.jsx(r5,{className:"size-3"})]})}):null]})}):o.jsx(wt,{title:"Channel Runtime",description:"当前 channel 暂无状态。",children:o.jsx("section",{className:"rounded-[18px] bg-secondary px-3.5 py-5 text-sm text-muted-foreground",children:"当前 channel 暂无状态"})}),o.jsx(wt,{title:"Sessions",description:`当前筛选结果 ${C.length} 条。`,actions:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:`total ${C.length}`}),o.jsx(lt,{value:h,onChange:k=>x(k.target.value),placeholder:"搜索 session",className:"w-[220px]"}),o.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:["all","chat","api","other"].map(k=>o.jsx(be,{type:"button",size:"sm",variant:y===k?"default":"outline",className:"px-2 text-xs",onClick:()=>w(k),children:k},k))})]}),children:C.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-4 py-5 text-sm text-muted-foreground",children:"当前筛选条件下无 session"}):o.jsx("div",{className:"space-y-2",children:C.map(k=>{const D=Oj(k),B=k.sessionId===r,Q=String(d||"").trim()===k.sessionId,Z=k.executing===!0,te=$j(k),se=te.value,ie=MI(k),oe=String(k.chatId||"").trim(),pe=String(k.chatType||"").trim();return o.jsx("article",{className:B?"rounded-[20px] bg-secondary px-4 py-3":"rounded-[20px] bg-transparent px-4 py-3 transition-colors hover:bg-secondary",children:o.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",title:`${se}
|
|
423
|
+
${k.sessionId}`,children:se}),o.jsx("div",{className:"mt-1 truncate font-mono text-[11px] text-muted-foreground/85",children:k.sessionId}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-[10px] text-muted-foreground/90",children:[o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5 uppercase tracking-[0.08em]",children:D}),o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5 uppercase tracking-[0.08em]",children:te.source}),pe?o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5 uppercase tracking-[0.08em]",children:pe}):null,o.jsx("span",{className:`rounded-full px-1.5 py-0.5 uppercase tracking-[0.08em] ${Z?"bg-primary/12 text-primary":"bg-background text-muted-foreground"}`,children:Z?"executing":"idle"}),o.jsx("span",{className:"rounded-full bg-background px-1.5 py-0.5",children:`${k.messageCount||0} msgs`}),o.jsx("span",{children:i(k.updatedAt)}),oe?o.jsx("span",{className:"max-w-[10rem] truncate font-mono",title:oe,children:oe}):null]}),o.jsx("div",{className:"mt-2 truncate text-xs text-muted-foreground",title:k.lastText||"",children:`${k.lastRole||"unknown"} · ${k.lastText||"(empty)"}`})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 lg:justify-end",children:[o.jsxs(yj,{children:[o.jsxs(vj,{render:o.jsx(be,{size:"sm",variant:"outline",className:"h-8 px-2.5 text-[11px]"}),children:[o.jsx(WA,{className:"size-3.5"}),o.jsx("span",{children:"Route"})]}),o.jsxs(wj,{align:"end",className:"w-[min(92vw,34rem)] overflow-hidden p-0",children:[o.jsx("div",{className:"bg-secondary px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:"context route json"}),o.jsx("pre",{className:"max-h-[320px] overflow-auto whitespace-pre-wrap break-words bg-background/85 px-3 py-3 font-mono text-[11px] leading-relaxed text-foreground/85",children:ie})]})]}),o.jsx(be,{size:"sm",variant:B?"secondary":"outline",className:"h-8 px-2.5",onClick:()=>l(k.sessionId),children:B?"已打开":"打开"}),o.jsxs(be,{size:"sm",variant:"destructive",className:"h-8 px-2.5",disabled:!!d,onClick:async()=>{await m({title:"删除 Session",description:`确认彻底删除 session「${k.sessionId}」吗?该操作不可恢复。`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"})&&u(k.sessionId)},children:[o.jsx(er,{className:"size-3.5"}),o.jsx("span",{children:Q?"删除中...":"删除"})]})]})]})},k.sessionId)})})})]})}function La(e){return String(e||"").trim()||null}function Uj(e){const t=String(e||""),n=t.match(/<info>([\s\S]*?)<\/info>/i),s=n?String(n[1]||"").trim():"";return{text:t.replace(/<info>[\s\S]*?<\/info>/gi,"").trim()||"(empty)",info:s}}function OI(e){const t=String(e.role||"unknown").trim(),n=String(e.toolName||"").trim();return(t==="tool-call"||t==="tool-result")&&n?`${t} · ${n}`:t||"unknown"}function zI(e){const t=String(e||"unknown").trim();return t==="tool-call"?{cardClassName:"border border-border/70 bg-secondary/88 shadow-[inset_0_1px_0_rgba(255,255,255,0.52)] dark:bg-muted/58",roleBadgeClassName:"bg-foreground text-background dark:bg-foreground dark:text-background",toolBadgeClassName:"bg-background/92 text-foreground ring-1 ring-border/70 dark:bg-background/70 dark:ring-border/80",textClassName:"font-mono text-[10px] leading-[1.6] text-foreground/96"}:t==="tool-result"?{cardClassName:"border border-border/55 bg-background shadow-[inset_0_1px_0_rgba(255,255,255,0.34)] dark:bg-background/88",roleBadgeClassName:"bg-secondary text-foreground/86 dark:bg-secondary dark:text-foreground/86",toolBadgeClassName:"bg-secondary/82 text-foreground/78 ring-1 ring-border/60 dark:bg-muted/72 dark:ring-border/70",textClassName:"font-mono text-[10px] leading-[1.6] text-foreground/82"}:t==="user"?{cardClassName:"border border-border/55 bg-secondary/42",roleBadgeClassName:"bg-secondary text-foreground/78",toolBadgeClassName:"bg-secondary text-muted-foreground",textClassName:"text-[10px] leading-[1.55] text-foreground/92"}:{cardClassName:"border border-border/45 bg-background",roleBadgeClassName:"bg-secondary text-foreground/78",toolBadgeClassName:"bg-secondary text-muted-foreground",textClassName:"text-[10px] leading-[1.55] text-foreground/90"}}function Hj(e){const t=String(e.chatTitle||"").trim(),n=String(e.chatId||"").trim();return t&&(!n||t!==n)?{value:t,source:"title"}:n?{value:n,source:"chat_id"}:{value:String(e.sessionId||"").trim()||"unknown",source:"session_id"}}function II(e){const t=Hj({chatTitle:e.chatTitle,chatId:e.chatId,sessionId:e.selectedSessionId});return JSON.stringify({sessionId:La(e.selectedSessionId),channel:La(e.channel),chatId:La(e.chatId),chatTitle:La(e.chatTitle),chatDisplayName:La(t.value),chatDisplayNameSource:t.source,chatType:La(e.chatType),threadId:typeof e.threadId=="number"&&Number.isFinite(e.threadId)?e.threadId:null},null,2)}function DI(e){const t=Array.isArray(e==null?void 0:e.sections)?e.sections:[];if(t.length===0)return[];const n=t.filter(r=>{const a=String(r.key||"").trim().toLowerCase(),i=String(r.title||"").trim().toLowerCase();return a.includes("system")||a.includes("profile")||i.includes("system")||i.includes("profile")});return(n.length>0?n:t.slice(0,2)).flatMap(r=>{const a=String(r.title||r.key||"section").trim()||"section",i=Array.isArray(r.items)?r.items:[];return i.length===0?[{title:a,content:""}]:i.map((l,u)=>{const d=String(l.content||"").trim();return{title:typeof l.index=="number"&&Number.isFinite(l.index)?`${a} · #${l.index}`:`${a} · ${u+1}`,content:d}})})}function _I(e){const{events:t,formatTime:n}=e,s=c.useRef(null),r=c.useRef(!0),a=c.useRef(0);return c.useLayoutEffect(()=>{const i=s.current;if(!i)return;t.length>a.current&&r.current&&(i.scrollTop=i.scrollHeight),a.current=t.length},[t]),o.jsx("div",{ref:s,className:"h-full min-h-0 space-y-2 overflow-y-auto px-2 py-2",onScroll:i=>{const l=i.currentTarget,u=l.scrollHeight-l.scrollTop-l.clientHeight;r.current=u<=48},children:t.length===0?o.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"暂无 chat history"}):t.map((i,l)=>{const d=String(i.direction||"unknown")==="inbound",f=i,g=String(f.actorName||f.username||f.userName||f.senderName||f.displayName||f.fromName||f.from||"").trim(),m=d?g||"user":"agent",h=Uj(String(i.text||"")),x=i.ts?n(i.ts):String(i.isoTime||"").trim()||"-";return o.jsxs("article",{className:Me("rounded-[16px] px-3 py-2.5",d?"bg-background":"bg-secondary"),children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[o.jsx("span",{className:"truncate font-medium uppercase tracking-[0.08em]",children:m}),o.jsx("span",{className:"shrink-0 font-mono text-[10px]",children:x})]}),o.jsx("div",{className:"whitespace-pre-wrap break-words text-[11px] leading-[1.5] text-foreground",children:h.text}),h.info?o.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer select-none",children:"info"}),o.jsx("pre",{className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1 font-mono text-[11px] leading-relaxed text-foreground/80",children:h.info})]}):null]},`${String(i.id||"evt")}:${String(i.ts||"na")}:${l}`)})})}function Fj(e){const{items:t,formatTime:n}=e;return o.jsx("div",{className:"h-full min-h-0 space-y-2 overflow-y-auto px-3 py-3",children:t.length===0?o.jsx("div",{className:"py-8 text-center text-xs text-muted-foreground",children:"暂无 session messages"}):t.map((s,r)=>{const a=String(s.role||"unknown"),i=OI({role:a,toolName:s.toolName}),l=zI(a),u=String(s.toolName||"").trim(),d=Uj(String(s.text||"")),f=n(s.ts);return o.jsxs("article",{className:Me("rounded-[16px] px-3 py-2.5",l.cardClassName),children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:Me("inline-flex h-5 max-w-full items-center rounded-full px-2 text-[10px] font-semibold uppercase tracking-[0.1em]",l.roleBadgeClassName),title:i,children:o.jsx("span",{className:"truncate",children:a})}),u?o.jsx("span",{className:Me("inline-flex h-5 max-w-[min(52vw,16rem)] items-center rounded-full px-2 font-mono text-[10px]",l.toolBadgeClassName),title:u,children:o.jsx("span",{className:"truncate",children:u})}):null]}),o.jsx("span",{className:"shrink-0 font-mono text-[10px]",children:f})]}),o.jsx("div",{className:Me("whitespace-pre-wrap break-words",l.textClassName),children:d.text}),d.info?o.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer select-none",children:"info"}),o.jsx("pre",{className:"mt-1 max-h-32 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1 font-mono text-[11px] leading-relaxed text-foreground/80",children:d.info})]}):null]},`${s.id||a}-${r}`)})})}function LI(e){return o.jsx("div",{className:"h-full min-h-0 overflow-hidden px-3 py-3",children:o.jsx("pre",{className:"h-full overflow-auto whitespace-pre-wrap break-words rounded-[16px] bg-secondary/85 px-3 py-3 font-mono text-xs leading-relaxed text-foreground/85",children:e.routeJson})})}function BI(e){const{blocks:t}=e;return o.jsx("div",{className:"h-full min-h-0 overflow-y-auto px-3 py-3",children:t.length===0?o.jsx("div",{className:"py-8 text-center text-xs text-muted-foreground",children:"暂无 system 内容"}):o.jsx("div",{className:"space-y-3",children:t.map((n,s)=>o.jsxs("section",{className:"rounded-[18px] border border-border/45 bg-secondary/85 px-3 py-3",children:[o.jsx("div",{className:"border-b border-border/40 pb-2 text-xs font-medium text-foreground/85",children:n.title}),o.jsx("div",{className:"pt-3",children:o.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-foreground/85",children:n.content||"(empty)"})})]},`${n.title}-${s}`))})})}function PI(e){const{archives:t,selectedArchiveId:n,archiveMessages:s,formatTime:r,onSelectArchive:a,onRefreshArchives:i}=e;return o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[220px_minmax(0,1fr)]",children:[o.jsxs("div",{className:"flex min-h-0 flex-col rounded-l-[18px] bg-secondary/85",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/45 px-3 py-2",children:[o.jsxs("div",{className:"inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:[o.jsx(PA,{className:"size-3.5"}),o.jsx("span",{children:"compact archives"})]}),o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"size-7 rounded-md",onClick:i,"aria-label":"刷新 archive",title:"刷新 archive",children:o.jsx(xc,{className:"size-3.5"})})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 pb-2",children:t.length===0?o.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"暂无 compact archive"}):o.jsx("div",{className:"space-y-1",children:t.map((l,u)=>{const d=String(l.archiveId||"").trim();if(!d)return null;const f=d===n,g=Number(l.messageCount||0);return o.jsxs("button",{type:"button",className:Me("w-full rounded-[14px] px-2.5 py-2 text-left text-xs transition-colors",f?"bg-background text-foreground":"text-muted-foreground hover:bg-background hover:text-foreground"),onClick:()=>a(d),children:[o.jsx("div",{className:"truncate font-mono text-[11px]",title:d,children:d}),o.jsxs("div",{className:"mt-0.5 flex items-center justify-between gap-2 text-[10px]",children:[o.jsx("span",{children:`${g} msgs`}),o.jsx("span",{className:"truncate",title:r(l.archivedAt),children:r(l.archivedAt)})]})]},`${d}-${u}`)})})})]}),o.jsx("div",{className:"min-h-0 overflow-hidden rounded-r-[18px] bg-background/55",children:n?o.jsx(Fj,{items:s,formatTime:r}):o.jsx("div",{className:"flex h-full items-center justify-center px-4 text-xs text-muted-foreground",children:"请选择左侧 archive 查看 compact 前的历史消息"})})]})}function $I(e){const t=String(e.state||"unknown").trim().toLowerCase(),n=t==="connected"?"bg-primary/12 text-primary":t==="disconnected"||t==="error"?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground";return o.jsxs("div",{className:Me("inline-flex items-center gap-1 rounded-full px-2 py-1 text-[11px]",n),children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",t==="connected"?"bg-primary":"bg-current")}),o.jsx("span",{children:t||"unknown"})]})}function UI(e){const{selectedSessionId:t,sessions:n,channelHistory:s,chatChannels:r,sessionMessages:a,sessionArchives:i,selectedArchiveId:l,sessionArchiveMessages:u,prompt:d,chatInput:f,debugPanelsCollapsed:g,sending:m,clearingSessionMessages:h,clearingChatHistory:x,deletingSession:y,formatTime:w,onChangeInput:b,onSendConsoleUiMessage:p,onClearSessionMessages:v,onClearChatHistory:S,onDeleteSession:j,onRefreshArchives:C,onSelectArchive:A}=e,M=Ls(),[O,P]=c.useState("route"),$=c.useMemo(()=>n.find(k=>String(k.sessionId||"").trim()===t)||null,[n,t]),z=c.useMemo(()=>{const k=ma($||t);return k==="other"?"unknown":k},[$,t]),N=z==="consoleui",H=($==null?void 0:$.executing)===!0,R=c.useMemo(()=>{if(z==="consoleui")return"connected";if(z==="unknown")return"unknown";const k=r.find(D=>String(D.channel||"").trim().toLowerCase()===z);return String((k==null?void 0:k.linkState)||"unknown")},[r,z]),I=c.useMemo(()=>Hj({chatTitle:$==null?void 0:$.chatTitle,chatId:$==null?void 0:$.chatId,sessionId:t}),[$,t]),T=c.useMemo(()=>II({selectedSessionId:t,channel:z,chatId:$==null?void 0:$.chatId,chatTitle:$==null?void 0:$.chatTitle,chatType:$==null?void 0:$.chatType,threadId:$==null?void 0:$.threadId}),[z,$,t]),E=c.useMemo(()=>DI(d),[d]),q=c.useCallback(async()=>{await M({title:"删除 Chat",description:`确认彻底删除 session「${t}」吗?该操作不可恢复。`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"})&&j()},[M,j,t]);return c.useEffect(()=>{P("route")},[t]),t?o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 xl:flex-row",children:[o.jsxs("section",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[22px] bg-background ring-1 ring-border/70 shadow-[0_1px_0_rgba(17,17,19,0.03)]",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 border-b border-border/55 px-4 py-4",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-base font-semibold text-foreground",title:I.value,children:I.value}),o.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",title:t,children:t}),o.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:`source: ${I.source}`})]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full bg-secondary px-2 py-1 text-[11px] text-muted-foreground",children:[o.jsx("span",{className:"font-mono",children:z}),o.jsx("span",{children:`${s.length} msgs`})]}),o.jsxs("div",{className:Me("inline-flex items-center gap-1 rounded-full px-2 py-1 text-[11px]",H?"bg-primary/12 text-primary":"bg-secondary text-muted-foreground"),children:[o.jsx("span",{className:Me("inline-flex size-1.5 rounded-full",H?"bg-primary":"bg-muted-foreground/60")}),o.jsx("span",{children:H?"executing":"idle"})]}),o.jsx($I,{state:R}),o.jsxs(yn,{children:[o.jsxs(vn,{render:o.jsx(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[11px] px-2.5 text-[11px]",disabled:y||h||x}),children:[o.jsx(kw,{className:"size-3.5"}),o.jsx("span",{children:"操作"})]}),o.jsxs(wn,{align:"end",className:"w-48",children:[o.jsx(bt,{disabled:h,onClick:v,children:h?"清理 context 中...":"清理 session messages"}),o.jsx(bt,{disabled:x,onClick:S,children:x?"清理 history 中...":"清理 chat history"}),o.jsx(Md,{}),o.jsx(bt,{variant:"destructive",disabled:y,onClick:()=>{q()},children:y?"删除中...":"删除 chat"})]})]})]})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:o.jsx(_I,{events:s,formatTime:w})}),o.jsxs("div",{className:"border-t border-border/55 px-4 py-4",children:[o.jsx(jf,{value:f,onChange:k=>b(k.target.value),onKeyDown:k=>{(k.metaKey||k.ctrlKey)&&k.key==="Enter"&&(k.preventDefault(),!(!N||m||!f.trim())&&p())},rows:3,placeholder:N?"输入发给 consoleui channel 的消息...":"当前 session 为只读,仅 consoleui channel 可发送",disabled:!N,className:"min-h-[84px] resize-y rounded-[14px] bg-secondary/85 text-[11px] focus-visible:bg-secondary"}),o.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[o.jsx("div",{className:"text-[11px] text-muted-foreground",children:N?"Cmd/Ctrl + Enter 发送":"只读模式"}),o.jsx(be,{onClick:p,disabled:!N||m||!f.trim(),children:m?"发送中...":"发送"})]})]})]}),g?null:o.jsxs("aside",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden rounded-[22px] bg-background ring-1 ring-border/70 shadow-[0_1px_0_rgba(17,17,19,0.03)] xl:w-[min(40%,560px)] xl:min-w-[340px]",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/55 px-4 py-4",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground",children:"details"}),o.jsxs("div",{className:"inline-flex rounded-[12px] bg-secondary p-0.5",children:[o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="route"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("route"),children:"route"}),o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="system"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("system"),children:"system"}),o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="context"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("context"),children:"context"}),o.jsx("button",{type:"button",className:Me("rounded-[10px] px-2 py-1 text-xs transition-colors",O==="archive"?"bg-background text-foreground":"text-muted-foreground hover:bg-background/70 hover:text-foreground"),onClick:()=>P("archive"),children:"archive"})]})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:O==="route"?o.jsx(LI,{routeJson:T}):O==="system"?o.jsx(BI,{blocks:E}):O==="context"?o.jsx(Fj,{items:a,formatTime:w}):o.jsx(PI,{archives:i,selectedArchiveId:l,archiveMessages:u,formatTime:w,onSelectArchive:A,onRefreshArchives:C})})]})]}):o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"请选择一个 context 进入工作区"})}function Kr(e,t){return e.some(n=>String(n.name||"").trim()===t)}function _u(e){const t=String(e.state||"").trim().toLowerCase();return t==="disabled"?"disabled":t==="available"?"enabled":"attention"}function A0(e){return _u(e)!=="disabled"}function HI(e){return e==="enabled"?{cardClass:"border-border/70 bg-background",badgeLabel:"Enabled",badgeClass:"bg-emerald-500/10 text-emerald-700",dotClass:"bg-emerald-600"}:e==="disabled"?{cardClass:"border-border/65 bg-[color-mix(in_oklab,var(--background)_96%,var(--secondary)_4%)]",badgeLabel:"Disabled",badgeClass:"bg-secondary text-muted-foreground",dotClass:"bg-muted-foreground/45"}:{cardClass:"border-amber-200/80 bg-[color-mix(in_oklab,var(--background)_95%,oklch(0.95_0.02_85)_5%)]",badgeLabel:"Setup required",badgeClass:"bg-amber-500/10 text-amber-700",dotClass:"bg-amber-500"}}function du(e){const{icon:t,label:n,loading:s,disabled:r=!1,tone:a="default",onClick:i}=e;return o.jsxs("button",{type:"button",onClick:i,disabled:r||s,className:`inline-flex h-8 items-center gap-1.5 rounded-full border border-transparent px-2.5 text-[12px] transition-colors disabled:pointer-events-none disabled:opacity-50 ${a==="danger"?"text-red-600 hover:border-red-200 hover:bg-red-50 hover:text-red-700":"text-muted-foreground hover:border-border/60 hover:bg-background hover:text-foreground"}`,children:[s?o.jsx(nt,{className:"size-3.5 animate-spin"}):t,o.jsx("span",{children:n})]})}function FI(e,t){const n=t&&typeof t=="object"?t:null,s=n!=null&&n.plugin&&typeof n.plugin=="object"?n.plugin:null,r=n!=null&&n.transcriber&&typeof n.transcriber=="object"?n.transcriber:null,a={...s||{},...r||{}},i={};for(const l of(e==null?void 0:e.fields)||[]){const u=a[l.key];if(l.type==="checkbox"){i[l.key]=u===!0;continue}if(typeof u=="string"&&u.trim()){i[l.key]=u.trim();continue}if(Array.isArray(l.options)&&l.options.length>0){i[l.key]=l.options[0].value;continue}i[l.key]=""}return i}function qI(e,t){const n=t&&typeof t=="object"?t:null,s=Array.isArray(n==null?void 0:n.options)?n.options:Array.isArray(n==null?void 0:n.models)?n.models:[],r=[];for(const a of s){const i=a&&typeof a=="object"?a:null,l=String((i==null?void 0:i.value)||(i==null?void 0:i.id)||"").trim();l&&r.push({label:String((i==null?void 0:i.label)||l).trim()||l,value:l,hint:String((i==null?void 0:i.hint)||(i==null?void 0:i.description)||"").trim()||void 0})}return r}function GI(e,t){const n={};for(const s of(e==null?void 0:e.fields)||[]){const r=t[s.key];if(s.type==="checkbox"){n[s.key]=r===!0;continue}typeof r=="string"&&r.trim()&&(n[s.key]=r.trim())}if((e==null?void 0:e.primaryAction)==="install"){const s=typeof n.modelId=="string"?n.modelId:"";s&&(n.modelIds=[s],n.activeModel=s)}return n}function VI(e,t){return e==="install"?t?"修复安装":"重新安装":e==="configure"?"保存配置":t?"修复并更新配置":"更新安装配置"}function YI(e,t){const n=t&&typeof t=="object"?t:null,s=n!=null&&n.plugin&&typeof n.plugin=="object"?n.plugin:n,r={};for(const a of(e==null?void 0:e.fields)||[]){const i=s==null?void 0:s[a.key];if(a.type==="boolean"){r[a.key]=i===!0;continue}if(typeof i=="string"&&i.trim()){r[a.key]=i.trim();continue}if(typeof i=="number"&&Number.isFinite(i)){r[a.key]=String(i);continue}if(Array.isArray(a.options)&&a.options.length>0){r[a.key]=a.options[0].value;continue}r[a.key]=""}return r}function KI(e,t){const n=t&&typeof t=="object"?t:null,s=Array.isArray(n==null?void 0:n.options)?n.options:Array.isArray(n==null?void 0:n.models)?n.models:[],r=[];for(const a of s){const i=a&&typeof a=="object"?a:null,l=String((i==null?void 0:i.value)||(i==null?void 0:i.id)||"").trim();l&&r.push({label:String((i==null?void 0:i.label)||l).trim()||l,value:l,description:String((i==null?void 0:i.description)||(i==null?void 0:i.hint)||"").trim()||void 0})}return r}function XI(e,t){const n={};for(const s of(e==null?void 0:e.fields)||[]){const r=t[s.key];if(s.type==="boolean"){n[s.key]=r===!0;continue}const a=typeof r=="string"?r.trim():"";if(a){if(s.type==="number"){const i=Number(a);Number.isFinite(i)&&(n[s.key]=i);continue}n[s.key]=a}}return n}function E0(e){var oe,pe;const{scope:t,plugins:n,onRunAction:s}=e,r=t==="agent"?e.hasRunningAgent:!1,a=t==="agent"?e.selectedAgentProjectId:void 0,i=Ls(),[l,u]=c.useState(""),[d,f]=c.useState({}),[g,m]=c.useState({}),[h,x]=c.useState({}),[y,w]=c.useState({}),[b,p]=c.useState({}),[v,S]=c.useState({}),[j,C]=c.useState({}),[A,M]=c.useState({}),[O,P]=c.useState(""),[$,z]=c.useState("");c.useEffect(()=>{m(_=>{let Y=!1;const le={..._};for(const ne of n){const ue=String(ne.name||"").trim();if(!ue)continue;const ae=le[ue];ae!==void 0&&ae===A0(ne)&&(delete le[ue],Y=!0)}return Y?le:_})},[n]);const N=c.useMemo(()=>{const _=l.trim().toLowerCase();return n.filter(Y=>_?String(Y.name||"").toLowerCase().includes(_)||String(Y.title||"").toLowerCase().includes(_)||String(Y.description||"").toLowerCase().includes(_):!0)},[n,l]),H=c.useMemo(()=>{let _=0,Y=0,le=0;for(const ne of N){const ue=_u(ne);ue==="enabled"?_+=1:ue==="disabled"?Y+=1:le+=1}return{enabled:_,disabled:Y,attention:le}},[N]),R=c.useMemo(()=>n.find(_=>String(_.name||"").trim()===O)||null,[n,O]),I=c.useMemo(()=>n.find(_=>String(_.name||"").trim()===$)||null,[n,$]),T=c.useCallback(async(_,Y,le,ne)=>{const ue=Date.now();f(ae=>({...ae,[_]:Y}));try{const ae=await s(_,le,ne);if(Array.isArray(ae==null?void 0:ae.logs)&&M(xe=>({...xe,[_]:ae.logs||[]})),Y==="toggle"){const xe=le==="on";ae.success&&m(W=>({...W,[_]:xe}));const ee=Date.now()-ue;ee<220&&await new Promise(W=>window.setTimeout(W,220-ee))}return ae}finally{f(ae=>({...ae,[_]:null}))}},[s]),E=c.useCallback(async _=>{var ue,ae,xe;const Y=String(_.name||"").trim(),le=Array.isArray((ue=_.config)==null?void 0:ue.actions)?(ae=_.config)==null?void 0:ae.actions:[],ne=(xe=_.config)==null?void 0:xe.setup;if(!(!Y||!ne)){if(ne.statusAction&&Kr(le,ne.statusAction)){const ee=await T(Y,"status",ne.statusAction);ee!=null&&ee.success&&w(W=>({...W,[Y]:{...W[Y]||{},...FI(ne,ee.data)}}))}for(const ee of ne.fields){if(!ee.sourceAction||!Kr(le,ee.sourceAction))continue;const W=await T(Y,"setupOptions",ee.sourceAction);if(!(W!=null&&W.success))continue;const X=qI(ee,W.data);p(G=>({...G,[Y]:{...G[Y]||{},[ee.key]:X}})),w(G=>{const L={...G[Y]||{}};return ee.type==="select"&&typeof L[ee.key]!="string"&&X.length>0&&(L[ee.key]=X[0].value),ee.type==="select"&&!L[ee.key]&&X.length>0&&(L[ee.key]=X[0].value),{...G,[Y]:L}})}}},[T]),q=c.useCallback(async _=>{var ue,ae,xe;const Y=String(_.name||"").trim(),le=Array.isArray((ue=_.config)==null?void 0:ue.actions)?(ae=_.config)==null?void 0:ae.actions:[],ne=(xe=_.config)==null?void 0:xe.usage;if(!(!Y||!ne)){if(ne.statusAction&&Kr(le,ne.statusAction)){const ee=await T(Y,"status",ne.statusAction);ee!=null&&ee.success&&S(W=>({...W,[Y]:{...W[Y]||{},...YI(ne,ee.data)}}))}for(const ee of ne.fields){if(!ee.sourceAction||!Kr(le,ee.sourceAction))continue;const W=await T(Y,"usageOptions",ee.sourceAction);if(!(W!=null&&W.success))continue;const X=KI(ee,W.data);C(G=>({...G,[Y]:{...G[Y]||{},[ee.key]:X}})),S(G=>{const L={...G[Y]||{}};return ee.type==="select"&&typeof L[ee.key]!="string"&&X.length>0&&(L[ee.key]=X[0].value),ee.type==="select"&&!L[ee.key]&&X.length>0&&(L[ee.key]=X[0].value),{...G,[Y]:L}})}}},[T]),k=c.useCallback(_=>{var le;const Y=String(_.name||"").trim();!Y||!((le=_.config)!=null&&le.setup)||(P(Y),M(ne=>({...ne,[Y]:[]})),E(_))},[E]),D=c.useCallback(()=>{P("")},[]),B=c.useCallback(_=>{var le;const Y=String(_.name||"").trim();!Y||!((le=_.config)!=null&&le.usage)||(z(Y),q(_))},[q]),Q=c.useCallback(()=>{z("")},[]),Z=c.useCallback((_,Y,le)=>{w(ne=>({...ne,[_]:{...ne[_]||{},[Y]:le}}))},[]),te=c.useCallback((_,Y,le)=>{S(ne=>({...ne,[_]:{...ne[_]||{},[Y]:le}}))},[]),se=c.useCallback(async()=>{var xe,ee;if(!((xe=R==null?void 0:R.config)!=null&&xe.setup))return;const _=String(R.name||"").trim(),Y=R.config.setup,le=y[_]||{},ne=GI(Y,le),ue=Y.primaryAction,ae=await T(_,"setup",ue,ne);(ee=ae==null?void 0:ae.logs)!=null&&ee.length||M(W=>({...W,[_]:[ae!=null&&ae.success?"操作完成":(ae==null?void 0:ae.message)||"操作失败"]})),Y.statusAction&&await E(R),D()},[D,T,R,y,E]),ie=c.useCallback(async()=>{var ue;if(!((ue=I==null?void 0:I.config)!=null&&ue.usage))return;const _=String(I.name||"").trim(),Y=I.config.usage,le=v[_]||{},ne=XI(Y,le);await T(_,"usage",Y.saveAction,ne),Y.statusAction&&await q(I),Q()},[Q,T,q,v,I]);return o.jsxs(o.Fragment,{children:[o.jsx(wt,{title:"Plugins",description:`enabled ${H.enabled} · disabled ${H.disabled}${H.attention>0?` · attention ${H.attention}`:""}`,bodyClassName:"min-h-0 overflow-y-auto",actions:o.jsxs("div",{className:"relative w-[220px]",children:[o.jsx(Wl,{className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{value:l,onChange:_=>u(_.target.value),placeholder:"搜索 plugin",className:"pl-9"})]}),children:t==="agent"&&!r&&N.length===0?o.jsx("div",{className:"rounded-[18px] border border-border/70 bg-secondary/45 px-4 py-6 text-sm text-muted-foreground",children:a?`${a} 当前未运行,Console UI 无法读取 runtime plugins。先启动 agent 再查看。`:"当前没有运行中的 agent,Console UI 无法读取 runtime plugins。先启动 agent 再查看。"}):N.length===0?o.jsx("div",{className:"rounded-[18px] border border-border/70 bg-secondary/45 px-4 py-6 text-sm text-muted-foreground",children:"当前没有匹配的 plugin。"}):o.jsx("div",{className:"space-y-3",children:N.map(_=>{var jt,Ct,zt,Ce,rt,et;const Y=String(_.name||"unknown").trim()||"unknown",le=String(_.title||Y).trim()||Y,ne=String(_.description||"").trim(),ue=Array.isArray((jt=_.config)==null?void 0:jt.actions)?(Ct=_.config)==null?void 0:Ct.actions:[],ae=(zt=_.config)==null?void 0:zt.setup,xe=(Ce=_.config)==null?void 0:Ce.usage,ee=_u(_),W=g[Y]??A0(_),X=d[Y]||null,G=X==="toggle",L=X==="status",J=X==="doctor",me=X==="setup",ge=X==="usage",U=X==="setupOptions",ce=X==="usageOptions",F=Kr(ue,"status"),K=Kr(ue,"doctor"),he=Kr(ue,"on"),Te=Kr(ue,"off"),Se=he||Te,Fe=HI(W?ee==="attention"?"attention":"enabled":"disabled"),Re=(Array.isArray((rt=_.availability)==null?void 0:rt.reasons)?(et=_.availability)==null?void 0:et.reasons:[]).map($e=>String($e||"").trim()).filter(Boolean).join(" · "),Ye=h[Y]===!0,yt=Array.isArray(_.pipelines)?_.pipelines:[],De=Array.isArray(_.guards)?_.guards:[],ot=Array.isArray(_.effects)?_.effects:[],_e=Array.isArray(_.resolves)?_.resolves:[],Je=ue.map($e=>String($e.name||"").trim()).filter(Boolean);return o.jsxs("article",{className:Me("rounded-[20px] border px-4 py-4 shadow-[0_1px_0_rgba(17,17,19,0.02)] transition-colors",Fe.cardClass),children:[o.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:Me("inline-flex size-2 rounded-full",Fe.dotClass)}),o.jsx("div",{className:"min-w-0 truncate text-[15px] font-semibold tracking-[-0.02em] text-foreground",children:le}),o.jsx("span",{className:"inline-flex h-6 items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-muted-foreground",children:Y}),o.jsx("span",{className:Me("inline-flex h-6 items-center rounded-full px-2.5 text-[11px]",Fe.badgeClass),children:Fe.badgeLabel})]}),ne?o.jsx("div",{className:"mt-2 max-w-3xl text-[13px] leading-6 text-foreground/70",children:ne}):null,Re?o.jsx("div",{className:"mt-3 text-[12px] leading-5 text-muted-foreground",children:Re}):null]}),o.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-1 rounded-full bg-secondary/70 p-1 lg:justify-end",children:[t==="global"&&ae?o.jsx(du,{icon:o.jsx(pd,{className:"size-3.5"}),label:ee==="attention"?"修复":"安装",loading:me||U,disabled:G||L||J||ge||ce,onClick:()=>k(_)}):null,t==="agent"&&xe?o.jsx(du,{icon:o.jsx(pd,{className:"size-3.5"}),label:"选项",loading:ge||ce,disabled:G||L||J||me||U,onClick:()=>B(_)}):null,t==="agent"&&F?o.jsx(du,{icon:o.jsx(xc,{className:"size-3.5"}),label:"同步",loading:L,disabled:G||J||me||U||ge||ce,onClick:()=>{T(Y,"status","status")}}):null,t==="global"&&Se?o.jsx(du,{icon:o.jsx(M5,{className:"size-3.5"}),label:W?"停用":"启用",loading:G,disabled:L||J||me||U||ge||ce,tone:W?"danger":"default",onClick:()=>{if((W?"off":"on")==="off"){(async()=>await i({title:"关闭 Plugin",description:`确认关闭 "${Y}"?`,confirmText:"关闭",confirmVariant:"destructive"})&&await T(Y,"toggle","off"))();return}T(Y,"toggle","on")}}):null,o.jsxs("button",{type:"button",className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-transparent px-2.5 text-[12px] text-muted-foreground transition-colors hover:border-border/60 hover:bg-background hover:text-foreground",onClick:()=>x($e=>({...$e,[Y]:!Ye})),children:[o.jsx(kr,{className:Me("size-3.5 transition-transform",Ye?"rotate-180":"")}),o.jsx("span",{children:Ye?"收起":"详情"})]})]})]}),Ye?o.jsx("div",{className:"mt-4 border-t border-border/60 pt-4",children:o.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto]",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.12em] text-muted-foreground",children:"Hooks"}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:[...yt,...De,...ot,..._e].length>0?o.jsxs(o.Fragment,{children:[yt.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`pipeline · ${$e}`},`${Y}:pipeline:${$e}`)),De.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`guard · ${$e}`},`${Y}:guard:${$e}`)),ot.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`effect · ${$e}`},`${Y}:effect:${$e}`)),_e.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:`resolve · ${$e}`},`${Y}:resolve:${$e}`))]}):o.jsx("span",{className:"text-[12px] text-muted-foreground",children:"未声明额外 hooks。"})})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.12em] text-muted-foreground",children:"Actions"}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:Je.length>0?Je.map($e=>o.jsx("span",{className:"inline-flex rounded-full bg-secondary px-2.5 py-1 font-mono text-[11px] text-foreground/82",children:$e},`${Y}:action:${$e}`)):o.jsx("span",{className:"text-[12px] text-muted-foreground",children:"未暴露额外 actions。"})})]})]}),t==="agent"&&K?o.jsx("div",{className:"flex items-start",children:o.jsxs(be,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-[12px] px-3",disabled:G||L||me||U||ge||ce,onClick:()=>{T(Y,"doctor","doctor")},children:[J?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(Ew,{className:"size-3.5"}),o.jsx("span",{children:"Doctor"})]})}):null]})}):null]},Y)})})}),o.jsx($n,{open:!!R,onOpenChange:_=>{_||D()},children:o.jsx(Un,{className:"w-[min(92vw,560px)] overflow-hidden border border-border/75 bg-background p-0 shadow-[0_24px_72px_rgba(17,17,19,0.12)]",children:(oe=R==null?void 0:R.config)!=null&&oe.setup?o.jsxs(o.Fragment,{children:[o.jsxs(Hn,{className:"border-b border-border/60 px-5 py-4",children:[o.jsx(Fn,{children:R.config.setup.title}),o.jsx(os,{className:"max-w-[40ch] text-[12px] leading-5 text-muted-foreground",children:R.config.setup.description||"使用统一 setup 流程完成插件安装或配置。"})]}),o.jsx("div",{className:"space-y-4 px-5 py-5",children:(()=>{var W,X,G;const _=String(R.name||"").trim(),Y=(W=R.config)==null?void 0:W.setup,le=d[_]==="setup"||d[_]==="status"||d[_]==="setupOptions",ne=_u(R),ue=Array.isArray((X=R.availability)==null?void 0:X.reasons)?(G=R.availability)==null?void 0:G.reasons:[],ae=y[_]||{},xe=b[_]||{},ee=A[_]||[];return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-[16px] bg-secondary/55 px-4 py-3",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:String(R.title||_)}),o.jsx("div",{className:"mt-1 text-[12px] leading-5 text-muted-foreground",children:ne==="attention"?ue.join(" · ")||"当前插件需要修复或补全运行环境。":"当前插件已可用,可在这里更新配置。"})]}),o.jsx("div",{className:"space-y-4",children:Y.fields.map(L=>{var ge,U,ce;if(L.type==="checkbox")return o.jsxs("label",{className:"flex items-center gap-2 rounded-[14px] bg-secondary/55 px-3 py-2 text-[12px] text-foreground",children:[o.jsx("input",{type:"checkbox",checked:ae[L.key]===!0,onChange:F=>Z(_,L.key,F.target.checked)}),o.jsx("span",{children:L.label})]},`${_}:field:${L.key}`);const J=Array.isArray(xe[L.key])&&xe[L.key].length>0?xe[L.key]:Array.isArray(L.options)?L.options:[],me=typeof ae[L.key]=="string"?String(ae[L.key]||""):((ge=J[0])==null?void 0:ge.value)||"";return o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{htmlFor:`${_}:${L.key}`,children:L.label}),o.jsx("select",{id:`${_}:${L.key}`,value:me,onChange:F=>Z(_,L.key,F.target.value),className:"flex h-10 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none transition-colors focus:border-ring",children:J.map(F=>o.jsx("option",{value:F.value,children:F.label},`${_}:${L.key}:${F.value}`))}),(U=J.find(F=>F.value===me))!=null&&U.hint?o.jsx("div",{className:"text-[12px] text-muted-foreground",children:(ce=J.find(F=>F.value===me))==null?void 0:ce.hint}):null]},`${_}:field:${L.key}`)})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-muted-foreground",children:"安装日志"}),o.jsxs("div",{className:"max-h-48 overflow-y-auto rounded-[14px] border border-border/70 bg-secondary/35 px-3 py-2 font-mono text-[11px] leading-5 text-foreground/82",children:[le?o.jsx("div",{children:"正在执行,请稍候..."}):null,ee.length>0?ee.map((L,J)=>o.jsx("div",{children:L},`${_}:log:${J}`)):le?null:o.jsx("div",{className:"text-muted-foreground",children:"执行完成后会在这里显示安装过程与错误信息。"})]})]}),o.jsxs(rs,{className:"border-t border-border/60 px-0 pt-4 sm:justify-end",children:[o.jsx(be,{type:"button",variant:"outline",onClick:D,disabled:le,children:"取消"}),o.jsxs(be,{type:"button",disabled:le||Y.fields.some(L=>{var J;return L.required!==!0||L.type==="checkbox"?!1:!String(((J=y[_])==null?void 0:J[L.key])||"").trim()}),onClick:()=>void se(),children:[le?o.jsx(nt,{className:"size-4 animate-spin"}):null,o.jsx("span",{children:VI(Y.mode,ne==="attention")})]})]})]})})()})]}):null})}),o.jsx($n,{open:!!I,onOpenChange:_=>{_||Q()},children:o.jsx(Un,{className:"w-[min(92vw,560px)] overflow-hidden border border-border/75 bg-background p-0 shadow-[0_24px_72px_rgba(17,17,19,0.12)]",children:(pe=I==null?void 0:I.config)!=null&&pe.usage?o.jsxs(o.Fragment,{children:[o.jsxs(Hn,{className:"border-b border-border/60 px-5 py-4",children:[o.jsx(Fn,{children:I.config.usage.title}),o.jsx(os,{className:"max-w-[40ch] text-[12px] leading-5 text-muted-foreground",children:I.config.usage.description||"配置当前 agent 如何使用这个 plugin。"})]}),o.jsx("div",{className:"space-y-4 px-5 py-5",children:(()=>{var ae;const _=String(I.name||"").trim(),Y=(ae=I.config)==null?void 0:ae.usage,le=d[_]==="usage"||d[_]==="status"||d[_]==="usageOptions",ne=v[_]||{},ue=j[_]||{};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-[16px] bg-secondary/55 px-4 py-3",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:String(I.title||_)}),o.jsx("div",{className:"mt-1 text-[12px] leading-5 text-muted-foreground",children:"这里修改的是 agent 运行时如何使用该 plugin,不负责依赖安装或资源修复。"})]}),o.jsx("div",{className:"space-y-4",children:Y.fields.map(xe=>{var X;const ee=Array.isArray(ue[xe.key])&&ue[xe.key].length>0?ue[xe.key]:Array.isArray(xe.options)?xe.options:[],W=xe.type==="boolean"?ne[xe.key]===!0:typeof ne[xe.key]=="string"?String(ne[xe.key]||""):((X=ee[0])==null?void 0:X.value)||"";return o.jsx(Pj,{field:{key:xe.key,label:xe.label,type:xe.type,placeholder:xe.placeholder,description:xe.description,required:xe.required,disabled:xe.disabled||le,trueLabel:xe.trueLabel,falseLabel:xe.falseLabel,options:ee.map(G=>({value:G.value,label:G.label,description:G.description}))},value:W,onChange:G=>te(_,xe.key,G)},`${_}:usage:${xe.key}`)})}),o.jsxs(rs,{className:"border-t border-border/60 px-0 pt-4 sm:justify-end",children:[o.jsx(be,{type:"button",variant:"outline",onClick:Q,disabled:le,children:"取消"}),o.jsxs(be,{type:"button",disabled:le||Y.fields.some(xe=>{var ee;return xe.required!==!0||xe.type==="boolean"?!1:!String(((ee=v[_])==null?void 0:ee[xe.key])||"").trim()}),onClick:()=>void ie(),children:[le?o.jsx(nt,{className:"size-4 animate-spin"}):null,o.jsx("span",{children:"保存选项"})]})]})]})})()})]}):null})})]})}function M0(e){return{projectRoot:"",agentId:"",executionType:e?"api":"acp",agentType:"kimi",modelId:e,localModel:""}}function $g(e){const t=String(e||"").trim().replace(/[\\/]+$/,"");if(!t)return"selected-folder";const n=t.split(/[\\/]/).filter(Boolean);return n[n.length-1]||t}function R0(e){if(e.executionMode==="api")return{executionType:"api",agentType:"kimi"};if(e.executionMode==="local")return{executionType:"local",agentType:"kimi"};const t=String(e.agentType||"").trim();return t==="claude"||t==="codex"?{executionType:"acp",agentType:t}:{executionType:"acp",agentType:"kimi"}}function ZI(e){return e.executionType==="api"?e.selectedModelLabel||"-":e.executionType==="local"?`Local · ${e.selectedLocalModelLabel||"-"}`:`ACP · ${e.agentType}`}function JI(e){return e.executionMode==="api"?String(e.modelId||"").trim()||"-":e.executionMode==="local"?`local ${String(e.localModel||"-").trim()||"-"}`:`acp ${String(e.agentType||"-").trim()||"-"}`}function QI(e,t){const n=new Set,s=String(t||"").trim();s&&n.add(s);for(const r of e){const a=String(r||"").trim();a&&n.add(a)}return Array.from(n)}const WI=c.forwardRef(function(t,n){const{agents:s,modelPoolItems:r,onPickAgentDirectory:a,onInspectAgentDirectory:i,onLoadLocalModels:l,onRestartAgent:u,onStopAgent:d,onStartAgent:f,onStartAgentWithInitialization:g}=t,m=Ls(),[h,x]=c.useState(""),[y,w]=c.useState(""),[b,p]=c.useState(""),[v,S]=c.useState(!1),[j,C]=c.useState(""),[A,M]=c.useState(!1),[O,P]=c.useState(!1),[$,z]=c.useState([]),[N,H]=c.useState(!1),R=c.useMemo(()=>r.filter(_=>_.isPaused!==!0),[r]),I=c.useMemo(()=>{var _,Y;return String(((_=R[0])==null?void 0:_.id)||((Y=r[0])==null?void 0:Y.id)||"").trim()},[R,r]),[T,E]=c.useState(()=>M0(I)),q=c.useCallback(()=>{S(!1),C(""),P(!1),z([]),H(!1),E(M0(I))},[I]),k=c.useCallback(async(_,Y)=>{try{H(!0);const le=await l(_);z(le);const ne=String(Y||"").trim();E(ue=>{const ae=String(ue.localModel||ne||le[0]||"").trim();return ae===ue.localModel?ue:{...ue,localModel:ae}})}finally{H(!1)}},[l]),D=c.useCallback(_=>{C(String(_.agentId||_.projectRoot||"").trim()),E({projectRoot:String(_.projectRoot||"").trim(),agentId:String(_.id||"").trim(),...R0({executionMode:_.executionMode,agentType:_.agentType}),modelId:String(_.modelId||I||"").trim(),localModel:String(_.localModel||"").trim()}),S(!0),k(String(_.projectRoot||"").trim(),String(_.localModel||"").trim())},[I,k]),B=c.useCallback(async()=>{try{M(!0);const _=await a();if(!_)return;const Y=await i(_);if(!Y)return;if(Y.initialized){try{x(Y.projectRoot),await Promise.resolve(f(Y.projectRoot))}finally{x("")}return}D({agentId:Y.knownAgent?Y.projectRoot:"",projectRoot:Y.projectRoot,id:Y.agentId,executionMode:Y.executionMode,modelId:Y.modelId,localModel:Y.localModel,agentType:Y.agentType})}finally{M(!1)}},[i,a,f,D]);c.useImperativeHandle(n,()=>({openFolder:B}),[B]),c.useEffect(()=>{E(_=>_.modelId||!I?_:{..._,modelId:I})},[I]);const Q=c.useCallback(async()=>{try{M(!0);const _=await a();if(!_)return;const Y=await i(_);if(!Y)return;if(Y.initialized){q();try{x(Y.projectRoot),await Promise.resolve(f(Y.projectRoot))}finally{x("")}return}E(le=>({...le,projectRoot:Y.projectRoot,agentId:Y.agentId||le.agentId,...R0({executionMode:Y.executionMode,agentType:Y.agentType}),modelId:String(Y.modelId||le.modelId||"").trim(),localModel:String(Y.localModel||le.localModel||"").trim()})),k(Y.projectRoot,String(Y.localModel||"").trim())}finally{M(!1)}},[i,a,f,k,q]);c.useEffect(()=>{v&&T.executionType==="local"&&(N||$.length>0||k(T.projectRoot,T.localModel))},[v,T.executionType,T.localModel,T.projectRoot,N,$.length,k]);const Z=!!String(T.projectRoot||"").trim()&&(T.executionType==="api"&&!!String(T.modelId||"").trim()&&R.length>0||T.executionType==="local"&&!!String(T.localModel||"").trim()||T.executionType==="acp"),te=String(T.agentId||"").trim()||$g(T.projectRoot),se=c.useMemo(()=>{const _=R.find(Y=>String(Y.id||"").trim()===String(T.modelId||"").trim());return String((_==null?void 0:_.name)||(_==null?void 0:_.id)||T.modelId||"").trim()},[R,T.modelId]),ie=String(T.localModel||"").trim(),oe=c.useMemo(()=>QI($,ie),[$,ie]),pe=ZI({executionType:T.executionType,agentType:T.agentType,selectedModelLabel:se,selectedLocalModelLabel:ie});return o.jsxs("section",{className:"min-h-0 overflow-y-auto",children:[s.length===0?o.jsx("div",{className:"rounded-[20px] bg-secondary px-4 py-5 text-sm text-muted-foreground",children:"暂无 agent,点击右上角打开文件夹"}):o.jsx("div",{className:"space-y-2",children:s.map(_=>{const Y=_.running===!0,le=JI(_),ne=h===_.id,ue=y===_.id,ae=b===_.id;return o.jsx("article",{className:Y?"rounded-[20px] bg-transparent px-4 py-3 transition-colors hover:bg-secondary":"rounded-[20px] bg-transparent px-4 py-3 text-muted-foreground opacity-58 transition-all hover:bg-secondary hover:opacity-78",children:o.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[o.jsx("div",{className:Y?"mt-0.5 rounded-full bg-emerald-500/12 p-2 text-emerald-700":"mt-0.5 rounded-full bg-secondary/80 p-2 text-muted-foreground",children:o.jsx(zp,{className:"size-4"})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:Y?"truncate text-[15px] font-semibold text-foreground":"truncate text-[15px] font-semibold text-foreground/72",children:_.agentId||"unknown-agent"}),o.jsx("div",{className:"truncate font-mono text-[11px] text-muted-foreground",children:_.id})]})]}),o.jsxs("div",{className:"flex flex-1 flex-wrap items-center gap-2 lg:justify-end",children:[o.jsx("span",{className:Y?"inline-flex h-7 max-w-full items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-foreground/86":"inline-flex h-7 max-w-full items-center rounded-full bg-secondary/75 px-2.5 font-mono text-[11px] text-foreground/62",children:le}),o.jsx("span",{className:Y?"inline-flex h-7 items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-muted-foreground":"inline-flex h-7 items-center rounded-full bg-secondary/75 px-2.5 font-mono text-[11px] text-muted-foreground",children:`pid ${Y?String(_.daemonPid||"-"):"-"}`}),o.jsx("span",{className:Y?"inline-flex h-7 items-center rounded-full bg-secondary px-2.5 font-mono text-[11px] text-muted-foreground":"inline-flex h-7 items-center rounded-full bg-secondary/75 px-2.5 font-mono text-[11px] text-muted-foreground",children:`port ${Y?String(_.port||"-"):"-"}`}),o.jsx("div",{className:"ml-auto flex items-center gap-1.5",children:Y?o.jsxs(o.Fragment,{children:[o.jsx(be,{size:"icon",variant:"ghost",className:Vn,onClick:async()=>{try{w(_.id),await Promise.resolve(u(_.id))}finally{w("")}},disabled:ue||ae,"aria-label":"重启",title:"重启",children:ue?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Ip,{className:"size-4"})}),o.jsx(be,{size:"icon",variant:"ghost",className:Ro,onClick:()=>{(async()=>{if(await m({title:"停止 Agent",description:`确认停止 "${_.agentId||"unknown-agent"}"?停止前会检查当前是否有正在执行的 context 和 task。`,confirmText:"停止",confirmVariant:"destructive"}))try{p(_.id),await Promise.resolve(d(_.id))}finally{p("")}})()},disabled:ue||ae,"aria-label":"停止",title:"停止",children:ae?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Dp,{className:"size-4"})})]}):o.jsx(be,{size:"icon",variant:"ghost",className:Vn,disabled:ne||ue||ae,"aria-label":"启动",title:"启动",onClick:async()=>{try{x(_.id),await Promise.resolve(f(_.id))}finally{x("")}},children:ne?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(sa,{className:"size-4"})})})]})]})},_.id)})}),o.jsx($n,{open:v,onOpenChange:_=>_?S(!0):q(),children:o.jsxs(Un,{className:"w-[min(92vw,640px)] overflow-hidden border border-border/80 bg-[linear-gradient(180deg,rgba(250,250,250,0.98),rgba(246,247,249,0.98))] p-0 shadow-[0_28px_90px_rgba(15,23,42,0.14)]",children:[o.jsxs(Hn,{className:"gap-3 border-b border-border/70 px-5 py-5 sm:px-6",children:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"mt-0.5 rounded-[16px] border border-foreground/8 bg-foreground/[0.03] p-2.5 text-foreground",children:o.jsx(Ym,{className:"size-4"})}),o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx(Fn,{className:"text-[1.05rem] font-semibold tracking-[0.01em]",children:"初始化并启动 Agent"}),o.jsx(os,{className:"max-w-[46ch] text-[12px] leading-5 text-muted-foreground",children:"当前文件夹还没有完成 Downcity 初始化。确认后会补齐运行骨架,再把它接入 Console。"})]})]}),o.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[o.jsxs("div",{className:"rounded-[18px] border border-border/75 bg-background/78 px-3 py-3",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:"Folder"}),o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-foreground",title:T.projectRoot||"-",children:$g(T.projectRoot)})]}),o.jsxs("div",{className:"rounded-[18px] border border-border/75 bg-background/78 px-3 py-3",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:"Agent ID"}),o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-foreground",title:te,children:te})]}),o.jsxs("div",{className:"rounded-[18px] border border-border/75 bg-background/78 px-3 py-3",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:"Execution"}),o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-foreground",title:pe||"-",children:pe||"-"})]})]})]}),o.jsxs("div",{className:"space-y-4 px-5 py-5 sm:px-6",children:[o.jsxs("div",{className:"rounded-[22px] border border-border/75 bg-background/82 p-4",children:[o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"Source Folder"}),o.jsx("div",{className:"mt-1 text-sm font-medium text-foreground",children:"选择要接入或编辑的项目目录"})]}),o.jsx("span",{className:"inline-flex items-center rounded-full border border-border/70 bg-secondary/75 px-2.5 py-1 text-[11px] text-muted-foreground",children:"step 1"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(lt,{id:"agent-project-root",value:T.projectRoot,placeholder:"请选择目录",readOnly:!0,disabled:!0,className:"h-11 rounded-[14px] border-border/80 bg-secondary/55 px-3 font-mono text-[12px] text-foreground/88"}),o.jsx(be,{type:"button",variant:"ghost",className:Vn,onClick:()=>void Q(),disabled:A,"aria-label":"选择目录",title:"选择目录",children:A?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(a5,{className:"size-4"})})]}),o.jsx("p",{className:"mt-3 text-[12px] leading-5 text-muted-foreground",children:"已初始化目录会直接启动;未初始化目录会自动补齐 `PROFILE.md`、`SOUL.md` 和 `downcity.json`。"})]}),o.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[o.jsxs("div",{className:"rounded-[22px] border border-border/75 bg-background/82 p-4",children:[o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"Identity"}),o.jsx("div",{className:"mt-1 text-sm font-medium text-foreground",children:"确认这个文件夹在 Console 里的 agent id"})]}),o.jsx("span",{className:"inline-flex items-center rounded-full border border-border/70 bg-secondary/75 px-2.5 py-1 text-[11px] text-muted-foreground",children:"step 2"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{htmlFor:"agent-id",className:"text-[12px] font-medium text-foreground/82",children:"Agent ID"}),o.jsx(lt,{id:"agent-id",value:T.agentId,placeholder:$g(T.projectRoot),className:"h-11 rounded-[14px] border-border/80 bg-background px-3 text-sm",onChange:_=>E(Y=>({...Y,agentId:_.target.value}))})]})]}),o.jsxs("div",{className:"rounded-[22px] border border-border/75 bg-background/82 p-4",children:[o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"Execution"}),o.jsx("div",{className:"mt-1 text-sm font-medium text-foreground",children:"统一选择 api、local 或 acp"})]}),o.jsx("span",{className:"inline-flex items-center rounded-full border border-border/70 bg-secondary/75 px-2.5 py-1 text-[11px] text-muted-foreground",children:"step 3"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(qt,{htmlFor:"agent-runtime",className:"text-[12px] font-medium text-foreground/82",children:"执行模式"}),o.jsxs("select",{id:"agent-runtime",className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",value:T.executionType,onChange:_=>E(Y=>({...Y,executionType:_.target.value})),children:[o.jsx("option",{value:"api",children:"API"}),o.jsx("option",{value:"acp",children:"ACP"}),o.jsx("option",{value:"local",children:"Local"})]})]}),T.executionType==="api"?o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx(qt,{htmlFor:"agent-model",className:"text-[12px] font-medium text-foreground/82",children:"模型 ID"}),o.jsxs("select",{id:"agent-model",className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",value:T.modelId,onChange:_=>E(Y=>({...Y,modelId:_.target.value})),disabled:R.length===0,children:[R.length===0?o.jsx("option",{value:"",children:"请先在 Global / Model 创建可用模型"}):null,R.map(_=>o.jsx("option",{value:_.id,children:String(_.id||"").trim()},_.id))]})]}):T.executionType==="local"?o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx(qt,{htmlFor:"agent-local-model",className:"text-[12px] font-medium text-foreground/82",children:"GGUF 文件名"}),o.jsxs("select",{id:"agent-local-model",value:T.localModel,className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 font-mono text-[12px] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",onChange:_=>E(Y=>({...Y,localModel:_.target.value})),disabled:N||oe.length===0,children:[oe.length===0?o.jsx("option",{value:"",children:N?"正在读取本地模型":"没有发现本地 GGUF 模型"}):null,oe.map(_=>o.jsx("option",{value:_,children:_},_))]}),o.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:"直接选择已安装模型;默认扫描 `~/.models`,若项目配置了 `plugins.lmp.modelsDir` 会优先使用该目录。"})]}):T.executionType==="acp"?o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx(qt,{htmlFor:"agent-acp-type",className:"text-[12px] font-medium text-foreground/82",children:"Coding Agent"}),o.jsxs("select",{id:"agent-acp-type",className:"flex h-11 w-full rounded-[14px] border border-input bg-background px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",value:T.agentType,onChange:_=>E(Y=>({...Y,agentType:_.target.value})),children:[o.jsx("option",{value:"kimi",children:"Kimi"}),o.jsx("option",{value:"claude",children:"Claude"}),o.jsx("option",{value:"codex",children:"Codex"})]})]}):o.jsx(o.Fragment,{})]})]}),o.jsxs("div",{className:"rounded-[20px] border border-dashed border-border/85 bg-secondary/45 px-4 py-3",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"What Will Be Written"}),o.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[12px] text-foreground/78",children:[o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`downcity.json.execution`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`downcity.json.plugins.lmp`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`PROFILE.md`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`SOUL.md`"}),o.jsx("span",{className:"rounded-full bg-background/85 px-2.5 py-1",children:"`.downcity/*`"})]})]})]}),o.jsxs(rs,{className:"border-t border-border/70 bg-background/74 px-5 py-4 sm:px-6 sm:justify-end",children:[o.jsx(be,{type:"button",variant:"ghost",onClick:q,disabled:O,children:"取消"}),o.jsx(be,{type:"button",disabled:!Z||O,className:"min-w-[8.5rem] rounded-[14px] bg-foreground px-4 text-background hover:bg-foreground/92",onClick:async()=>{try{P(!0);const _=T.executionType==="api"?{executionMode:"api",modelId:T.modelId.trim()}:T.executionType==="local"?{executionMode:"local",localModel:T.localModel.trim()}:{executionMode:"acp",agentType:T.agentType};await Promise.resolve(g(j||T.projectRoot.trim(),{id:T.agentId.trim()||void 0,..._})),q()}finally{P(!1)}},children:O?o.jsx(nt,{className:"size-4 animate-spin"}):"初始化并启动"})]})]})})]})});function O0(e){const{cityVersion:t,agents:n,modelPoolItems:s,plugins:r,configStatus:a,onPickAgentDirectory:i,onInspectAgentDirectory:l,onLoadLocalModels:u,onStartAgent:d,onStartAgentWithInitialization:f,onRestartAgent:g,onStopAgent:m}=e,h=c.useRef(null),[x,y]=c.useState(!1),w=c.useCallback(async()=>{if(h.current){y(!0);try{await h.current.openFolder()}finally{y(!1)}}},[]),b=new Set(["ship_db","console_pid","agents_registry"]),p=a.filter(N=>N.scope==="console"),v=p.filter(N=>b.has(N.key)),S=p.filter(N=>!b.has(N.key)&&N.status==="missing").length,j=v.filter(N=>N.status!=="ok"),C=r.filter(N=>String(N.state||"").toLowerCase()==="unavailable").length,A=v.length-j.length,O=j.length===0?S>0?"warning":"ok":"error",P=[...p.filter(N=>N.status!=="ok").map(N=>({key:`config:${N.key}`,source:b.has(N.key)?"required config":"optional config",name:N.label,state:N.status,detail:N.reason||N.path})),...r.filter(N=>String(N.state||"").toLowerCase()==="unavailable").map(N=>({key:`plugin:${String(N.name||"unknown")}`,source:"plugin",name:String(N.name||"unknown"),state:String(N.state||"unavailable"),detail:String(N.lastError||"").trim()||"-"}))],$=Array.from(new Map(P.map(N=>[N.key,N])).values()),z=$.length;return o.jsxs("section",{className:"space-y-5",children:[o.jsx(wt,{title:"Global Summary",description:"当前全局运行态与异常信号概览。",children:o.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`dc ${String(t||"-")}`}),o.jsx("span",{className:O==="ok"?"inline-flex items-center rounded-full bg-emerald-500/12 px-2 py-1 text-emerald-700":O==="warning"?"inline-flex items-center rounded-full bg-secondary px-2 py-1 text-foreground":"inline-flex items-center rounded-full bg-destructive/10 px-2 py-1 text-destructive",children:`config ${A}/${v.length}`}),S>0?o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`optional missing ${S}`}):null,o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`plugin unavailable ${C}`}),o.jsx("span",{className:"inline-flex items-center rounded-full bg-secondary px-2 py-1",children:`signals ${z}`})]})}),o.jsx(wt,{title:"Agent Runtime",description:`共 ${n.length} 个 agent,可直接在此启动、重启或停止。`,actions:o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:Vn,onClick:()=>void w(),disabled:x,"aria-label":"打开文件夹",title:"打开文件夹",children:x?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(fa,{className:"size-4"})}),children:o.jsx(WI,{ref:h,agents:n,modelPoolItems:s,onPickAgentDirectory:i,onInspectAgentDirectory:l,onLoadLocalModels:u,onStartAgent:d,onStartAgentWithInitialization:f,onRestartAgent:g,onStopAgent:m})}),o.jsx(wt,{title:"Signals",description:$.length===0?"当前没有异常信号。":`共 ${$.length} 条异常信号。`,className:"shadow-[0_1px_0_rgba(17,17,19,0.02)]",children:$.length===0?o.jsx("div",{className:"py-2 text-sm text-muted-foreground",children:"没有异常信号"}):o.jsx("div",{className:"space-y-1",children:$.map(N=>o.jsxs("div",{className:"rounded-[16px] bg-destructive/8 px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 text-sm",children:[o.jsx("span",{className:"font-medium text-foreground",children:N.name}),o.jsx("span",{className:"text-[11px] uppercase tracking-[0.1em] text-muted-foreground",children:N.source}),o.jsx("span",{className:"text-xs text-destructive",children:N.state})]}),o.jsx("div",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:N.detail,children:N.detail})]},N.key))})})]})}function e7(e){const{logs:t,formatTime:n}=e,s=t.length===0?"暂无日志":t.map(r=>{const a=n(r.timestamp),i=String(r.type||r.level||"info").toUpperCase(),l=String(r.message||"");return`[${a}] [${i}] ${l}`}).join(`
|
|
424
|
+
`);return o.jsx(wt,{title:"Recent Logs",description:`最近 ${t.length} 条日志输出。`,bodyClassName:"gap-0",children:o.jsx("div",{className:"overflow-hidden rounded-[20px] bg-secondary/85",children:o.jsx("pre",{className:"max-h-[68vh] overflow-auto px-4 py-4 font-mono text-[11px] leading-relaxed text-foreground/88",children:s})})})}function z0(e){const t=String(e||"").trim().toLowerCase();return t?t==="project"||t==="home"||t==="external"?t:"other":"unknown"}function Fo(e){return o.jsx("span",{className:e.tone==="strong"?"inline-flex h-6 items-center rounded-full bg-background px-2.5 text-[11px] text-foreground":"inline-flex h-6 items-center rounded-full bg-background/80 px-2.5 text-[11px] text-muted-foreground",children:e.children})}function t7(e){const{skills:t,loading:n,selectedAgentId:s,onRefreshSkills:r,onFindSkill:a,onInstallSkill:i}=e,[l,u]=c.useState(""),[d,f]=c.useState(""),[g,m]=c.useState(""),[h,x]=c.useState(!1),[y,w]=c.useState(!0),[b,p]=c.useState(!0),[v,S]=c.useState("claude-code"),[j,C]=c.useState(""),[A,M]=c.useState(null),O=!!String(s||"").trim(),P=l.trim().toLowerCase(),$=c.useMemo(()=>P?t.filter(R=>{const I=String(R.id||"").toLowerCase(),T=String(R.name||"").toLowerCase(),E=String(R.description||"").toLowerCase(),q=String(R.source||"").toLowerCase(),k=String(R.skillMdPath||"").toLowerCase(),D=Array.isArray(R.allowedTools)?R.allowedTools.join(" ").toLowerCase():"";return I.includes(P)||T.includes(P)||E.includes(P)||q.includes(P)||k.includes(P)||D.includes(P)}):t,[P,t]),z=c.useMemo(()=>{const R={project:0,home:0,external:0,other:0};for(const I of $){const T=z0(String(I.source||""));R[T]+=1}return R},[$]),N=c.useCallback(async()=>{const R=String(d||"").trim();if(R)try{C("find");const I=await a(R);M({title:"Find",message:(I==null?void 0:I.message)||`已执行 find: ${R}`,nextAction:I==null?void 0:I.nextAction,workflow:I==null?void 0:I.workflow})}finally{C("")}},[d,a]),H=c.useCallback(async()=>{const R=String(g||"").trim();if(R)try{C("install");const I=await i({spec:R,global:y,yes:b,agent:String(v||"").trim()||"claude-code"});M({title:"Install",message:(I==null?void 0:I.message)||`已执行 install: ${R}`,nextAction:I==null?void 0:I.nextAction,workflow:I==null?void 0:I.workflow})}finally{C("")}},[v,y,g,b,i]);return o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Skills",actions:o.jsxs(o.Fragment,{children:[o.jsx(Fo,{tone:"strong",children:`total ${$.length}`}),o.jsx(Fo,{children:`project ${z.project}`}),o.jsx(Fo,{children:`home ${z.home}`}),o.jsx(Fo,{children:`external ${z.external}`}),o.jsxs("div",{className:"relative",children:[o.jsx(Wl,{className:"pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"}),o.jsx(lt,{value:l,onChange:R=>u(R.target.value),placeholder:"搜索 skills",className:"w-[220px] pl-8"})]}),o.jsx(be,{size:"sm",variant:"outline",disabled:n||!O,onClick:()=>void r(),children:o.jsx(xc,{className:`size-3.5 ${n?"animate-spin":""}`})})]}),children:$.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary/85 px-4 py-8 text-sm text-muted-foreground",children:P?"没有匹配的 skills。":"暂无 skills。"}):o.jsx("div",{className:"space-y-2",children:$.map(R=>{const I=String(R.id||"unknown"),T=String(R.name||"unknown"),E=z0(String(R.source||"")),q=String(R.description||"").trim(),k=Array.isArray(R.allowedTools)?R.allowedTools:[],D=String(R.skillMdPath||"").trim()||"-",B=[E,k.length>0?k.join(", "):"no tools"].filter(Boolean).join(" · ");return o.jsx("div",{className:"group rounded-[14px] bg-transparent px-3 py-3 transition-colors hover:bg-secondary",children:o.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between",children:[o.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:T}),o.jsx("span",{className:"inline-flex h-5 items-center rounded-full bg-background px-2 text-[11px] text-muted-foreground",children:E})]}),o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:I}),q?o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:q}):null]}),o.jsxs("div",{className:"min-w-0 text-left lg:max-w-[42rem] lg:text-right",children:[o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:B}),o.jsx("div",{className:"truncate font-mono text-[11px] text-muted-foreground/90",title:D,children:D})]})]})},`${E}:${I}`)})})}),o.jsx(wt,{title:"Find / Install",actions:o.jsxs(o.Fragment,{children:[o.jsx(Fo,{children:`global ${String(y)}`}),o.jsx(Fo,{children:`yes ${String(b)}`}),o.jsx(Fo,{children:`agent ${String(v||"claude-code")}`}),o.jsx(be,{size:"sm",variant:"outline",onClick:()=>x(!0),children:o.jsx(pd,{className:"size-3.5"})})]}),children:o.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"mb-2 text-xs uppercase tracking-[0.12em] text-muted-foreground",children:"Find"}),o.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[o.jsx(lt,{value:d,onChange:R=>f(R.target.value),placeholder:"例如 playwright",className:"flex-1"}),o.jsx(be,{variant:"outline",className:"sm:min-w-24",disabled:!O||j==="install"||j==="find",onClick:()=>void N(),children:j==="find"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Wl,{className:"size-4"})})]})]})}),o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"mb-2 text-xs uppercase tracking-[0.12em] text-muted-foreground",children:"Install"}),o.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[o.jsx(lt,{value:g,onChange:R=>m(R.target.value),placeholder:"例如 owner/repo@playwright",className:"flex-1"}),o.jsx(be,{variant:"outline",className:"sm:min-w-24",disabled:!O||j==="install"||j==="find",onClick:()=>void H(),children:j==="install"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Ew,{className:"size-4"})})]})]})})]})}),o.jsx(wt,{title:"Action Report",children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:A?o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3 text-sm",children:[o.jsx("div",{className:"text-foreground",children:A.title}),o.jsx("div",{className:"mt-1 text-muted-foreground",children:A.message}),A.nextAction?o.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:`next · ${A.nextAction}`}):null,Array.isArray(A.workflow)&&A.workflow.length>0?o.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:`workflow · ${A.workflow.join(" -> ")}`}):null]}):o.jsx("div",{className:"rounded-[14px] bg-transparent px-3 py-6 text-sm text-muted-foreground",children:"暂无动作反馈"})})}),o.jsx($n,{open:h,onOpenChange:x,children:o.jsxs(Un,{className:"w-[min(92vw,520px)]",children:[o.jsxs(Hn,{children:[o.jsx(Fn,{children:"Install 配置"}),o.jsx(os,{children:"设置 `city skill install` 的默认参数。配置会用于当前页面的 Install 操作。"})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("div",{className:"text-xs font-medium text-foreground",children:"Agent"}),o.jsx(lt,{value:v,onChange:R=>S(R.target.value),placeholder:"claude-code"})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(be,{type:"button",variant:y?"default":"outline",size:"sm",onClick:()=>w(R=>!R),children:`global: ${y?"on":"off"}`}),o.jsx(be,{type:"button",variant:b?"default":"outline",size:"sm",onClick:()=>p(R=>!R),children:`yes: ${b?"on":"off"}`})]})]}),o.jsx(rs,{children:o.jsx(be,{variant:"outline",onClick:()=>x(!1),children:"完成"})})]})})]})}function n7(e){const t=String(e||"").trim();if(!t)return"-";const n=t.match(/^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-(\d{3})$/);if(!n)return t;const[,s,r,a,i,l,u,d]=n,f=new Date(Number(s),Number(r)-1,Number(a),Number(i),Number(l),Number(u),Number(d));if(Number.isNaN(f.getTime()))return t;const g=f.toLocaleString("zh-CN",{hour12:!1}),m=Date.now()-f.getTime();return Number.isFinite(m)?m<6e4?`${g} · 刚刚`:m<36e5?`${g} · ${Math.floor(m/6e4)} 分钟前`:m<864e5?`${g} · ${Math.floor(m/36e5)} 小时前`:`${g} · ${Math.floor(m/864e5)} 天前`:g}function Ba(e){return o.jsx("div",{className:"truncate text-sm text-foreground",title:e.value,children:e.value})}function Pa(e){const t=e.tone==="success"?"bg-emerald-500/8 text-emerald-700":e.tone==="danger"?"bg-destructive/8 text-destructive":"bg-background/80 text-muted-foreground";return o.jsx("span",{className:`inline-flex h-6 items-center rounded-full px-2.5 text-[11px] ${t}`,children:e.children})}function s7(e){return e.action==="start"||e.action==="resume"?o.jsx(sa,{className:"size-3.5"}):e.action==="pause"?o.jsx(Nw,{className:"size-3.5"}):e.action==="restart"?o.jsx(Ip,{className:"size-3.5"}):o.jsx(Dp,{className:"size-3.5"})}function r7(e){if(e.executionMode==="api"||!e.executionMode)return{executionType:"api",agentType:"kimi"};if(e.executionMode==="local")return{executionType:"local",agentType:"kimi"};const t=String(e.agentType||"").trim();return t==="claude"||t==="codex"?{executionType:"acp",agentType:t}:{executionType:"acp",agentType:"kimi"}}function o7(e){return e.executionType==="api"?"api":e.executionType==="local"?"local":`acp ${e.agentType}`}function a7(e,t){const n=new Set,s=String(t||"").trim();s&&n.add(s);for(const r of e){const a=String(r||"").trim();a&&n.add(a)}return Array.from(n)}function i7(e){var me,ge;const{selectedAgent:t,overview:n,services:s,skills:r,tasks:a,sessions:i,channelAccounts:l,consoleUiSessionId:u,configStatus:d,model:f,onLoadLocalModels:g,onUpdateExecution:m,onStartAgent:h,onRestartAgent:x,onStopAgent:y,onOpenTask:w,onOpenSession:b,onControlService:p,chatChannels:v,onChatAction:S}=e,j=Ls(),A=(Array.isArray((me=n==null?void 0:n.sessions)==null?void 0:me.items)?n.sessions.items:[]).some(U=>U.sessionId===u),M=Array.isArray(t==null?void 0:t.chatProfiles)?t.chatProfiles:[],O=c.useMemo(()=>i.filter(U=>U.executing===!0),[i]),P=O.length>0,$=d.filter(U=>U.scope==="agent"),z=$.filter(U=>String(U.status||"").toLowerCase()!=="ok"),N=$.filter(U=>{const ce=String(U.key||"").toLowerCase(),F=String(U.label||"").toLowerCase(),K=String(U.path||"").toLowerCase();return ce.includes("memory")||F.includes("memory")||K.includes("/memory")}),H=Array.isArray(f==null?void 0:f.availableModels)?f.availableModels:[],R=String((f==null?void 0:f.agentPrimaryModelId)||(f==null?void 0:f.primaryModelId)||(t==null?void 0:t.modelId)||"").trim(),I=String(((ge=H[0])==null?void 0:ge.id)||"").trim(),T=R||I,E=String((t==null?void 0:t.localModel)||"").trim(),q=r7({executionMode:t==null?void 0:t.executionMode,agentType:t==null?void 0:t.agentType}),[k,D]=c.useState(T),[B,Q]=c.useState(E),[Z,te]=c.useState(q.executionType),[se,ie]=c.useState(q.agentType),[oe,pe]=c.useState([]),[_,Y]=c.useState(!1),[le,ne]=c.useState(""),[ue,ae]=c.useState({});c.useEffect(()=>{D(T)},[T]),c.useEffect(()=>{te(q.executionType),ie(q.agentType)},[q]),c.useEffect(()=>{Q(E)},[E]),c.useEffect(()=>{if(!t)return;let U=!1;return(async()=>{try{Y(!0);const ce=await g(t.projectRoot||t.id);if(U)return;pe(ce)}finally{U||Y(!1)}})(),()=>{U=!0}},[g,t]);const xe=c.useMemo(()=>a7(oe,B||E),[E,oe,B]),ee=c.useCallback(U=>!!ue[U],[ue]),W=c.useMemo(()=>{const U=new Map;for(const ce of v){const F=String(ce.channel||"").trim().toLowerCase();if(!F)continue;const K=ce.detail,he=K&&typeof K=="object"&&!Array.isArray(K)?K:null,Te=he!=null&&he.config&&typeof he.config=="object"&&!Array.isArray(he.config)?he.config:null;U.set(F,{enabled:ce.enabled,configured:ce.configured,channelAccountId:String((Te==null?void 0:Te.channelAccountId)||"").trim()})}return U},[v]),X=c.useMemo(()=>{const U=new Map;for(const ce of l){const F=String(ce.id||"").trim();if(!F)continue;const K=String(ce.name||ce.id||"").trim()||F;U.set(F,K)}return U},[l]),G=c.useMemo(()=>{const U=["chat","task","skill","memory","context"],ce=new Map;for(const K of s){const he=String(K.name||"").trim().toLowerCase();he&&(ce.has(he)||ce.set(he,K))}const F=U.map(K=>{const he=ce.get(K);return he||{name:K,state:"stopped"}});for(const[K,he]of ce.entries())U.includes(K)||F.push(he);return F},[s]),L=c.useCallback(U=>{const ce=String(U||"").trim().toLowerCase();if(!ce)return"";const F=i.map(K=>String(K.sessionId||"").trim()).filter(K=>K.startsWith(`${ce}-`));return F.length===0?"":F[0]||""},[i]),J=c.useCallback(U=>{const ce=String(U||"").trim().toLowerCase();return ce==="running"?["pause","restart","stop"]:ce==="paused"?["resume","restart","stop"]:ce==="stopped"||ce==="idle"||ce==="unknown"?["start","restart"]:["start","restart","stop"]},[]);return t?o.jsxs("section",{className:"space-y-4",children:[o.jsx(wt,{title:"Agent",actions:o.jsxs(o.Fragment,{children:[o.jsx(Pa,{tone:t.running?"success":"default",children:t.running?"running":"stopped"}),o.jsx(Pa,{tone:P?"success":"default",children:P?`executing ${O.length}`:"idle"}),t.running?o.jsxs(o.Fragment,{children:[o.jsx(be,{size:"icon",variant:"ghost",className:Vn,onClick:()=>{ne("restart"),Promise.resolve(x()).finally(()=>ne(""))},disabled:le!=="",children:le==="restart"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Ip,{className:"size-4"})}),o.jsx(be,{size:"icon",variant:"ghost",className:Ro,onClick:()=>{(async()=>await j({title:"停止 Agent",description:`确认停止 "${t.agentId||"unknown-agent"}"?`,confirmText:"停止",confirmVariant:"destructive"})&&(ne("stop"),Promise.resolve(y()).finally(()=>ne(""))))()},disabled:le!=="",children:le==="stop"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(Dp,{className:"size-4"})})]}):o.jsx(be,{size:"icon",variant:"ghost",className:Vn,onClick:()=>{ne("start"),Promise.resolve(h()).finally(()=>ne(""))},disabled:le!=="",children:le==="start"?o.jsx(nt,{className:"size-4 animate-spin"}):o.jsx(sa,{className:"size-4"})})]}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:o.jsxs("div",{className:"min-w-0 flex items-start gap-3",children:[o.jsx("img",{src:"/image.png",alt:"bot",className:"size-9 shrink-0 rounded-[6px] object-cover"}),o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx("div",{className:"truncate text-base font-medium text-foreground",children:t.agentId||"-"}),o.jsx("div",{className:"truncate text-sm text-muted-foreground",children:t.projectRoot||t.id||"-"})]})]})}),o.jsxs("div",{className:"mt-4 grid gap-x-8 md:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Ba,{value:String((n==null?void 0:n.cityVersion)||"-")}),o.jsx(Ba,{value:String(t.daemonPid||"-")}),o.jsx(Ba,{value:String(t.host||"-")})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Ba,{value:t.port?String(t.port):"-"}),o.jsx(Ba,{value:String(t.projectRoot||"-")}),o.jsx(Ba,{value:String(t.id||"-")})]})]})]})})}),o.jsx(wt,{title:"Execution",actions:o.jsxs(o.Fragment,{children:[o.jsx(Pa,{children:o7(q)}),o.jsx(Pa,{children:`available ${H.length}`})]}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3",children:[o.jsx("div",{className:"grid gap-3 md:grid-cols-1",children:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium"}),children:o.jsx("span",{className:"truncate",children:Z==="api"?"API":Z==="local"?"Local":"ACP"})}),o.jsxs(wn,{className:"max-h-72 min-w-[20rem]",children:[o.jsx(bt,{onClick:()=>{te("api"),T&&(D(T),!(q.executionType==="api"&&T===R)&&m({executionMode:"api",modelId:T}))},children:"API"}),o.jsx(bt,{onClick:()=>{te("local");const U=String(B||E||xe[0]||"").trim();U&&(q.executionType==="local"&&U===E||m({executionMode:"local",localModel:U}))},children:"Local"}),o.jsx(bt,{onClick:()=>{te("acp"),ie(q.agentType);const U=q.agentType||"kimi";q.executionType==="acp"&&q.agentType===U||m({executionMode:"acp",agentType:U})},children:"ACP"})]})]})}),Z==="api"?o.jsx("div",{className:"mt-3 grid gap-3 md:grid-cols-1",children:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium"}),children:o.jsx("span",{className:"truncate",children:k||"选择 execution.modelId"})}),o.jsx(wn,{className:"max-h-72 min-w-[20rem]",children:H.length===0?o.jsx(bt,{disabled:!0,children:"无可选模型"}):H.map(U=>{const ce=String(U.id||"").trim();return ce?o.jsx(bt,{onClick:()=>{const F=String(ce||"").trim();D(F),!(!F||q.executionType==="api"&&F===R)&&m({executionMode:"api",modelId:F})},children:`${ce} · ${U.providerType||"-"}${U.isPaused?" · paused":""}`},ce):null})})]})}):Z==="local"?o.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[o.jsxs("select",{value:B,className:"flex h-9 flex-1 rounded-[12px] border border-input bg-background px-3 font-mono text-[12px] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",onChange:U=>Q(U.target.value),disabled:_||xe.length===0,children:[xe.length===0?o.jsx("option",{value:"",children:_?"正在读取本地模型":"没有发现本地 GGUF 模型"}):null,xe.map(U=>o.jsx("option",{value:U,children:U},U))]}),o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 rounded-[12px] bg-background px-3 text-xs",disabled:!String(B||"").trim()||_,onClick:()=>{const U=String(B||"").trim();U&&(q.executionType==="local"&&U===E||m({executionMode:"local",localModel:U}))},children:"应用"})]}):Z==="acp"?o.jsx("div",{className:"mt-3 grid gap-3 md:grid-cols-1",children:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{variant:"ghost",size:"sm",className:"h-9 justify-start rounded-[12px] bg-background px-3 text-left text-sm font-medium"}),children:o.jsx("span",{className:"truncate",children:`ACP · ${se}`})}),o.jsx(wn,{className:"max-h-72 min-w-[20rem]",children:["kimi","claude","codex"].map(U=>o.jsx(bt,{onClick:()=>{ie(U),!(q.executionType==="acp"&&q.agentType===U)&&m({executionMode:"acp",agentType:U})},children:`ACP · ${U}`},U))})]})}):null]})})}),G.map((U,ce)=>{const F=String(U.name||U.service||`service-${ce}`).trim().toLowerCase(),K=F==="skill"?"skills":F,he=String(U.state||U.status||"unknown").trim().toLowerCase(),Te=J(he),Ae=he==="error"||he==="failed"?"danger":he==="running"?"success":"default",Re=F.includes("task"),Ye=F.includes("chat"),yt=F.includes("skill"),De=F.includes("memory"),ot=F.includes("context"),_e=Ye?M.map(Ce=>{const rt=String(Ce.channel||"-"),et=String(Ce.linkState||Ce.statusText||"unknown"),$e=L(rt),Ht=W.get(rt.trim().toLowerCase()),zn=String((Ht==null?void 0:Ht.channelAccountId)||"").trim(),ms=zn?String(X.get(zn)||zn):"no binding";return{channel:rt,link:et,sessionId:$e,clickable:!!$e,enabled:(Ht==null?void 0:Ht.enabled)===!0,configured:(Ht==null?void 0:Ht.configured)===!0,accountName:ms}}):[],Je=Re?a.slice(0,5):[],jt=yt?r.slice(0,5):[],Ct=ot?i.slice(0,5).map(Ce=>String(Ce.sessionId||"-")):[],zt=De?N.length>0?N.map(Ce=>`${Ce.label} · ${Ce.status}`):["无 memory 配置"]:ot&&Ct.length===0?[`consoleui · ${A?"ok":"missing"}`]:!Re&&!Ye&&!yt&&!ot?["无额外明细"]:[];return o.jsx(wt,{title:K,actions:o.jsxs(o.Fragment,{children:[o.jsx(Pa,{tone:Ae,children:he||"-"}),o.jsx("div",{className:"flex items-center gap-1",children:Te.map(Ce=>{const rt=`${F}:${Ce}`;return o.jsx("button",{type:"button",className:Ce==="stop"?`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${Ro}`:`inline-flex items-center justify-center disabled:cursor-not-allowed disabled:opacity-50 ${Vn}`,disabled:ee(rt),onClick:()=>{(async()=>Ce==="stop"&&!await j({title:"停止 Service",description:`确认停止 service「${K}」吗?`,confirmText:"停止",confirmVariant:"destructive"})||(ae(et=>({...et,[rt]:!0})),Promise.resolve(p(F,Ce)).finally(()=>{ae(et=>({...et,[rt]:!1}))})))()},title:Ce,"aria-label":Ce,children:ee(rt)?o.jsx(nt,{className:"size-3.5 animate-spin"}):o.jsx(s7,{action:Ce})},rt)})})]}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:o.jsxs("div",{className:"space-y-3 rounded-[14px] bg-transparent px-3 py-3",children:[Ye&&_e.length>0?o.jsx("div",{className:"space-y-1.5",children:_e.map((Ce,rt)=>{const et=String(Ce.channel||"").trim(),$e=!!et&&et!=="-",Ht=!$e||!(Ce.enabled&&Ce.configured),zn=!$e||Ce.enabled,ms=!$e||!Ce.enabled,Bs=`${F}:chat:${et}:open`,In=`${F}:chat:${et}:close`,Sn=`${F}:chat:${et}:test`,Jn=`${F}:chat:${et}:reconnect`;return o.jsx("div",{className:"flex flex-col gap-2 rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:o.jsxs("div",{className:"flex flex-col gap-1 lg:flex-row lg:items-center lg:justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-foreground",children:Ce.channel}),o.jsx("div",{className:"truncate",children:`${Ce.link} · ${Ce.accountName}`})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[o.jsx("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",onClick:()=>b(Ce.sessionId),disabled:!Ce.clickable,children:"session"}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:zn||ee(Bs),onClick:()=>{ae(vt=>({...vt,[Bs]:!0})),Promise.resolve(S("open",et)).finally(()=>{ae(vt=>({...vt,[Bs]:!1}))})},children:[ee(Bs)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"open"})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:ms||ee(In),onClick:()=>{ae(vt=>({...vt,[In]:!0})),Promise.resolve(S("close",et)).finally(()=>{ae(vt=>({...vt,[In]:!1}))})},children:[ee(In)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"close"})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:Ht||ee(Sn),onClick:()=>{ae(vt=>({...vt,[Sn]:!0})),Promise.resolve(S("test",et)).finally(()=>{ae(vt=>({...vt,[Sn]:!1}))})},children:[ee(Sn)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"test"})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-55",disabled:Ht||ee(Jn),onClick:()=>{ae(vt=>({...vt,[Jn]:!0})),Promise.resolve(S("reconnect",et)).finally(()=>{ae(vt=>({...vt,[Jn]:!1}))})},children:[ee(Jn)?o.jsx(nt,{className:"size-3 animate-spin"}):null,o.jsx("span",{children:"reconnect"})]})]})]})},`${F}:chat:${Ce.channel}:${rt}`)})}):null,Re&&Je.length>0?o.jsx("div",{className:"space-y-1.5",children:Je.map((Ce,rt)=>{const et=String(Ce.title||`task-${rt}`).trim(),$e=String(Ce.status||"unknown").trim().toLowerCase();return o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-foreground",children:et}),o.jsx("div",{className:"truncate",children:`${$e} · ${n7(Ce.lastRunTimestamp)}`})]}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1 rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground",onClick:()=>w(et),children:[o.jsx("span",{children:"open"}),o.jsx(my,{className:"size-3 shrink-0"})]})]},`${F}:task:${et}:${rt}`)})}):null,yt&&jt.length>0?o.jsx("div",{className:"space-y-1.5",children:jt.map((Ce,rt)=>o.jsxs("div",{className:"rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:[o.jsx("div",{className:"truncate text-foreground",children:Ce.name||Ce.id||"-"}),o.jsx("div",{className:"truncate",children:`${Ce.source||"-"} · ${Array.isArray(Ce.allowedTools)&&Ce.allowedTools.length>0?Ce.allowedTools.join(", "):"-"}`})]},`${F}:skill:${Ce.id||Ce.name||rt}`))}):null,ot&&Ct.length>0?o.jsx("div",{className:"space-y-1.5",children:Ct.map(Ce=>o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:[o.jsx("div",{className:"min-w-0 truncate",children:Ce}),o.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1 rounded-[10px] px-2.5 transition-colors hover:bg-secondary hover:text-foreground",onClick:()=>b(Ce),children:[o.jsx("span",{children:"open"}),o.jsx(my,{className:"size-3 shrink-0"})]})]},`${F}:session:${Ce}`))}):null,zt.length>0?o.jsx("div",{className:"space-y-1",children:zt.map((Ce,rt)=>o.jsx("div",{className:"truncate rounded-[12px] px-2 py-2 text-xs text-muted-foreground transition-colors hover:bg-background",children:Ce},`${F}:detail:${rt}`))}):null]})})},`${F}:${ce}`)}),o.jsx(wt,{title:"Signals",actions:o.jsx(Pa,{tone:z.length>0?"danger":"default",children:`issues ${z.length}`}),children:o.jsx("div",{className:"rounded-[18px] bg-secondary/85 p-2",children:z.length>0?z.map(U=>o.jsxs("div",{className:"rounded-[14px] bg-transparent px-3 py-3 text-sm text-muted-foreground transition-colors hover:bg-background",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"text-foreground",children:U.label}),o.jsx("span",{className:"text-xs text-destructive",children:U.status})]}),o.jsx("div",{className:"mt-1 truncate text-xs",title:U.reason||U.path,children:U.reason||U.path||"-"})]},`${U.key}:${U.path}`)):o.jsx("div",{className:"rounded-[14px] bg-transparent px-3 py-6 text-sm text-muted-foreground",children:"当前没有异常信号"})})})]}):o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"未选择 agent"})}function l7(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return"-";const n=Math.max(0,Number(t)-Number(e));return n<1e3?`${n} ms`:`${(n/1e3).toFixed(2)} s`}function fu(e,t){const n=String(e||"").trim();if(!n)return"-";const s=n.match(/^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-(\d{3})$/);if(s){const a=Number(s[1]),i=Number(s[2])-1,l=Number(s[3]),u=Number(s[4]),d=Number(s[5]),f=Number(s[6]),g=Number(s[7]),m=new Date(a,i,l,u,d,f,g).getTime(),h=t(m);return h==="-"?"未记录时间":h}const r=t(n);return r==="-"?"未记录时间":r}function c7(e,t){var s;const n=String(((s=t==null?void 0:t.progress)==null?void 0:s.status)||"").trim();return n||(e!=null&&e.inProgress?"running":String((e==null?void 0:e.status)||(e==null?void 0:e.executionStatus)||"unknown"))}function I0(e){const t=String(e||"").trim();return!t||t==="@manual"?"manual":t.startsWith("time:")?t.slice(5)||"time":t}function u7(e){var xe,ee,W,X;const{tasks:t,statusBadgeVariant:n,formatTime:s,onRunTask:r,onSetTaskStatus:a,onDeleteTask:i,onLoadTaskRuns:l,onDeleteTaskRun:u,onClearTaskRuns:d,onLoadTaskRunDetail:f,selectedTaskTitle:g,onSelectTaskTitle:m}=e,h=Ls(),x=String(g||"").trim(),y=c.useMemo(()=>t.find(G=>String(G.title||"").trim()===x)||null,[x,t]),w=!x,[b,p]=c.useState([]),[v,S]=c.useState(""),[j,C]=c.useState(null),[A,M]=c.useState(!1),[O,P]=c.useState(!1),[$,z]=c.useState(!1),[N,H]=c.useState(!1),[R,I]=c.useState(!1),[T,E]=c.useState(""),[q,k]=c.useState(!1),D=c.useCallback(G=>{const L=n(G);return L==="ok"?"bg-secondary text-foreground":L==="bad"?"border-destructive/40 bg-destructive/10 text-destructive":"bg-card text-muted-foreground"},[n]),B=c.useMemo(()=>b.find(G=>String(G.timestamp||"").trim()===v)||null,[b,v]),Q=c.useMemo(()=>b.find(G=>!!G.inProgress)||null,[b]),Z=c.useMemo(()=>{var G;return!!(B!=null&&B.inProgress)||String(((G=j==null?void 0:j.progress)==null?void 0:G.status)||"").trim().toLowerCase()==="running"},[B,j]),te=c.useMemo(()=>{const G=t.length,L=t.filter(ge=>String(ge.status||"").toLowerCase()==="running").length,J=t.filter(ge=>{const U=String(ge.status||"").toLowerCase();return U==="error"||U==="failed"||U==="failure"}).length,me=t.filter(ge=>String(ge.when||"").trim()==="@manual").length;return{total:G,running:L,failed:J,manual:me}},[t]),se=c.useCallback(async(G,L)=>{const J=String(G||"").trim();if(!J)return[];const me=(L==null?void 0:L.showLoading)!==!1;me&&M(!0);try{const ge=await l(J,50);return p(ge),S(U=>{var F;const ce=L!=null&&L.preferInProgress?ge.find(K=>!!K.inProgress):null;return ce!=null&&ce.timestamp?String(ce.timestamp):U&&ge.some(K=>K.timestamp===U)?U:String(((F=ge[0])==null?void 0:F.timestamp)||"").trim()}),ge}finally{me&&M(!1)}},[l]),ie=c.useCallback(async(G,L,J)=>{const me=String(G||"").trim(),ge=String(L||"").trim();if(!me||!ge)return C(null),null;const U=(J==null?void 0:J.showLoading)!==!1;U&&P(!0);try{const ce=await f(me,ge);return C(ce),ce}finally{U&&P(!1)}},[f]);if(c.useEffect(()=>{if(!y){p([]),S(""),C(null),z(!1),H(!1);return}se(String(y.title||""),{showLoading:!0,preferInProgress:!0})},[se,y]),c.useEffect(()=>{const G=String((y==null?void 0:y.title)||"").trim(),L=String(v||"").trim();if(!G||!L){C(null);return}ie(G,L,{showLoading:!0})},[ie,v,y]),c.useEffect(()=>{Q!=null&&Q.timestamp&&Q.timestamp!==v&&S(Q.timestamp)},[Q,v]),c.useEffect(()=>{const G=String((y==null?void 0:y.title)||"").trim();if(!G||!($||Z||b.some(me=>!!me.inProgress)))return;const J=window.setInterval(()=>{se(G,{showLoading:!1,preferInProgress:!0}).then(me=>{var ce;const ge=me.find(F=>!!F.inProgress),U=String((ge==null?void 0:ge.timestamp)||v||((ce=me[0])==null?void 0:ce.timestamp)||"").trim();U&&ie(G,U,{showLoading:!1}),ge||z(!1)})},1500);return()=>{window.clearInterval(J)}},[$,ie,se,b,Z,v,y]),w)return o.jsx(wt,{title:"Tasks",description:"任务定义、状态与最近执行时间总览。",actions:o.jsxs(o.Fragment,{children:[o.jsx(An,{variant:"outline",className:"bg-secondary text-foreground",children:`total ${te.total}`}),o.jsx(An,{variant:"outline",className:"border-border/60 bg-primary/10 text-primary",children:`running ${te.running}`}),o.jsx(An,{variant:"outline",className:"border-border/60 bg-destructive/10 text-destructive",children:`failed ${te.failed}`}),o.jsx(An,{variant:"outline",className:"bg-secondary text-foreground",children:`manual ${te.manual}`})]}),children:t.length===0?o.jsx("div",{className:"rounded-[20px] bg-secondary px-4 py-6 text-sm text-muted-foreground",children:"暂无 task 数据"}):o.jsx("div",{className:"space-y-1.5",children:t.map(G=>{const L=String(G.title||"").trim();if(!L)return null;const J=String(G.status||"unknown"),me=String(G.description||"").trim(),ge=I0(G.when);return o.jsxs("button",{type:"button",className:"flex w-full items-start justify-between gap-3 rounded-[18px] bg-transparent px-3 py-2.5 text-left transition-colors hover:bg-secondary",onClick:()=>m==null?void 0:m(L),children:[o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:L}),o.jsx("div",{className:"truncate text-xs text-muted-foreground",children:me||"无描述"})]}),o.jsxs("div",{className:"flex flex-shrink-0 flex-wrap items-center justify-end gap-1.5",children:[o.jsx(An,{variant:"outline",className:D(J),children:J}),o.jsx(An,{variant:"outline",className:"bg-secondary text-muted-foreground",children:ge}),o.jsx(An,{variant:"outline",className:"bg-background text-muted-foreground",children:fu(String(G.lastRunTimestamp||""),s)})]})]},L)})})});if(!y)return o.jsx("div",{className:"py-6 text-sm text-muted-foreground",children:"该 task 不存在或已被删除"});const oe=String(y.title||"").trim(),pe=String(y.status||"").trim().toLowerCase(),_=pe==="enabled"?"paused":"enabled",Y=_==="enabled"?"恢复调度":"暂停调度",le=pe==="paused"?"paused:保留定义,不参与调度,可随时恢复。":pe==="disabled"?"disabled:显式禁用,仍保留定义,但当前作为关闭态处理。":"enabled:参与调度,按 when 正常运行。",ne=c.useCallback(async()=>{if(!(!oe||!await h({title:"删除任务",description:`确认删除任务「${oe}」及其全部运行记录?`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"}))){I(!0);try{await i(oe)&&(m==null||m(""))}finally{I(!1)}}},[h,i,m,oe]),ue=c.useCallback(async()=>{if(oe){I(!0);try{await a(oe,"disabled")}finally{I(!1)}}},[a,oe]),ae=c.useCallback(async()=>{if(oe){I(!0);try{await a(oe,_)}finally{I(!1)}}},[a,oe,_]);return o.jsxs("div",{className:"space-y-4",children:[o.jsxs(wt,{title:"Task Runtime",description:String(y.description||"").trim()||"无描述",actions:o.jsxs(yn,{children:[o.jsx(vn,{render:o.jsx(be,{size:"icon",variant:"ghost",className:Vn,disabled:R||!oe,"aria-label":"任务操作",title:"任务操作"}),children:o.jsx(kw,{className:"size-4"})}),o.jsxs(wn,{align:"end",className:"min-w-[14rem]",children:[o.jsxs(ih,{children:[o.jsx(lh,{children:"任务操作"}),o.jsx(bt,{onClick:()=>void ae(),children:Y}),pe!=="disabled"?o.jsx(bt,{onClick:()=>void ue(),children:"设为 disabled"}):null]}),o.jsx(Md,{}),o.jsx(bt,{variant:"destructive",onClick:()=>void ne(),children:"删除任务"})]})]}),children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(An,{variant:"outline",className:D(String(y.status||"unknown")),children:String(y.status||"unknown")}),o.jsx(be,{size:"sm",variant:"outline",onClick:()=>m==null?void 0:m(""),children:"返回列表"}),o.jsx(be,{size:"sm",onClick:()=>{const G=String(y.title||"").trim();G&&(z(!0),r(G),window.setTimeout(()=>{se(G,{showLoading:!1,preferInProgress:!0})},350))},children:"Run Task"})]}),o.jsx("div",{className:"text-lg font-semibold tracking-tight text-foreground",children:String(y.title||"-")}),o.jsx("div",{className:"text-xs text-muted-foreground",children:le})]}),o.jsxs("div",{className:"grid min-h-0 gap-4 xl:grid-cols-[minmax(0,1.08fr)_minmax(0,1fr)]",children:[o.jsxs(wt,{title:"Definition",description:"任务定义、触发方式与原始内容。",children:[o.jsx("div",{className:"rounded-[20px] bg-secondary px-4 py-3.5",children:o.jsxs("div",{className:"grid gap-1.5 text-xs text-muted-foreground",children:[o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"kind"}),o.jsx("span",{children:y.kind||"-"})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"when"}),o.jsx("span",{children:I0(y.when)})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"session"}),o.jsx("span",{className:"truncate font-mono",title:y.sessionId||"",children:y.sessionId||"-"})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"file"}),o.jsx("span",{className:"truncate font-mono",title:y.taskMdPath||"",children:y.taskMdPath||"-"})]}),o.jsxs("div",{className:"grid grid-cols-[84px_minmax(0,1fr)] gap-2",children:[o.jsx("span",{className:"text-foreground/80",children:"lastRun"}),o.jsx("span",{children:fu(String(y.lastRunTimestamp||""),s)})]})]})}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.14em] text-muted-foreground",children:"Body"}),o.jsx("pre",{className:"h-[46vh] min-h-[20rem] overflow-auto rounded-[20px] bg-secondary px-4 py-3.5 text-[12px] leading-relaxed text-foreground/90",children:y.body||"-"})]})]}),o.jsx(wt,{title:"Runtime",description:"最近执行记录、状态与运行详情。",bodyClassName:"min-h-0",actions:o.jsx("div",{className:"flex items-center gap-1.5",children:o.jsx(be,{size:"sm",variant:"outline",onClick:async()=>{var J;const G=String(y.title||"").trim();if(!(!G||!await h({title:"清空 Run Log",description:`确认清理任务「${G}」的全部 run 记录?`,confirmText:"清空",cancelText:"取消",confirmVariant:"destructive"}))){k(!0);try{if(!await d(G))return;const ge=await se(G,{showLoading:!1,preferInProgress:!0});String(((J=ge[0])==null?void 0:J.timestamp)||"").trim()||(S(""),C(null),H(!1))}finally{k(!1)}}},disabled:A||q,children:q?"清理中...":"清空 Run Log"})}),children:b.length===0?o.jsx("div",{className:"rounded-[18px] bg-secondary px-4 py-5 text-sm text-muted-foreground",children:"暂无执行记录"}):o.jsx("div",{className:"max-h-[62vh] space-y-1.5 overflow-y-auto pr-1",children:b.map(G=>{const L=G.inProgress?"running":String(G.status||G.executionStatus||"unknown"),J=String(G.timestamp||"")===String(v||""),me=String(G.timestamp||"").trim(),ge=T===me;return o.jsxs("div",{className:"flex items-start gap-1.5",children:[o.jsxs("button",{type:"button",className:Me("min-w-0 flex-1 rounded-[18px] px-3.5 py-3 text-left transition-colors",J?"bg-secondary":"bg-transparent hover:bg-secondary"),onClick:()=>{S(G.timestamp),H(!0)},children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsx("div",{className:"text-xs font-medium text-foreground/90",children:fu(G.timestamp,s)}),o.jsx(An,{variant:"outline",className:D(L),children:L})]}),o.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-3 text-[11px] text-muted-foreground",children:[o.jsx("span",{children:`start ${s(G.startedAt)}`}),o.jsx("span",{children:`duration ${l7(G.startedAt,G.endedAt)}`}),o.jsx("span",{children:`rounds ${G.dialogueRounds??G.progressRound??"-"}`})]})]}),o.jsx(be,{size:"icon",variant:"ghost",className:`mt-1 ${Ro}`,disabled:!!G.inProgress||ge,onClick:async()=>{var ce;if(!(!oe||!me||!await h({title:"删除 Run 记录",description:`确认删除 run「${me}」记录?`,confirmText:"删除",cancelText:"取消",confirmVariant:"destructive"}))){E(me);try{if(!await u(oe,me))return;const K=await se(oe,{showLoading:!1,preferInProgress:!0});if(!K.some(he=>String(he.timestamp||"").trim()===me)&&String(v||"").trim()===me){const he=String(((ce=K[0])==null?void 0:ce.timestamp)||"").trim();S(he),he||(C(null),H(!1))}}finally{E("")}}},title:"删除 run","aria-label":"删除 run",children:ge?o.jsx(er,{className:"size-3.5 animate-pulse"}):o.jsx(er,{className:"size-3.5"})})]},G.timestamp)})})})]}),o.jsx($n,{open:N,onOpenChange:H,children:o.jsxs(Un,{className:"w-[min(96vw,980px)] p-0",children:[o.jsxs(Hn,{className:"bg-secondary px-4 py-4",children:[o.jsx(Fn,{children:`Run Detail${v?` · ${fu(v,s)}`:""}`}),o.jsx(os,{children:(y==null?void 0:y.title)||"-"})]}),o.jsx("div",{className:"max-h-[68vh] space-y-3 overflow-y-auto px-4 py-4",children:O?o.jsx("div",{className:"text-sm text-muted-foreground",children:"加载中..."}):j?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-[18px] bg-secondary px-3.5 py-3 text-xs text-muted-foreground",children:[o.jsx("div",{children:`runDir: ${j.runDirRel||"-"}`}),o.jsx("div",{children:`status: ${c7(B,j)}`}),o.jsx("div",{children:`phase: ${String(((xe=j.progress)==null?void 0:xe.phase)||"-")}`}),o.jsx("div",{children:`message: ${String(((ee=j.progress)==null?void 0:ee.message)||"-")}`}),o.jsx("div",{children:`updatedAt: ${s((W=j.progress)==null?void 0:W.updatedAt)}`}),o.jsx("div",{children:`error: ${String(((X=j.meta)==null?void 0:X.error)||"-")}`})]}),o.jsx("div",{className:"grid gap-3 xl:grid-cols-2",children:["input","output","result","dialogue","error"].map(G=>{var L;return o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:G}),o.jsx("pre",{className:"max-h-56 overflow-auto rounded-[16px] bg-card px-3 py-2.5 text-[11px] leading-relaxed",children:String(((L=j.artifacts)==null?void 0:L[G])||"-")})]},G)})})]}):o.jsx("div",{className:"text-sm text-muted-foreground",children:"未找到执行详情"})})]})})]})}function d7(e){const{message:t,type:n}=e;return o.jsx("div",{className:Me("fixed right-5 bottom-5 z-50 rounded-[18px] px-4 py-2.5 text-sm shadow-[0_10px_26px_rgba(24,24,27,0.06)] backdrop-blur-sm",n==="success"&&"bg-card text-foreground",n==="error"&&"bg-destructive/10 text-destructive",n==="info"&&"bg-card text-muted-foreground"),children:t})}function f7(e){const[t,n]=c.useState("");return c.useEffect(()=>{var a,i;const s=((a=e.board)==null?void 0:a.agents)||[];if(s.length===0){n("");return}s.find(l=>l.id===t)||n(((i=s[0])==null?void 0:i.id)||"")},[e.board,t]),o.jsxs("section",{className:"space-y-4",children:[e.errorMessage?o.jsx("div",{className:"rounded-[22px] border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive",children:e.errorMessage}):null,o.jsx(mz,{board:e.board,loading:e.loading,selectedAgentId:t,onSelectAgent:n,onRefresh:e.onRefresh})]})}function g7(e){const{viewLabel:t,rightActions:n}=e,s=c.useMemo(()=>{const r=String(t||"").trim();if(!r)return"Overview";const a=r.toLowerCase();return a.includes("global")?r.replace(/global\s*/i,"").trim()||"Overview":a.includes("context")?"Chat":a.includes("agent")?r.replace(/agent\s*/i,"").trim()||"Agent":r},[t]);return o.jsx("header",{className:"flex h-(--header-height) shrink-0 items-center gap-2 bg-transparent transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-(--header-height)",children:o.jsx("div",{className:"flex w-full flex-wrap items-center gap-2 px-3 py-2 md:px-4 lg:gap-2 lg:px-5",children:o.jsxs("div",{className:"flex h-10 w-full items-center gap-2 rounded-[18px] bg-transparent px-2.5",children:[o.jsx(Cz,{className:"-ml-0.5"}),o.jsx("h1",{className:"text-[0.95rem] font-medium tracking-[-0.02em] text-foreground",children:s}),o.jsx("div",{className:"ml-auto flex items-center",children:n})]})})})}const Sx="city.console-ui.auth.v1";class Lu extends Error{constructor(n,s,r){super(n);at(this,"status");at(this,"statusText");this.name="ConsoleApiError",this.status=s,this.statusText=r}}function Id(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Sx);if(!e)return null;const t=JSON.parse(e),n=String((t==null?void 0:t.token)||"").trim();if(!n)return null;const s=String((t==null?void 0:t.username)||"").trim();return{token:n,...s?{username:s}:{}}}catch{return null}}function m7(e){if(typeof window>"u")return;const t=String(e.token||"").trim();if(!t)return;const n=String(e.username||"").trim();window.localStorage.setItem(Sx,JSON.stringify({token:t,...n?{username:n}:{}}))}function D0(){typeof window>"u"||window.localStorage.removeItem(Sx)}function qj(e,t,n){const s=String(e||"");if(!s.startsWith("/api/")||s.startsWith("/api/ui/"))return s;const r=n??t;if(!r)return s;const a=new URL(s,window.location.origin);return a.searchParams.set("agent",r),`${a.pathname}${a.search}`}async function Bu(e){var i;const t=Id(),n=new Headers((i=e.options)==null?void 0:i.headers);n.has("Content-Type")||n.set("Content-Type","application/json"),t!=null&&t.token&&!n.has("Authorization")&&n.set("Authorization",`Bearer ${t.token}`);const s=await fetch(qj(e.path,e.selectedAgentId,e.preferredAgentId),{...e.options||{},headers:n}),r=await s.text();let a=null;try{a=r?JSON.parse(r):{}}catch{a=null}if(!s.ok){const l=typeof(a==null?void 0:a.error)=="string"?a.error:typeof(a==null?void 0:a.message)=="string"?a.message:`${s.status} ${s.statusText}`;throw new Lu(l,s.status,s.statusText)}if(a&&a.success===!1){const l=typeof a.error=="string"?a.error:typeof a.message=="string"?a.message:"request failed";throw new Lu(l,s.status,s.statusText)}if(a===null)throw new Lu(`Invalid JSON response from ${e.path}`,s.status,s.statusText);return a}const ve={authStatus:()=>"/api/auth/status",authMe:()=>"/api/auth/me",authTokenList:()=>"/api/auth/token/list",authTokenCreate:()=>"/api/auth/token/create",authTokenDelete:()=>"/api/auth/token/delete",uiAgents:e=>e?`/api/ui/agents?agent=${encodeURIComponent(e)}`:"/api/ui/agents",uiAgentRuntimeStatus:e=>`/api/ui/agents/runtime-status?agent=${encodeURIComponent(e)}`,uiLocalModels:()=>"/api/ui/local-models",uiPlugins:e=>e?`/api/ui/plugins?agent=${encodeURIComponent(e)}`:"/api/ui/plugins",uiPluginsAction:e=>e?`/api/ui/plugins/action?agent=${encodeURIComponent(e)}`:"/api/ui/plugins/action",uiModel:e=>e?`/api/ui/model?agent=${encodeURIComponent(e)}`:"/api/ui/model",uiModelSwitch:e=>`/api/ui/model/switch?agent=${encodeURIComponent(e)}`,uiConfigStatus:e=>e?`/api/ui/config-status?agent=${encodeURIComponent(e)}`:"/api/ui/config-status",uiAgentEnv:e=>`/api/ui/env?scope=agent&agent=${encodeURIComponent(e)}`,overview:(e=40)=>`/api/dashboard/overview?sessionLimit=${encodeURIComponent(String(e))}`,workboardSnapshot:()=>"/api/workboard/snapshot",services:()=>"/api/dashboard/services",sessions:(e=120)=>`/api/dashboard/sessions?limit=${encodeURIComponent(String(e))}`,sessionMessages:(e,t=100)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/messages?limit=${encodeURIComponent(String(t))}`,sessionArchives:(e,t=80)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/archives?limit=${encodeURIComponent(String(t))}`,sessionArchiveDetail:(e,t)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/archives/${encodeURIComponent(t)}`,sessionExecute:e=>`/api/dashboard/sessions/${encodeURIComponent(e)}/execute`,sessionClearMessages:e=>`/api/dashboard/sessions/${encodeURIComponent(e)}/messages`,sessionClearChatHistory:e=>`/api/dashboard/sessions/${encodeURIComponent(e)}/chat-history`,systemPrompt:e=>`/api/dashboard/system-prompt?sessionId=${encodeURIComponent(e)}`,tasks:()=>"/api/dashboard/tasks",taskRun:()=>"/api/dashboard/tasks/run",taskStatus:e=>`/api/dashboard/tasks/${encodeURIComponent(e)}/status`,taskDetail:e=>`/api/dashboard/tasks/${encodeURIComponent(e)}`,taskRuns:(e,t=50)=>`/api/dashboard/tasks/${encodeURIComponent(e)}/runs?limit=${encodeURIComponent(String(t))}`,taskRunDetail:(e,t)=>`/api/dashboard/tasks/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}`,logs:(e=260)=>`/api/dashboard/logs?limit=${encodeURIComponent(String(e))}`,authorization:()=>"/api/dashboard/authorization",authorizationConfig:()=>"/api/dashboard/authorization/config",authorizationAction:()=>"/api/dashboard/authorization/action",localMessages:(e,t=80)=>`/api/dashboard/sessions/${encodeURIComponent(e)}/messages?limit=${encodeURIComponent(String(t))}`,servicesCommand:()=>"/api/services/command",servicesControl:()=>"/api/services/control",pluginsAction:()=>"/api/plugins/action",uiModelPool:()=>"/api/ui/model/pool",uiEnv:()=>"/api/ui/env",uiChannelAccounts:()=>"/api/ui/channel-accounts",uiAgentStart:()=>"/api/ui/agents/start",uiAgentCreate:()=>"/api/ui/agents/create",uiAgentInspect:()=>"/api/ui/agents/inspect",uiAgentExecution:()=>"/api/ui/agents/execution",uiPickDirectory:()=>"/api/ui/system/pick-directory",uiAgentRestart:()=>"/api/ui/agents/restart",uiAgentStop:()=>"/api/ui/agents/stop",uiCommandExecute:()=>"/api/ui/command/execute",uiModelProviderUpsert:()=>"/api/ui/model/provider/upsert",uiModelProviderRemove:()=>"/api/ui/model/provider/remove",uiModelProviderTest:()=>"/api/ui/model/provider/test",uiModelProviderDiscover:()=>"/api/ui/model/provider/discover",uiModelItemUpsert:()=>"/api/ui/model/model/upsert",uiModelItemRemove:()=>"/api/ui/model/model/remove",uiModelItemPause:()=>"/api/ui/model/model/pause",uiModelItemTest:()=>"/api/ui/model/model/test",uiChannelAccountUpsert:()=>"/api/ui/channel-accounts/upsert",uiChannelAccountProbe:()=>"/api/ui/channel-accounts/probe",uiChannelAccountRemove:()=>"/api/ui/channel-accounts/remove",uiEnvUpsert:()=>"/api/ui/env/upsert",uiEnvImport:()=>"/api/ui/env/import",uiEnvRemove:()=>"/api/ui/env/remove"},Js="consoleui-chat-main";function Le(e){return e instanceof Error?e.message:String(e)}function Gj(e){const t=String(e||"").toLowerCase();return t.includes("no running agent found")||t.includes("start one via `city agent start` first")||t.includes("no running agent selected")}function kf(e){const t=String(e||"").toLowerCase();return Gj(t)||t.includes("service unavailable")||t.includes("selected agent runtime endpoint is unavailable")||t.includes("503")}function h7(e){const t=String(e||"").toLowerCase();return t.includes("service")&&t.includes("chat")&&t.includes("未启动")||t.includes("service")&&t.includes("chat")&&t.includes("not started")||t.includes("service")&&t.includes("chat")&&t.includes("not start")||t.includes("chat")&&t.includes("not running")}function mh(e){const t=String(e||"").toLowerCase();return t.includes("404")||t.includes("not found")}function Vj(e){if(typeof e=="object"&&e!==null&&"status"in e)return Number(e.status)===401;const t=Le(e).toLowerCase();return t.includes("missing bearer token")||t.includes("invalid bearer token")||t.includes("token is revoked")||t.includes("token is expired")||t.includes("user not found for token")}function p7(e){const t=String(e||"").toLowerCase();return["running","ok","active","enabled","success"].includes(t)?"ok":["stopped","disabled","paused","error","failed","offline"].includes(t)?"bad":"warn"}function x7(e){if(e==null)return"-";const t=typeof e=="number"?e:Date.parse(String(e));return!Number.isFinite(t)||Number.isNaN(t)?"-":new Date(t).toLocaleString("zh-CN",{hour12:!1})}function b7(e){var s,r;const t=((s=e.availability)==null?void 0:s.enabled)===!0,n=((r=e.availability)==null?void 0:r.available)===!0;return t?n?"available":"unavailable":"disabled"}function y7(e){return e.map(t=>{var s,r;const n=Array.isArray((s=t.availability)==null?void 0:s.reasons)?(r=t.availability)==null?void 0:r.reasons:[];return{...t,state:b7(t),lastError:n.length>0?n.join("; "):""}})}function dl(e){return new Promise(t=>{window.setTimeout(t,e)})}function v7(e){const t=String(e||"").trim().toLowerCase();return t?t.startsWith("consoleui-")||t==="local_ui":!1}function w7(e,t){return t.map((n,s)=>{const r=String(n.role||"").trim().toLowerCase(),a=n.ts,i=typeof a=="number"?a:Number.isFinite(Date.parse(String(a||"")))?Date.parse(String(a||"")):Date.now();return{id:String(n.id||`${e}:timeline:${s}`),sessionId:e,contextId:e,channel:"consoleui",direction:r==="user"?"inbound":"outbound",ts:i,text:String(n.text||""),...r==="user"?{actorName:"user"}:{actorName:"agent"}}})}async function S7(e){var g,m,h,x;const t=String(e.preferredAgentId||e.selectedAgentId||"").trim(),n=ve.uiAgents(t||void 0);let s;try{s=await e.requestJson(n)}catch(y){const w=Le(y);if(Gj(w))return{nextAgentId:"",list:[],cityVersion:""};throw y}const r=Array.isArray(s.agents)?s.agents:[],a=String(s.cityVersion||"").trim(),i=t&&((g=r.find(y=>y.id===t))==null?void 0:g.id)||"",l=String(s.selectedAgentId||"").trim(),u=l&&((m=r.find(y=>y.id===l))==null?void 0:m.id)||"",d=((h=r.find(y=>y.running===!0))==null?void 0:h.id)||"",f=((x=r[0])==null?void 0:x.id)||"";return{nextAgentId:i||u||d||f,list:r,cityVersion:a}}async function j7(e,t){return t?e(ve.overview(40),{},t):null}async function C7(e,t){if(!t)return[];const n=await e(ve.services(),{},t);return Array.isArray(n.services)?n.services:[]}async function k7(e,t){var n;if(!t)return[];try{const s=await e(ve.pluginsAction(),{method:"POST",body:JSON.stringify({pluginName:"skill",actionName:"list",payload:{}})},t);return Array.isArray((n=s==null?void 0:s.data)==null?void 0:n.skills)?s.data.skills:[]}catch(s){const r=Le(s);if(/404|not found|unknown action|unknown plugin/i.test(r)||kf(r))return[];throw s}}async function jx(e){const t=String(e.agentId||"").trim();if(!t)throw new Error("当前无可用 agent");const n=String(e.command||"").trim();if(!n)throw new Error("skill command 不能为空");const s=e.payload??{};return e.requestJson(ve.pluginsAction(),{method:"POST",body:JSON.stringify({pluginName:"skill",actionName:n,payload:s})},t)}async function Cx(e){const t=String(e.agentId||"").trim();if(!t)return{running:!1,servicesReady:!1};const n=Number.isFinite(e.maxRetry)?Number(e.maxRetry):36,s=Number.isFinite(e.intervalMs)?Number(e.intervalMs):500;let r=!1;for(let a=0;a<n;a+=1){try{const i=await e.requestJson(ve.uiAgents(t)),u=(Array.isArray(i.agents)?i.agents:[]).find(d=>String(d.id||"")===t);r=(u==null?void 0:u.running)===!0}catch{r=!1}if(!r){await dl(s);continue}try{const i=await e.requestJson(ve.uiAgentRuntimeStatus(t));if(i.running!==!0){await dl(s);continue}if(i.serverReady!==!0){await dl(s);continue}if(i.servicesReady===!0)return{running:!0,servicesReady:!0};await dl(s);continue}catch(i){const l=Le(i);kf(l)}await dl(s)}return{running:r,servicesReady:!1}}async function _0(e,t){const n=await e(ve.uiPlugins(t)),s=Array.isArray(n.plugins)?n.plugins:[];return y7(s)}async function N7(e,t){const n=await e(ve.uiLocalModels(),{method:"POST",body:JSON.stringify(t?{projectRoot:t}:{})});return Array.isArray(n.models)?n.models.map(s=>String(s||"").trim()).filter(Boolean):[]}async function T7(e,t){var n;if(!t)return[];try{const s=await e(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"status",payload:{}})},t);return[...Array.isArray((n=s==null?void 0:s.data)==null?void 0:n.channels)?s.data.channels:[],{channel:"consoleui",enabled:!0,configured:!0,running:!0,linkState:"connected",statusText:"console-ui built-in channel",detail:{readonly:!0,managedBy:"console-ui"}}]}catch(s){const r=Le(s);if(h7(r)||kf(r))return[{channel:"consoleui",enabled:!0,configured:!0,running:!0,linkState:"connected",statusText:"console-ui built-in channel",detail:{readonly:!0,managedBy:"console-ui"}}];throw s}}async function A7(e,t){if(!t)return[];const n=await e(ve.sessions(120),{},t),s=Array.isArray(n.sessions)?n.sessions:[];return s.some(a=>String(a.sessionId||"").trim()===Js)?s:[{sessionId:Js,channel:"consoleui",messageCount:0,updatedAt:Date.now(),lastRole:"system",lastText:"consoleui channel"},...s]}async function E7(e,t,n){var a;if(!t||!n)return[];try{const i=await e(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"history",payload:{sessionId:n,limit:80}})},t),l=Array.isArray((a=i==null?void 0:i.data)==null?void 0:a.events)?i.data.events:[];if(l.length>0||!String(n||"").startsWith("consoleui-"))return l}catch(i){if(!(String(n||"").trim().toLowerCase().startsWith("consoleui-")||String(n||"").trim().toLowerCase()==="local_ui"))throw i}const s=await e(ve.sessionMessages(n,100),{},t),r=Array.isArray(s.messages)?s.messages:[];return w7(n,r)}async function M7(e,t,n){if(!t||!n)return[];const s=await e(ve.sessionMessages(n,100),{},t);return Array.isArray(s.messages)?s.messages:[]}async function R7(e,t,n,s){return e(ve.sessionArchiveDetail(n,s),{},t)}async function O7(e,t,n){if(!t||!n)return[];try{const s=await e(ve.sessionArchives(n,80),{},t);return Array.isArray(s.archives)?s.archives:[]}catch(s){if(mh(Le(s)))return[];throw s}}async function z7(e,t){if(!t)return[];const n=await e(ve.tasks(),{},t);return Array.isArray(n.tasks)?n.tasks:[]}async function I7(e,t){if(!t)return[];const n=await e(ve.logs(260),{},t);return Array.isArray(n.logs)?n.logs:[]}async function D7(e,t){try{const n=ve.uiModel(t||void 0);return(await e(n,{},t)).model||null}catch(n){if(/404|not found/i.test(Le(n)))return null;throw n}}async function _7(e,t){const n=ve.uiConfigStatus(t||void 0),s=await e(n,{},t);return Array.isArray(s.items)?s.items:[]}async function L7(e){const t=await e(ve.uiModelPool());return{providers:Array.isArray(t.providers)?t.providers:[],models:Array.isArray(t.models)?t.models:[]}}async function B7(e){const t=await e(ve.uiEnv());return Array.isArray(t.items)?t.items:[]}async function P7(e,t){if(!t)return[];const n=await e(ve.uiAgentEnv(t));return Array.isArray(n.items)?n.items:[]}async function $7(e){const t=await e(ve.uiChannelAccounts());return Array.isArray(t.items)?t.items:[]}async function U7(e,t,n){if(!t)return null;const s=String(n).trim()||Js;try{return await e(ve.systemPrompt(s),{},t)}catch(r){if(/404|not found/i.test(Le(r)))return null;throw r}}async function H7(e,t){if(!t)return[];const n=await e(ve.localMessages(Js,80),{},t);return Array.isArray(n.messages)?n.messages:[]}async function F7(e,t){return t?e(ve.authorization(),{},t):null}async function q7(e){try{await e.requestJson(ve.servicesControl(),{method:"POST",body:JSON.stringify({serviceName:e.serviceName,action:e.action})}),e.showToast(`service ${e.serviceName} ${e.action} 已执行`,"success"),await Promise.all([e.refreshServices(e.selectedAgentId),e.refreshSkills(e.selectedAgentId)])}catch(t){e.showToast(`service 操作失败: ${Le(t)}`,"error")}}async function L0(e){try{const t=Id(),n=e.scope==="global"?"global":"agent",s=n==="global"?ve.uiPluginsAction(e.selectedAgentId):qj(ve.pluginsAction(),e.selectedAgentId),r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...t!=null&&t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({pluginName:e.pluginName,actionName:e.actionName,payload:e.payload})}),a=await r.text(),i=a?JSON.parse(a):{},l=String((i==null?void 0:i.message)||(i==null?void 0:i.error)||`${e.pluginName} ${e.actionName}`).trim(),u=G7(i==null?void 0:i.data,l),d=e.actionName==="on"||e.actionName==="off"||e.actionName==="install"||e.actionName==="configure"||e.actionName==="use";return d&&n==="global"&&e.refreshGlobalPlugins&&e.refreshGlobalPlugins().catch(()=>{}),d&&n==="agent"&&e.selectedAgentId&&e.refreshPlugins(e.selectedAgentId).catch(()=>{}),e.showToast(`plugin ${e.pluginName} ${e.actionName}: ${l}`,r.ok&&(i!=null&&i.success)?"success":"error"),{success:r.ok&&(i==null?void 0:i.success)===!0,message:l,data:i==null?void 0:i.data,logs:u}}catch(t){const n=Le(t);return e.showToast(`plugin 操作失败: ${n}`,"error"),{success:!1,message:n}}}function G7(e,t){const n=e&&typeof e=="object"?e:null,r=(Array.isArray(n==null?void 0:n.logs)?n.logs:n!=null&&n.details&&typeof n.details=="object"&&Array.isArray(n.details.logs)?n.details.logs:[]).map(a=>String(a||"").trim()).filter(Boolean);return r.length>0?r:t?[t]:[]}async function V7(e){var t;try{const n=e.channel?{channel:e.channel}:{},s=await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:e.action,payload:n})});if(e.action==="test"){const r=Array.isArray((t=s==null?void 0:s.data)==null?void 0:t.results)?s.data.results:[],a=e.channel?r.find(f=>String(f.channel||"")===e.channel):r[0],i=String((a==null?void 0:a.message)||"test completed");e.showToast(`${e.channel||"chat"} test: ${i}`,a!=null&&a.success?"success":"error");const l=e.chatChannels.find(f=>String(f.channel||"").trim()===String(e.channel||"").trim()),u=String((l==null?void 0:l.linkState)||"").trim().toLowerCase();!!e.channel&&!!(a!=null&&a.success)&&u!=="connected"&&(await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"reconnect",payload:{channel:e.channel}})}),e.showToast(`${e.channel} test 通过,已自动 reconnect`,"success"))}else e.action==="open"||e.action==="close"?e.showToast(`${e.channel||"chat"} ${e.action} 已执行(已写入 downcity.json)`,"success"):e.showToast(`${e.channel||"chat"} ${e.action} 已执行`,"success");await Promise.all([e.refreshChatChannels(e.selectedAgentId),e.refreshServices(e.selectedAgentId)])}catch(n){e.showToast(`chat ${e.action} 失败: ${Le(n)}`,"error")}}async function Y7(e){const t=String(e.channel||"").trim();if(t)try{await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"configure",payload:{channel:t,config:e.config,restart:!0}})}),e.showToast(`${t} 配置已保存并重载`,"success"),await e.refreshDashboard(e.selectedAgentId)}catch(n){e.showToast(`配置 ${t} 失败: ${Le(n)}`,"error")}}async function K7(e){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}try{const t=await e.requestJson(ve.authorizationConfig(),{method:"POST",body:JSON.stringify({config:e.config})},e.selectedAgentId);e.setAuthorization(t),e.showToast("authorization 配置已保存","success")}catch(t){e.showToast(`保存 authorization 失败: ${Le(t)}`,"error")}}async function X7(e){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}try{const t=await e.requestJson(ve.authorizationAction(),{method:"POST",body:JSON.stringify(e.input)},e.selectedAgentId);e.setAuthorization(t),e.showToast(`authorization ${e.input.action} 已执行`,"success")}catch(t){e.showToast(`authorization ${e.input.action} 失败: ${Le(t)}`,"error")}}async function Z7(e){const t=String(e.query||"").trim();if(!t)return e.showToast("请输入要查找的 skill 关键词","error"),null;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),null;const n={query:t};try{const s=await jx({requestJson:e.requestJson,agentId:e.selectedAgentId,command:"find",payload:n}),r=(s==null?void 0:s.data)||null;return e.showToast((r==null?void 0:r.message)||`已执行 skill find: ${t}`,"success"),await e.refreshSkills(e.selectedAgentId),r}catch(s){return e.showToast(`skill find 失败: ${Le(s)}`,"error"),null}}async function J7(e){const t=String(e.input.spec||"").trim();if(!t)return e.showToast("请输入要安装的 skill spec","error"),null;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),null;const n={spec:t,global:e.input.global!==!1,yes:e.input.yes!==!1,agent:String(e.input.agent||"claude-code").trim()||"claude-code"};try{const s=await jx({requestJson:e.requestJson,agentId:e.selectedAgentId,command:"install",payload:n}),r=(s==null?void 0:s.data)||null;return e.showToast((r==null?void 0:r.message)||`skill 安装完成: ${t}`,"success"),await e.refreshSkills(e.selectedAgentId),r}catch(s){return e.showToast(`skill install 失败: ${Le(s)}`,"error"),null}}async function Q7(e){var n;const t=String(e.name||"").trim();if(!t)return e.showToast("请输入 skill 名称","error"),null;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),null;try{const s=await jx({requestJson:e.requestJson,agentId:e.selectedAgentId,command:"lookup",payload:{name:t}}),r=(s==null?void 0:s.data)||null,a=String(((n=r==null?void 0:r.skill)==null?void 0:n.name)||t).trim()||t;return e.showToast((r==null?void 0:r.message)||`skill lookup 已执行: ${a}`,"success"),r}catch(s){return e.showToast(`skill lookup 失败: ${Le(s)}`,"error"),null}}async function W7(e){const t=String(e.primaryModelId||"").trim();if(t){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}try{await e.requestJson(ve.uiModelSwitch(e.selectedAgentId),{method:"POST",body:JSON.stringify({primaryModelId:t})},e.selectedAgentId),await e.refreshModel(e.selectedAgentId),e.showToast("agent model.primary 已更新(需重启 agent 完整生效)","success")}catch(n){e.showToast(`model.primary 更新失败: ${Le(n)}`,"error")}}}async function eD(e){const t=String(e.agentId||"").trim(),n=String(e.primaryModelId||"").trim();if(!(!t||!n))try{await e.requestJson(ve.uiModelSwitch(t),{method:"POST",body:JSON.stringify({primaryModelId:n})},t),await e.refreshDashboard(e.selectedAgentId||t),e.showToast(`已更新 ${t} 的 model.primary(需重启 agent 生效)`,"success")}catch(s){e.showToast(`agent model.primary 更新失败: ${Le(s)}`,"error")}}async function tD(e){const t=String(e.agentId||"").trim();if(t)try{await e.requestJson(ve.uiAgentExecution(),{method:"POST",body:JSON.stringify({projectRoot:t,executionMode:e.executionMode,modelId:e.modelId,localModel:e.localModel,agentType:e.agentType})},t),await e.refreshDashboard(e.selectedAgentId||t),e.showToast(`已更新 ${t} 的 execution(需重启 agent 生效)`,"success")}catch(n){e.showToast(`agent execution 更新失败: ${Le(n)}`,"error")}}async function nD(e){var n,s;const t=String(e.agentId||"").trim();if(t)try{const r=await e.requestJson(ve.uiAgentStart(),{method:"POST",body:JSON.stringify({agentId:t,initializeIfNeeded:((n=e.options)==null?void 0:n.initializeIfNeeded)===!0,initialization:(s=e.options)!=null&&s.initialization?{id:e.options.initialization.id,executionMode:e.options.initialization.executionMode,modelId:e.options.initialization.modelId,localModel:e.options.initialization.localModel,agentType:e.options.initialization.agentType}:void 0})}),a=await Cx({requestJson:e.requestJson,agentId:t,maxRetry:120,intervalMs:500});if(a.running&&a.servicesReady){await e.refreshDashboard(t),r.started===!0?e.showToast(`agent 已启动(pid ${String(r.pid||"-")})`,"success"):e.showToast("agent 已在运行","info");return}e.showToast("agent 启动超时:服务未全部就绪","error")}catch(r){e.showToast(`启动 agent 失败: ${Le(r)}`,"error")}}async function sD(e){const t=String(e.input.projectRoot||"").trim();if(t)try{const n=await e.requestJson(ve.uiAgentCreate(),{method:"POST",body:JSON.stringify({projectRoot:t,id:e.input.id,executionMode:e.input.executionMode,modelId:e.input.modelId,localModel:e.input.localModel,agentType:e.input.agentType,autoStart:e.input.autoStart!==!1})});if(e.input.autoStart===!1||n.started!==!0){await e.refreshDashboard(t),e.showToast(`agent 已创建:${String(n.id||t)}`,"success");return}const s=await Cx({requestJson:e.requestJson,agentId:t,maxRetry:120,intervalMs:500});if(s.running&&s.servicesReady){await e.refreshDashboard(t),e.showToast(`agent 已创建并启动(pid ${String(n.pid||"-")})`,"success");return}e.showToast("agent 创建成功,但启动超时:服务未全部就绪","error")}catch(n){e.showToast(`创建 agent 失败: ${Le(n)}`,"error")}}async function rD(e){const t=await e(ve.uiPickDirectory(),{method:"POST"});return String(t.directoryPath||"").trim()}async function oD(e,t){const n=String(t||"").trim();return n&&(await e(ve.uiAgentInspect(),{method:"POST",body:JSON.stringify({projectRoot:n})})).inspection||null}async function aD(e){const t=String(e.agentId||"").trim();if(t)try{await e.requestJson(ve.uiAgentRestart(),{method:"POST",body:JSON.stringify({agentId:t})});const n=await Cx({requestJson:e.requestJson,agentId:t,maxRetry:120,intervalMs:500});if(n.running&&n.servicesReady){await e.refreshDashboard(t),e.showToast("agent 已重启","success");return}e.showToast("agent 重启超时:服务未全部就绪","error")}catch(n){const s=Le(n);if(/not found/i.test(s)){e.showToast("当前 Console UI 进程版本过旧,请先重启 `city console ui` 后再重启 agent","error");return}e.showToast(`重启 agent 失败: ${s}`,"error")}}async function iD(e){const t=String(e.agentId||"").trim();if(t)try{await e.requestJson(ve.uiAgentStop(),{method:"POST",body:JSON.stringify({agentId:t})});const n=20,s=400;let r=!1;for(let a=0;a<n;a+=1){const i=await e.requestJson(ve.uiAgents(t)),u=(Array.isArray(i.agents)?i.agents:[]).find(d=>String(d.id||"")===t);if(!u||u.running!==!0){r=!0;break}await new Promise(d=>window.setTimeout(d,s))}if(await e.refreshDashboard(e.selectedAgentId||t),r){e.showToast("agent 已停止","success");return}e.showToast("agent 停止中,请稍后刷新","info")}catch(n){const s=Le(n);if(/not found/i.test(s)){e.showToast("当前 Console UI 进程版本过旧,请先重启 `city console ui` 后再停止 agent","error");return}e.showToast(`停止 agent 失败: ${s}`,"error")}}async function Is(e){try{await e.requestJson(e.path,{method:"POST",body:JSON.stringify(e.body)}),e.after&&await e.after(),e.showToast(e.successMessage,"success")}catch(t){e.showToast(`${e.errorMessage}: ${Le(t)}`,"error")}}async function lD(e){try{const t=await e.requestJson(ve.uiChannelAccountProbe(),{method:"POST",body:JSON.stringify(e.input)}),n={channel:String(t.channel||e.input.channel||"").trim(),accountId:String(t.accountId||"").trim(),name:String(t.name||"").trim(),identity:String(t.identity||"").trim()||void 0,owner:String(t.owner||"").trim()||void 0,creator:String(t.creator||"").trim()||void 0,botUserId:String(t.botUserId||"").trim()||void 0,message:String(t.message||"").trim()||void 0};return!n.accountId||!n.name?(e.showToast("bot 信息探测成功,但返回数据不完整","error"),null):(e.showToast(n.message||"bot 信息探测成功","success"),n)}catch(t){return e.showToast(`bot 信息探测失败: ${Le(t)}`,"error"),null}}async function cD(e){try{const t=await e.requestJson(ve.uiModelProviderDiscover(),{method:"POST",body:JSON.stringify(e.input)}),n={providerId:String(t.providerId||e.input.providerId||"").trim(),discoveredModels:Array.isArray(t.discoveredModels)?t.discoveredModels:[],modelCount:Number(t.modelCount||0),autoAdded:Array.isArray(t.autoAdded)?t.autoAdded:[]};return e.input.autoAdd===!0?(await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)]),e.showToast(`discover 完成:${n.modelCount} 个,自动添加 ${n.autoAdded.length} 个`,"success")):e.showToast(`discover 完成:发现 ${n.modelCount} 个模型,请选择后添加`,"success"),n}catch(t){return e.showToast(`discover 失败: ${Le(t)}`,"error"),null}}async function B0(e){try{const t=await e.requestJson(ve.uiEnvImport(),{method:"POST",body:JSON.stringify({scope:e.scope,...e.agentId?{agentId:e.agentId}:{},raw:String(e.raw||"")})});await e.refresh();const n=Number(t.count||0),s=Array.isArray(t.keys)?t.keys.map(r=>String(r||"").trim()).filter(Boolean):[];e.showToast(n>0?`已批量导入 ${n} 个${e.scope==="global"?"全局":"agent"} env${s.length?`:${s.slice(0,3).join("、")}${s.length>3?"…":""}`:""}`:`已导入 ${e.scope==="global"?"全局":"agent"} env`,"success")}catch(t){throw e.showToast(`批量导入 env 失败: ${Le(t)}`,"error"),t}}async function uD(e){const t=String(e.input.command||"").trim(),n=String(e.input.agentId||e.selectedAgentId||"").trim();if(!t)throw new Error("command 不能为空");if(!n)throw new Error("当前无可用 agent");const s=await e.requestJson(ve.uiCommandExecute(),{method:"POST",body:JSON.stringify({agentId:n,command:t,timeoutMs:e.input.timeoutMs})},n);if(!s.result)throw new Error("command 执行失败:缺少结果");return s.result}async function dD(e){try{await e.requestJson(ve.taskRun(),{method:"POST",body:JSON.stringify({title:e.title,reason:"dashboard_manual_trigger"})}),e.showToast(`task ${e.title} 已触发`,"success"),await Promise.all([e.refreshTasks(e.selectedAgentId),e.refreshLogs(e.selectedAgentId)])}catch(t){e.showToast(`task 执行失败: ${Le(t)}`,"error")}}async function fD(e){const t=String(e.title||"").trim();if(!t)return e.showToast("task title 不能为空","error"),!1;try{const n=await e.requestJson(ve.taskStatus(t),{method:"POST",body:JSON.stringify({status:e.status})},e.selectedAgentId),s=String((n==null?void 0:n.status)||e.status).trim()||e.status;return e.showToast(`task ${t} 状态已更新为 ${s}`,"success"),await Promise.all([e.refreshTasks(e.selectedAgentId),e.refreshOverview(e.selectedAgentId)]),!0}catch(n){return e.showToast(`task 状态更新失败: ${Le(n)}`,"error"),!1}}async function gD(e){const t=String(e.title||"").trim();if(!t)return e.showToast("task title 不能为空","error"),!1;try{return await e.requestJson(ve.taskDetail(t),{method:"DELETE"},e.selectedAgentId),e.showToast(`task ${t} 已删除`,"success"),await Promise.all([e.refreshTasks(e.selectedAgentId),e.refreshOverview(e.selectedAgentId),e.refreshLogs(e.selectedAgentId)]),!0}catch(n){return e.showToast(`task 删除失败: ${Le(n)}`,"error"),!1}}async function mD(e){const t=String(e.title||"").trim();if(!t)return[];try{const n=await e.requestJson(ve.taskRuns(t,e.limit||50),{},e.selectedAgentId);return Array.isArray(n.runs)?n.runs:[]}catch(n){return e.showToast(`加载 task runs 失败: ${Le(n)}`,"error"),[]}}async function hD(e){const t=String(e.title||"").trim(),n=String(e.timestamp||"").trim();if(!t||!n)return e.showToast("task title 或 run timestamp 不能为空","error"),!1;try{return await e.requestJson(ve.taskRunDetail(t,n),{method:"DELETE"},e.selectedAgentId),e.showToast(`run ${n} 已删除`,"success"),await e.refreshLogs(e.selectedAgentId),!0}catch(s){return e.showToast(`删除 run 记录失败: ${Le(s)}`,"error"),!1}}async function pD(e){const t=String(e.title||"").trim();if(!t)return e.showToast("task title 不能为空","error"),!1;try{const n=await e.requestJson(ve.taskRuns(t),{method:"DELETE"},e.selectedAgentId),s=typeof n.deletedCount=="number"&&Number.isFinite(n.deletedCount)?n.deletedCount:0,r=typeof n.skippedRunningCount=="number"&&Number.isFinite(n.skippedRunningCount)?n.skippedRunningCount:0;return r>0?e.showToast(`已清理 ${s} 条 run,跳过 ${r} 条运行中记录`,"success"):e.showToast(`已清理 ${s} 条 run 记录`,"success"),await e.refreshLogs(e.selectedAgentId),!0}catch(n){return e.showToast(`清理 run 记录失败: ${Le(n)}`,"error"),!1}}async function xD(e){const t=String(e.title||"").trim(),n=String(e.timestamp||"").trim();if(!t||!n)return null;try{return await e.requestJson(ve.taskRunDetail(t,n),{},e.selectedAgentId)}catch(s){return e.showToast(`加载 run 详情失败: ${Le(s)}`,"error"),null}}function bD(e){e.setChannelHistory([]),e.setSessionMessages([]),e.setSessionArchives([]),e.setSelectedArchiveId(""),e.setSessionArchiveMessages([]),e.setPrompt(null)}function yD(e){var r,a,i;const t=((r=e.sessions.find(l=>l.sessionId===e.currentSessionId))==null?void 0:r.sessionId)||"",n=((a=e.sessions.find(l=>l.sessionId===Js))==null?void 0:a.sessionId)||"",s=((i=e.sessions[0])==null?void 0:i.sessionId)||"";return t||n||s}function vD(e){const t=c.useCallback(async s=>{e.setLoading(!0);try{const{nextAgentId:r,list:a}=await e.refreshAgents(s);if(!r){e.setSelectedAgentId(""),e.clearPanelDataForNoAgent(),await Promise.allSettled([e.refreshGlobalPlugins(),e.refreshPlugins(""),e.refreshModel(""),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshConfigStatus("")]),e.setAgentEnvItems([]),e.setTopbarError(!1),e.setTopbarStatus("Console 在线");return}const i=a.find(d=>d.id===r)||null;if(i&&i.running!==!0){e.clearPanelDataForNoAgent(),await Promise.allSettled([e.refreshGlobalPlugins(),e.refreshPlugins(""),e.refreshModel(r),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshAgentEnv(r),e.refreshConfigStatus(r)]),e.setTopbarError(!1),e.setTopbarStatus("Console 在线");return}const[,l]=await Promise.all([e.refreshChatChannels(r),e.refreshSessions(r)]);await Promise.all([e.refreshGlobalPlugins(),e.refreshAuthorization(r),e.refreshPlugins(r),e.refreshOverview(r),e.refreshServices(r),e.refreshSkills(r),e.refreshTasks(r),e.refreshLogs(r),e.refreshModel(r),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshAgentEnv(r),e.refreshConfigStatus(r),e.refreshLocalChat(r)]);const u=yD({sessions:l,currentSessionId:String(e.selectedSessionIdRef.current||"").trim()});e.setSelectedSessionId(u),u?await Promise.all([e.refreshChannelHistory(r,u),e.refreshSessionMessages(r,u),e.refreshSessionArchives(r,u),e.refreshPrompt(r,u)]):bD({setChannelHistory:e.setChannelHistory,setSessionMessages:e.setSessionMessages,setSessionArchives:e.setSessionArchives,setSelectedArchiveId:e.setSelectedArchiveId,setSessionArchiveMessages:e.setSessionArchiveMessages,setPrompt:e.setPrompt}),e.setAuthRequired(!1),e.setTopbarError(!1),e.setTopbarStatus("Console 在线")}catch(r){const a=Le(r);if(kf(a)){const i=String(s||e.selectedAgentId||"").trim();if(i)try{const l=await e.requestJson(ve.uiAgents(i)),d=(Array.isArray(l.agents)?l.agents:[]).find(f=>String(f.id||"")===i);if((d==null?void 0:d.running)===!0){e.setSelectedAgentId(i),e.setTopbarError(!1);return}}catch{}e.clearPanelDataForNoAgent(),e.setSelectedAgentId(""),await Promise.allSettled([e.refreshGlobalPlugins(),e.refreshPlugins(""),e.refreshModel(""),e.refreshModelPool(),e.refreshChannelAccounts(),e.refreshGlobalEnv(),e.refreshConfigStatus("")]),e.setAgentEnvItems([]),e.setTopbarError(!1),e.setTopbarStatus("Console 在线");return}if(Vj(r)){e.setAuthRequired(!0),e.setTopbarError(!0),e.setTopbarStatus("需要 Bearer Token");return}e.setTopbarError(!0),e.setTopbarStatus(`连接失败: ${a}`),e.showToast(`刷新失败: ${a}`,"error")}finally{e.setLoading(!1)}},[e]),n=c.useCallback(async s=>{const r=String(s||"").trim();e.setSelectedSessionId(r),!(!e.selectedAgentId||!r)&&await Promise.all([e.refreshChannelHistory(e.selectedAgentId,r),e.refreshSessionMessages(e.selectedAgentId,r),e.refreshSessionArchives(e.selectedAgentId,r),e.refreshPrompt(e.selectedAgentId,r)])},[e]);return{refreshDashboard:t,handleSessionChange:n}}function wD(e){var t;(t=e.setSelectedSessionId)==null||t.call(e,""),e.setChannelHistory([]),e.setSessionMessages([]),e.setSessionArchives([]),e.setSelectedArchiveId(""),e.setSessionArchiveMessages([]),e.setPrompt(null)}function SD(e){var r,a,i;const t=((r=e.sessions.find(l=>l.sessionId===e.currentSessionId))==null?void 0:r.sessionId)||"",n=((a=e.sessions.find(l=>l.sessionId===Js))==null?void 0:a.sessionId)||"",s=((i=e.sessions[0])==null?void 0:i.sessionId)||"";return t||n||s}function jD(e){const t=c.useCallback(async()=>{if(e.sending)return;const a=e.chatInput.trim();if(a){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}e.setSending(!0);try{const i=String(e.selectedSessionIdRef.current||"").trim(),l=i.startsWith("consoleui-")||i==="local_ui"?i:Js;await e.requestJson(ve.sessionExecute(l),{method:"POST",body:JSON.stringify({instructions:a})}),e.setChatInput(""),await Promise.all([e.refreshLocalChat(e.selectedAgentId),e.refreshChannelHistory(e.selectedAgentId,l),e.refreshSessionMessages(e.selectedAgentId,l),e.refreshSessionArchives(e.selectedAgentId,l),e.refreshPrompt(e.selectedAgentId,l),e.refreshLogs(e.selectedAgentId),e.refreshOverview(e.selectedAgentId)]),e.showToast("已发送到 consoleui channel","success")}catch(i){e.showToast(`发送失败: ${Le(i)}`,"error")}finally{e.setSending(!1)}}},[e]),n=c.useCallback(async a=>{const i=String(a||"").trim();if(i){if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}if(!e.clearingSessionMessages){e.setClearingSessionMessages(!0);try{await e.requestJson(ve.sessionClearMessages(i),{method:"DELETE"},e.selectedAgentId),await Promise.all([e.refreshSessions(e.selectedAgentId),e.refreshChannelHistory(e.selectedAgentId,i),e.refreshSessionMessages(e.selectedAgentId,i),e.refreshSessionArchives(e.selectedAgentId,i),e.refreshPrompt(e.selectedAgentId,i),e.refreshOverview(e.selectedAgentId),e.refreshLogs(e.selectedAgentId)]),e.showToast("session messages 已清理","success")}catch(l){e.showToast(`清理 session messages 失败: ${Le(l)}`,"error")}finally{e.setClearingSessionMessages(!1)}}}},[e]),s=c.useCallback(async a=>{const i=String(a||"").trim();if(i){if(v7(i)){await n(i);return}if(!e.selectedAgentId){e.showToast("当前无可用 agent","error");return}if(!e.clearingChatHistory){e.setClearingChatHistory(!0);try{await e.requestJson(ve.sessionClearChatHistory(i),{method:"DELETE"},e.selectedAgentId),await Promise.all([e.refreshChannelHistory(e.selectedAgentId,i),e.refreshLogs(e.selectedAgentId)]),e.showToast("chat history 已清理","success")}catch(l){e.showToast(`清理 chat history 失败: ${Le(l)}`,"error")}finally{e.setClearingChatHistory(!1)}}}},[n,e]),r=c.useCallback(async a=>{var l;const i=String(a||"").trim();if(!i)return!1;if(!e.selectedAgentId)return e.showToast("当前无可用 agent","error"),!1;if(e.deletingSessionId)return!1;e.setDeletingSessionId(i);try{const u=await e.requestJson(ve.servicesCommand(),{method:"POST",body:JSON.stringify({serviceName:"chat",command:"delete",payload:{sessionId:i}})},e.selectedAgentId),d=((l=u==null?void 0:u.data)==null?void 0:l.deleted)===!0,f=await e.refreshSessions(e.selectedAgentId),g=SD({sessions:f,currentSessionId:String(e.selectedSessionIdRef.current||"").trim()});return g?(e.setSelectedSessionId(g),await Promise.all([e.refreshChannelHistory(e.selectedAgentId,g),e.refreshSessionMessages(e.selectedAgentId,g),e.refreshSessionArchives(e.selectedAgentId,g),e.refreshPrompt(e.selectedAgentId,g)])):wD({setSelectedSessionId:e.setSelectedSessionId,setChannelHistory:e.setChannelHistory,setSessionMessages:e.setSessionMessages,setSessionArchives:e.setSessionArchives,setSelectedArchiveId:e.setSelectedArchiveId,setSessionArchiveMessages:e.setSessionArchiveMessages,setPrompt:e.setPrompt}),await Promise.all([e.refreshChatChannels(e.selectedAgentId),e.refreshOverview(e.selectedAgentId),e.refreshLogs(e.selectedAgentId),e.refreshLocalChat(e.selectedAgentId)]),e.showToast(d?`已删除 session: ${i}`:`session 不存在,已同步状态: ${i}`,"success"),d}catch(u){return e.showToast(`删除 session 失败: ${Le(u)}`,"error"),!1}finally{e.setDeletingSessionId("")}},[e]);return{sendConsoleUiMessage:t,clearSessionMessages:n,clearChatHistory:s,deleteChatSession:r}}function CD(e){const t=c.useCallback(async z=>{await W7({requestJson:e.requestJson,primaryModelId:z,selectedAgentId:e.selectedAgentId,refreshModel:e.refreshModel,showToast:e.showToast})},[e]),n=c.useCallback(async(z,N)=>{await eD({requestJson:e.requestJson,agentId:z,primaryModelId:N,selectedAgentId:e.selectedAgentId,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),s=c.useCallback(async(z,N)=>{await nD({requestJson:e.requestJson,agentId:z,options:N,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),r=c.useCallback(async z=>{await sD({requestJson:e.requestJson,input:z,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),a=c.useCallback(async()=>rD(e.requestJson),[e]),i=c.useCallback(async z=>oD(e.requestJson,z),[e]),l=c.useCallback(async z=>{await aD({requestJson:e.requestJson,agentId:z,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),u=c.useCallback(async z=>{await iD({requestJson:e.requestJson,agentId:z,selectedAgentId:e.selectedAgentId,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),d=c.useCallback(async z=>{await tD({requestJson:e.requestJson,agentId:z.agentId,executionMode:z.executionMode,modelId:z.modelId,localModel:z.localModel,agentType:z.agentType,selectedAgentId:e.selectedAgentId,refreshDashboard:e.refreshDashboard,showToast:e.showToast})},[e]),f=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiModelProviderUpsert(),body:z,successMessage:`provider ${z.id} 已保存`,errorMessage:"provider 保存失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),g=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiModelProviderRemove(),body:{providerId:z},successMessage:`provider ${z} 已删除`,errorMessage:"provider 删除失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),m=c.useCallback(async z=>{try{const N=await e.requestJson(ve.uiModelProviderTest(),{method:"POST",body:JSON.stringify({providerId:z})});e.showToast(`provider ${z} 测试通过,发现 ${Number(N.modelCount||0)} 个模型`,"success")}catch(N){e.showToast(`provider 测试失败: ${Le(N)}`,"error")}},[e]),h=c.useCallback(async z=>cD({requestJson:e.requestJson,input:z,selectedAgentId:e.selectedAgentId,refreshModelPool:e.refreshModelPool,refreshModel:e.refreshModel,showToast:e.showToast}),[e]),x=c.useCallback(async z=>{var N,H,R,I,T,E;await Is({requestJson:e.requestJson,path:ve.uiModelItemUpsert(),body:{...z,temperature:((N=z.temperature)==null?void 0:N.trim())||void 0,maxTokens:((H=z.maxTokens)==null?void 0:H.trim())||void 0,topP:((R=z.topP)==null?void 0:R.trim())||void 0,frequencyPenalty:((I=z.frequencyPenalty)==null?void 0:I.trim())||void 0,presencePenalty:((T=z.presencePenalty)==null?void 0:T.trim())||void 0,anthropicVersion:((E=z.anthropicVersion)==null?void 0:E.trim())||void 0},successMessage:`model ${z.id} 已保存`,errorMessage:"model 保存失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),y=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiModelItemRemove(),body:{modelId:z},successMessage:`model ${z} 已删除`,errorMessage:"model 删除失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),w=c.useCallback(async(z,N)=>{await Is({requestJson:e.requestJson,path:ve.uiModelItemPause(),body:{modelId:z,isPaused:N},successMessage:`model ${z} 已${N?"暂停":"恢复"}`,errorMessage:"model 状态更新失败",after:async()=>{await Promise.all([e.refreshModelPool(),e.refreshModel(e.selectedAgentId)])},showToast:e.showToast})},[e]),b=c.useCallback(async(z,N)=>{try{await e.requestJson(ve.uiModelItemTest(),{method:"POST",body:JSON.stringify({modelId:z,prompt:String(N||"").trim()||void 0})}),e.showToast(`model ${z} 测试通过`,"success")}catch(H){e.showToast(`model 测试失败: ${Le(H)}`,"error")}},[e]),p=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiChannelAccountUpsert(),body:z,successMessage:`channel account ${z.id} 已确认`,errorMessage:"channel account 确认失败",after:async()=>{await Promise.all([e.refreshChannelAccounts(),e.refreshChatChannels(e.selectedAgentId)])},showToast:e.showToast})},[e]),v=c.useCallback(async z=>lD({requestJson:e.requestJson,input:z,showToast:e.showToast}),[e]),S=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiChannelAccountRemove(),body:{id:z},successMessage:`channel account ${z} 已删除`,errorMessage:"channel account 删除失败",after:async()=>{await Promise.all([e.refreshChannelAccounts(),e.refreshChatChannels(e.selectedAgentId)])},showToast:e.showToast})},[e]),j=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiEnvUpsert(),body:{scope:"global",key:String(z.key||"").trim(),description:String(z.description||"").trim(),value:String(z.value??"")},successMessage:`env ${String(z.key||"").trim()} 已保存`,errorMessage:"env 保存失败",after:async()=>{await e.refreshGlobalEnv()},showToast:e.showToast})},[e]),C=c.useCallback(async z=>{await B0({requestJson:e.requestJson,scope:"global",raw:z,refresh:e.refreshGlobalEnv,showToast:e.showToast})},[e]),A=c.useCallback(async z=>{await Is({requestJson:e.requestJson,path:ve.uiEnvRemove(),body:{scope:"global",key:String(z||"").trim()},successMessage:`env ${String(z||"").trim()} 已删除`,errorMessage:"env 删除失败",after:async()=>{await e.refreshGlobalEnv()},showToast:e.showToast})},[e]),M=c.useCallback(async z=>{const N=String(z.agentId||"").trim();if(!N){e.showToast("当前没有可写入的 agent","error");return}await Is({requestJson:e.requestJson,path:ve.uiEnvUpsert(),body:{scope:"agent",agentId:N,key:String(z.key||"").trim(),description:String(z.description||"").trim(),value:String(z.value??"")},successMessage:`agent env ${String(z.key||"").trim()} 已保存`,errorMessage:"agent env 保存失败",after:async()=>{await e.refreshAgentEnv(N)},showToast:e.showToast})},[e]),O=c.useCallback(async(z,N)=>{const H=String(z||"").trim();if(!H){e.showToast("当前没有可删除的 agent env","error");return}await Is({requestJson:e.requestJson,path:ve.uiEnvRemove(),body:{scope:"agent",agentId:H,key:String(N||"").trim()},successMessage:`agent env ${String(N||"").trim()} 已删除`,errorMessage:"agent env 删除失败",after:async()=>{await e.refreshAgentEnv(H)},showToast:e.showToast})},[e]),P=c.useCallback(async(z,N)=>{const H=String(z||"").trim();if(!H)throw e.showToast("当前没有可写入的 agent","error"),new Error("agentId is required");await B0({requestJson:e.requestJson,scope:"agent",agentId:H,raw:N,refresh:async()=>e.refreshAgentEnv(H),showToast:e.showToast})},[e]),$=c.useCallback(async z=>uD({requestJson:e.requestJson,input:z,selectedAgentId:e.selectedAgentId}),[e]);return{switchModel:t,switchModelForAgent:n,updateAgentExecution:d,startAgentFromHistory:s,createAgent:r,pickAgentDirectory:a,inspectAgentDirectory:i,restartAgentFromHistory:l,stopAgentFromHistory:u,upsertModelProvider:f,removeModelProvider:g,testModelProvider:m,discoverModelProvider:h,upsertModelPoolItem:x,removeModelPoolItem:y,setModelPoolItemPaused:w,testModelPoolItem:b,upsertChannelAccount:p,probeChannelAccount:v,removeChannelAccount:S,upsertGlobalEnv:j,importGlobalEnv:C,removeGlobalEnv:A,upsertAgentEnv:M,removeAgentEnv:O,importAgentEnv:P,executeAgentCommand:$}}async function kD(e){return e(ve.authMe())}async function ND(e){return e(ve.authTokenList())}async function TD(e){return(await e.requestJson(ve.authTokenCreate(),{method:"POST",body:JSON.stringify(e.input)})).token}async function AD(e){await e.requestJson(ve.authTokenDelete(),{method:"POST",body:JSON.stringify({tokenId:e.tokenId})})}function ED(e){const{enabled:t,requestJson:n,showToast:s}=e,[r,a]=c.useState(null),[i,l]=c.useState([]),[u,d]=c.useState(!1),[f,g]=c.useState(null),m=c.useCallback(async()=>{if(!t){a(null),l([]);return}d(!0);try{const[w,b]=await Promise.all([kD(n),ND(n)]);a(w.user||null),l(Array.isArray(b.tokens)?b.tokens:[])}finally{d(!1)}},[t,n]),h=c.useCallback(async w=>{const b=await TD({requestJson:n,input:w});g(b),s(`已签发 token ${b.name}`,"success"),await m()},[m,n,s]),x=c.useCallback(async w=>{await AD({requestJson:n,tokenId:w.tokenId}),s("已删除 token","success"),await m()},[m,n,s]),y=c.useCallback(()=>{g(null)},[]);return c.useEffect(()=>{if(!t){a(null),l([]),g(null);return}m().catch(w=>{s(Le(w),"error")})},[t,m,s]),{accessUser:r,accessTokens:i,accessLoading:u,latestIssuedAccessToken:f,clearLatestIssuedAccessToken:y,refreshAccess:m,createAccessToken:h,deleteAccessToken:x}}function MD(){const e=Id(),[t,n]=c.useState(!(e!=null&&e.token)),[s,r]=c.useState(!1),[a,i]=c.useState(!!(e!=null&&e.token)),[l,u]=c.useState(String((e==null?void 0:e.username)||"").trim()),[d,f]=c.useState(!1),[g,m]=c.useState(!1),[h,x]=c.useState(""),[y,w]=c.useState([]),[b,p]=c.useState(""),[v,S]=c.useState(""),[j,C]=c.useState(null),[A,M]=c.useState(null),[O,P]=c.useState([]),[$,z]=c.useState([]),[N,H]=c.useState([]),[R,I]=c.useState([]),[T,E]=c.useState([]),[q,k]=c.useState([]),[D,B]=c.useState(""),[Q,Z]=c.useState([]),[te,se]=c.useState([]),[ie,oe]=c.useState([]),[pe,_]=c.useState(""),[Y,le]=c.useState([]),[ne,ue]=c.useState([]),[ae,xe]=c.useState([]),[ee,W]=c.useState(null),[X,G]=c.useState([]),[L,J]=c.useState([]),[me,ge]=c.useState([]),[U,ce]=c.useState([]),[F,K]=c.useState([]),[he,Te]=c.useState([]),[Se,Fe]=c.useState(null),[Ae,Re]=c.useState([]),[Ye,yt]=c.useState("连接中..."),[De,ot]=c.useState(!1),[_e,Je]=c.useState(!1),[jt,Ct]=c.useState(!1),[zt,Ce]=c.useState(!1),[rt,et]=c.useState(!1),[$e,Ht]=c.useState(""),[zn,ms]=c.useState(""),[Bs,In]=c.useState(null),Sn=c.useRef(null),Jn=c.useRef(""),vt=c.useRef(""),Ft=c.useRef(null),Es=c.useRef("unknown");c.useEffect(()=>{Jn.current=D},[D]),c.useEffect(()=>{vt.current=pe},[pe]);const Aa=c.useMemo(()=>y.find(de=>de.id===v)||null,[y,v]),Ue=c.useCallback((de,Oe="info")=>{In({message:de,type:Oe}),Sn.current&&window.clearTimeout(Sn.current),Sn.current=window.setTimeout(()=>{In(null),Sn.current=null},2200)},[]),Ms=c.useCallback(()=>{D0(),n(!1),r(!1),i(!1),u(""),f(!0),x(""),yt("需要 Bearer Token"),ot(!1)},[]),ye=c.useCallback(async(de,Oe={},tt)=>{try{return await Bu({path:de,options:Oe,selectedAgentId:v,preferredAgentId:tt})}catch(kt){throw Vj(kt)&&Ms(),kt}},[Ms,v]),{accessUser:Ea,accessTokens:Nf,accessLoading:Tf,latestIssuedAccessToken:Af,clearLatestIssuedAccessToken:Ef,refreshAccess:Mf,createAccessToken:Rf,deleteAccessToken:Of}=ED({enabled:a&&!t&&!d,requestJson:ye,showToast:Ue}),zf=c.useCallback(async de=>{var Oe,tt;m(!0),x("");try{const kt=String(de.token||"").trim();if(!kt)throw new Error("请先输入 Bearer Token");const $s=await Bu({path:ve.authMe(),selectedAgentId:"",options:{headers:{Authorization:/^Bearer\s+/i.test(kt)?kt:`Bearer ${kt}`}}}),Tc=kt.replace(/^Bearer\s+/i,"").trim(),Ra=String(((Oe=$s==null?void 0:$s.user)==null?void 0:Oe.username)||"").trim();m7({token:Tc,...Ra?{username:Ra}:{}}),n(!1),r(!1),i(!0),u(Ra),f(!1),await((tt=Ft.current)==null?void 0:tt.call(Ft))}catch(kt){throw D0(),i(!1),u(""),f(!0),x(Le(kt)),kt}finally{m(!1)}},[]),If=c.useCallback(()=>{Ms()},[Ms]),Df=c.useCallback(()=>{C(null),M(null),P([]),z([]),I([]),E([]),k([]),B(""),Z([]),se([]),oe([]),_(""),le([]),ue([]),xe([]),Fe(null),Re([])},[]),_f=c.useCallback(async de=>{const Oe=await S7({requestJson:ye,preferredAgentId:de,selectedAgentId:v});Oe.cityVersion&&p(Oe.cityVersion);const tt=Oe.list,kt=Oe.nextAgentId;return w(tt),{nextAgentId:kt,list:tt}},[ye,v]),Pr=c.useCallback(async de=>{de&&C(await j7(ye,de))},[ye]),Po=c.useCallback(async de=>{de&&P(await C7(ye,de))},[ye]),Ps=c.useCallback(async de=>{de&&z(await k7(ye,de))},[ye]),Vi=c.useCallback(async()=>{const de=await _0(ye);return H(de),de},[ye]),or=c.useCallback(async de=>{if(!de){I([]);return}const Oe=await _0(ye,de);return I(Oe),Oe},[ye]),ar=c.useCallback(async de=>{if(!de)return[];const Oe=await T7(ye,de);return E(Oe),Oe},[ye]),Nn=c.useCallback(async de=>{if(!de)return[];const Oe=await A7(ye,de);return k(Oe),Oe},[ye]),Yi=c.useCallback(async(de,Oe)=>{!de||!Oe||Z(await E7(ye,de,Oe))},[ye]),Ki=c.useCallback(async(de,Oe)=>{!de||!Oe||se(await M7(ye,de,Oe))},[ye]),$r=c.useCallback(async(de,Oe,tt)=>{if(!de||!Oe||!tt){_(""),le([]);return}if(Es.current==="unsupported"){_(""),le([]);return}try{const kt=await R7(ye,de,Oe,tt);Es.current="supported",_(tt),le(Array.isArray(kt.messages)?kt.messages:[])}catch(kt){const $s=Le(kt);if(mh($s)){Es.current="unsupported",_(""),le([]);return}throw kt}},[ye]),Ur=c.useCallback(async(de,Oe)=>{var Ra;if(!de||!Oe)return oe([]),_(""),le([]),[];if(Es.current==="unsupported")return oe([]),_(""),le([]),[];let tt=[];try{tt=await O7(ye,de,Oe),Es.current="supported"}catch(Ac){const PC=Le(Ac);if(!mh(PC))throw Ac;Es.current="unsupported",tt=[]}oe(tt);const kt=String(vt.current||"").trim(),$s=String(((Ra=tt[0])==null?void 0:Ra.archiveId)||"").trim(),Tc=tt.some(Ac=>String(Ac.archiveId||"").trim()===kt)?kt:$s;return Tc?(await $r(de,Oe,Tc),tt):(_(""),le([]),tt)},[$r,ye]),Yt=c.useCallback(async de=>{de&&ue(await z7(ye,de))},[ye]),gn=c.useCallback(async de=>{de&&xe(await I7(ye,de))},[ye]),Hr=c.useCallback(async de=>{W(await D7(ye,de))},[ye]),ir=c.useCallback(async de=>{G(await _7(ye,de))},[ye]),Kt=c.useCallback(async()=>{const de=await L7(ye);J(de.providers),ge(de.models)},[ye]),Xi=c.useCallback(async()=>{K(await B7(ye))},[ye]),Fr=c.useCallback(async de=>{if(!de){Te([]);return}Te(await P7(ye,de))},[ye]),kc=c.useCallback(async()=>{ce(await $7(ye))},[ye]),Ma=c.useCallback(async(de,Oe)=>{if(!de)return;const tt=String(Oe||Js).trim()||Js;Fe(await U7(ye,de,tt))},[ye]),Zi=c.useCallback(async de=>{de&&Re(await H7(ye,de))},[ye]),Nc=c.useCallback(async de=>{de&&M(await F7(ye,de))},[ye]),{refreshDashboard:lr,handleSessionChange:V}=vD({requestJson:ye,selectedAgentId:v,selectedSessionIdRef:Jn,setSelectedAgentId:S,setSelectedSessionId:B,setAgentEnvItems:Te,setTopbarError:ot,setTopbarStatus:yt,setLoading:Je,setChannelHistory:Z,setSessionMessages:se,setSessionArchives:oe,setSelectedArchiveId:_,setSessionArchiveMessages:le,setPrompt:Fe,clearPanelDataForNoAgent:Df,refreshAgents:_f,refreshGlobalPlugins:Vi,refreshPlugins:or,refreshModel:Hr,refreshModelPool:Kt,refreshChannelAccounts:kc,refreshGlobalEnv:Xi,refreshConfigStatus:ir,refreshAgentEnv:Fr,refreshChatChannels:ar,refreshSessions:Nn,refreshAuthorization:Nc,refreshOverview:Pr,refreshServices:Po,refreshSkills:Ps,refreshTasks:Yt,refreshLogs:gn,refreshLocalChat:Zi,refreshChannelHistory:Yi,refreshSessionMessages:Ki,refreshSessionArchives:Ur,refreshPrompt:Ma,showToast:Ue,setAuthRequired:f}),re=c.useCallback(async(de,Oe)=>{await q7({requestJson:ye,serviceName:de,action:Oe,selectedAgentId:v,refreshServices:Po,refreshSkills:Ps,showToast:Ue})},[Po,Ps,ye,v,Ue]),Ke=c.useCallback(async(de,Oe,tt)=>L0({requestJson:ye,pluginName:de,actionName:Oe,payload:tt,selectedAgentId:v,refreshPlugins:or,scope:"agent",showToast:Ue}),[or,ye,v,Ue]),It=c.useCallback(async(de,Oe,tt)=>L0({requestJson:ye,pluginName:de,actionName:Oe,payload:tt,selectedAgentId:v,refreshPlugins:or,refreshGlobalPlugins:Vi,scope:"global",showToast:Ue}),[Vi,or,ye,v,Ue]),jn=c.useCallback(async de=>N7(ye,de),[ye]),Rs=c.useCallback(async(de,Oe)=>{await V7({requestJson:ye,action:de,channel:Oe,chatChannels:T,selectedAgentId:v,refreshChatChannels:ar,refreshServices:Po,showToast:Ue})},[T,ar,Po,ye,v,Ue]),Kj=c.useCallback(async(de,Oe)=>{await Y7({requestJson:ye,channel:de,config:Oe,selectedAgentId:v,refreshDashboard:lr,showToast:Ue})},[lr,ye,v,Ue]),Xj=c.useCallback(async de=>{await K7({requestJson:ye,config:de,selectedAgentId:v,setAuthorization:M,showToast:Ue})},[ye,v,Ue]),Zj=c.useCallback(async de=>{await X7({requestJson:ye,input:de,selectedAgentId:v,setAuthorization:M,showToast:Ue})},[ye,v,Ue]),Jj=c.useCallback(async de=>Z7({requestJson:ye,query:de,selectedAgentId:v,refreshSkills:Ps,showToast:Ue}),[Ps,ye,v,Ue]),Qj=c.useCallback(async de=>J7({requestJson:ye,input:de,selectedAgentId:v,refreshSkills:Ps,showToast:Ue}),[Ps,ye,v,Ue]),Wj=c.useCallback(async de=>Q7({requestJson:ye,name:de,selectedAgentId:v,showToast:Ue}),[ye,v,Ue]),eC=c.useCallback(async de=>{await dD({requestJson:ye,title:de,selectedAgentId:v,refreshTasks:Yt,refreshLogs:gn,showToast:Ue})},[gn,Yt,ye,v,Ue]),tC=c.useCallback(async(de,Oe)=>fD({requestJson:ye,title:de,status:Oe,selectedAgentId:v,refreshTasks:Yt,refreshOverview:Pr,showToast:Ue}),[Pr,Yt,ye,v,Ue]),nC=c.useCallback(async de=>gD({requestJson:ye,title:de,selectedAgentId:v,refreshTasks:Yt,refreshOverview:Pr,refreshLogs:gn,showToast:Ue}),[gn,Pr,Yt,ye,v,Ue]),sC=c.useCallback(async(de,Oe=50)=>mD({requestJson:ye,title:de,limit:Oe,selectedAgentId:v,showToast:Ue}),[ye,v,Ue]),rC=c.useCallback(async(de,Oe)=>hD({requestJson:ye,title:de,timestamp:Oe,selectedAgentId:v,refreshLogs:gn,showToast:Ue}),[gn,ye,v,Ue]),oC=c.useCallback(async de=>pD({requestJson:ye,title:de,selectedAgentId:v,refreshLogs:gn,showToast:Ue}),[gn,ye,v,Ue]),aC=c.useCallback(async(de,Oe)=>xD({requestJson:ye,title:de,timestamp:Oe,selectedAgentId:v,showToast:Ue}),[ye,v,Ue]),{sendConsoleUiMessage:iC,clearSessionMessages:lC,clearChatHistory:cC,deleteChatSession:uC}=jD({requestJson:ye,selectedAgentId:v,chatInput:zn,sending:jt,clearingSessionMessages:zt,clearingChatHistory:rt,deletingSessionId:$e,selectedSessionIdRef:Jn,setSending:Ct,setClearingSessionMessages:Ce,setClearingChatHistory:et,setDeletingSessionId:Ht,setChatInput:ms,setSelectedSessionId:B,setChannelHistory:Z,setSessionMessages:se,setSessionArchives:oe,setSelectedArchiveId:_,setSessionArchiveMessages:le,setPrompt:Fe,refreshLocalChat:Zi,refreshChannelHistory:Yi,refreshSessionMessages:Ki,refreshSessionArchives:Ur,refreshPrompt:Ma,refreshLogs:gn,refreshOverview:Pr,refreshSessions:Nn,refreshChatChannels:ar,showToast:Ue}),{switchModel:dC,switchModelForAgent:fC,updateAgentExecution:gC,startAgentFromHistory:mC,createAgent:hC,pickAgentDirectory:pC,inspectAgentDirectory:xC,restartAgentFromHistory:bC,stopAgentFromHistory:yC,upsertModelProvider:vC,removeModelProvider:wC,testModelProvider:SC,discoverModelProvider:jC,upsertModelPoolItem:CC,removeModelPoolItem:kC,setModelPoolItemPaused:NC,testModelPoolItem:TC,upsertChannelAccount:AC,probeChannelAccount:EC,removeChannelAccount:MC,upsertGlobalEnv:RC,importGlobalEnv:OC,removeGlobalEnv:zC,upsertAgentEnv:IC,removeAgentEnv:DC,importAgentEnv:_C,executeAgentCommand:LC}=CD({requestJson:ye,selectedAgentId:v,refreshDashboard:lr,refreshModel:Hr,refreshModelPool:Kt,refreshChannelAccounts:kc,refreshChatChannels:ar,refreshGlobalEnv:Xi,refreshAgentEnv:Fr,showToast:Ue}),BC=c.useCallback(de=>{S(de),lr(de)},[lr]);return c.useEffect(()=>{Ft.current=lr},[lr]),c.useEffect(()=>{let de=!1;return(async()=>{const tt=Id(),kt=!!(tt!=null&&tt.token);if(i(kt),u(String((tt==null?void 0:tt.username)||"").trim()),kt){if(de)return;r(!1),f(!1),n(!1);return}try{const $s=await Bu({path:ve.authStatus(),selectedAgentId:""});if(!$s.initialized){if(de)return;r(!0),f(!0),n(!1),yt("需要先创建 Token"),ot(!1);return}if($s.requireToken&&!kt){if(de)return;r(!1),f(!0),n(!1),yt("需要 Bearer Token"),ot(!1);return}}catch{}de||(r(!1),f(!0),yt("需要 Bearer Token"),ot(!1),n(!1))})(),()=>{de=!0}},[]),c.useEffect(()=>{var Oe;if(t||d&&!a)return;(Oe=Ft.current)==null||Oe.call(Ft);const de=window.setInterval(()=>{var tt;d&&!a||(tt=Ft.current)==null||tt.call(Ft)},12e3);return()=>{window.clearInterval(de),Sn.current&&window.clearTimeout(Sn.current)}},[t,d,a]),{authInitializing:t,authBootstrapRequired:s,isAuthenticated:a,authUsername:l,authRequired:d,authSubmitting:g,authErrorMessage:h,agents:y,cityVersion:b,selectedAgentId:v,selectedAgent:Aa,overview:j,authorization:A,accessUser:Ea,accessTokens:Nf,accessLoading:Tf,latestIssuedAccessToken:Af,services:O,skills:$,plugins:N,agentPlugins:R,chatChannels:T,sessions:q,selectedSessionId:D,channelHistory:Q,sessionMessages:te,sessionArchives:ie,selectedArchiveId:pe,sessionArchiveMessages:Y,tasks:ne,logs:ae,model:ee,configStatus:X,modelProviders:L,modelPoolItems:me,channelAccounts:U,globalEnvItems:F,agentEnvItems:he,prompt:Se,localMessages:Ae,topbarStatus:Ye,topbarError:De,loading:_e,sending:jt,clearingSessionMessages:zt,clearingChatHistory:rt,deletingSessionId:$e,chatInput:zn,toast:Bs,setChatInput:ms,handleAgentChange:BC,handleSessionChange:V,refreshDashboard:lr,refreshAuthorization:Nc,refreshAccess:Mf,refreshChatChannels:ar,refreshPlugins:or,loadLocalModels:jn,refreshSkills:Ps,refreshSessions:Nn,refreshChannelHistory:Yi,refreshSessionMessages:Ki,refreshSessionArchives:Ur,loadSessionArchiveMessages:$r,refreshPrompt:Ma,refreshModel:Hr,refreshModelPool:Kt,refreshGlobalEnv:Xi,refreshAgentEnv:Fr,refreshConfigStatus:ir,refreshLocalChat:Zi,controlService:re,runGlobalPluginAction:It,runPluginAction:Ke,runChatChannelAction:Rs,configureChatChannel:Kj,saveAuthorizationConfig:Xj,runAuthorizationAction:Zj,clearLatestIssuedAccessToken:Ef,createAccessToken:Rf,deleteAccessToken:Of,runSkillFind:Jj,runSkillInstall:Qj,runSkillLookup:Wj,runTask:eC,setTaskStatus:tC,deleteTask:nC,loadTaskRuns:sC,deleteTaskRun:rC,clearTaskRuns:oC,loadTaskRunDetail:aC,sendConsoleUiMessage:iC,clearSessionMessages:lC,clearChatHistory:cC,deleteChatSession:uC,switchModel:dC,switchModelForAgent:fC,updateAgentExecution:gC,startAgentFromHistory:mC,createAgent:hC,pickAgentDirectory:pC,inspectAgentDirectory:xC,restartAgentFromHistory:bC,stopAgentFromHistory:yC,upsertModelProvider:vC,removeModelProvider:wC,testModelProvider:SC,discoverModelProvider:jC,upsertModelPoolItem:CC,removeModelPoolItem:kC,setModelPoolItemPaused:NC,testModelPoolItem:TC,upsertChannelAccount:AC,probeChannelAccount:EC,removeChannelAccount:MC,upsertGlobalEnv:RC,removeGlobalEnv:zC,importGlobalEnv:OC,upsertAgentEnv:IC,removeAgentEnv:DC,importAgentEnv:_C,executeAgentCommand:LC,constants:{CONSOLEUI_SESSION_ID:Js},uiHelpers:{formatTime:x7,statusBadgeVariant:p7},submitAuthToken:zf,logout:If}}function RD(e){return e instanceof Lu?e.message:e instanceof Error&&e.message||String(e)}function Ug(e,t){return{name:String(e.agentId||e.id||"agent").trim()||"agent",running:!1,statusText:"当前还没有对外可见的新动态",collectedAt:t,headline:"当前处于安静待命的状态",posture:"静候下一步",momentum:"安静",visibilityNote:"这里展示的是面向外部的概览状态,不包含内部上下文细节。",current:[{id:`idle:${e.id}`,kind:"idle",title:"当前处于安静待命",summary:"等待新的输入、触发或下一次启动。",status:"waiting",updatedAt:t,tags:["public","idle"]}],recent:[],signals:[{label:"状态节奏",value:"安静待命",tone:"neutral"},{label:"现场感受",value:"整体平稳",tone:"neutral"},{label:"活跃温度",value:"较为安静",tone:"neutral"}]}}function gu(e,t){return{id:e,name:t.name,running:t.running,headline:t.headline,posture:t.posture,momentum:t.momentum,statusText:t.statusText,collectedAt:t.collectedAt,currentCount:t.current.length,recentCount:t.recent.length,signalCount:t.signals.length,snapshot:t}}async function OD(e){const t=new Date().toISOString(),n=String(e.agent.id||"").trim();if(!n||e.agent.running!==!0)return gu(n||`idle:${t}`,Ug(e.agent,t));try{const s=await Bu({path:ve.workboardSnapshot(),selectedAgentId:e.selectedAgentId,preferredAgentId:n});if(!s.snapshot)return gu(n,Ug(e.agent,t));const r={name:s.snapshot.agent.name,running:s.snapshot.agent.running,statusText:s.snapshot.agent.statusText,collectedAt:s.snapshot.agent.collectedAt,headline:s.snapshot.summary.headline,posture:s.snapshot.summary.posture,momentum:s.snapshot.summary.momentum,visibilityNote:s.snapshot.summary.visibilityNote,current:s.snapshot.current||[],recent:s.snapshot.recent||[],signals:s.snapshot.signals||[]};return gu(n,r)}catch{const s=Ug({...e.agent},t);return s.statusText="当前状态暂时无法更新",s.headline="当前状态暂时不可见",s.posture="稍后再看",s.momentum="轻微中断",s.current=[{id:`issue:${n}`,kind:"idle",title:"公开状态暂时不可见",summary:"这位 agent 仍然在线,但当前公开板面没有返回最新状态。",status:"issue",updatedAt:t,tags:["public","issue"]}],s.signals=[{label:"状态节奏",value:"暂时中断",tone:"warning"},{label:"现场感受",value:"有些波动",tone:"warning"},{label:"活跃温度",value:"稍后再看",tone:"neutral"}],gu(n,s)}}function zD(e){return[...e].sort((t,n)=>t.running!==n.running?t.running?-1:1:t.currentCount!==n.currentCount?n.currentCount-t.currentCount:t.name.localeCompare(n.name))}function ID(e){const[t,n]=c.useState(null),[s,r]=c.useState(!1),[a,i]=c.useState(""),l=c.useCallback(async()=>{const u=Array.isArray(e.agents)?e.agents:[];if(!e.enabled||u.length===0){n(null),i(""),r(!1);return}r(!0);try{const d=await Promise.all(u.map(y=>OD({agent:y,selectedAgentId:e.selectedAgentId}))),f=zD(d),g=f.filter(y=>y.running).length,m=f.filter(y=>y.snapshot.current.some(w=>w.status==="active")).length,h=f.filter(y=>y.snapshot.momentum==="安静").length,x=new Date().toISOString();n({summary:{totalAgents:f.length,liveAgents:g,activeAgents:m,quietAgents:h},agents:f,collectedAt:x}),i("")}catch(d){i(RD(d))}finally{r(!1)}},[e.agents,e.enabled,e.selectedAgentId]);return c.useEffect(()=>{l()},[l]),c.useEffect(()=>{if(!e.enabled||e.agents.length===0)return;const u=window.setInterval(()=>{l()},5e3);return()=>window.clearInterval(u)},[e.agents.length,e.enabled,l]),{board:t,loading:s,errorMessage:a,refresh:l}}const DD=Dz();function P0(e){const t=String(e||"").trim().toLocaleLowerCase();return t&&t.replace(/[\s_]+/g,"-").replace(/[/?#]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Ko(e){const t=String(e||"").trim().toLocaleLowerCase();return t&&t.replace(/[\s_]+/g,"-").replace(/[/?#]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"agent"}function $0(e,t){const n=Ko(String((t==null?void 0:t.agentSegment)||"agent"));if(e==="globalOverview")return String((t==null?void 0:t.agentSegment)||"").trim()?`/global/agent/${encodeURIComponent(n)}`:"/global/overview";if(e==="globalWorkboard")return"/global/workboard";if(e==="globalApiKeys")return"/global/api-keys";if(e==="globalEnv")return"/global/env";if(e==="globalModel")return"/global/model";if(e==="globalChannelAccounts")return"/global/channel-accounts";if(e==="globalCommand")return"/global/command";if(e==="globalAgents")return"/global/agents";if(e==="globalPlugins")return"/global/plugins";if(e==="agentOverview")return`/${encodeURIComponent(n)}/overview`;if(e==="agentAuthorization")return`/${encodeURIComponent(n)}/authorization`;if(e==="agentPlugins")return`/${encodeURIComponent(n)}/plugins`;if(e==="agentSkills")return`/${encodeURIComponent(n)}/skills`;if(e==="agentServices")return`/${encodeURIComponent(n)}/services`;if(e==="agentCommand")return`/${encodeURIComponent(n)}/command`;if(e==="agentTasks"){const s=String((t==null?void 0:t.taskTitle)||"").trim();return s?`/${encodeURIComponent(n)}/tasks/${encodeURIComponent(s)}`:`/${encodeURIComponent(n)}/tasks`}if(e==="agentLogs")return`/${encodeURIComponent(n)}/logs`;if(e==="contextOverview"){const s=P0(String((t==null?void 0:t.channel)||""));return`/${encodeURIComponent(n)}/channel/${encodeURIComponent(s)}`}if(e==="contextWorkspace"){const s=String((t==null?void 0:t.sessionId)||"").trim(),r=P0(String((t==null?void 0:t.channel)||""));return s?`/${encodeURIComponent(n)}/channel/${encodeURIComponent(r)}/chat/${encodeURIComponent(s)}`:`/${encodeURIComponent(n)}/channel/${encodeURIComponent(r)}`}return"/global/overview"}function $a(e){const t=String(e||"/").trim()||"/",n=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;for(const[r,a]of Object.entries(DD))if(n===a)return{view:r};const s=n.split("/").filter(Boolean);if(s.length>=3){const r=String(s[0]||"").trim().toLowerCase(),a=String(s[1]||"").trim().toLowerCase();if(r==="global"&&a==="agent"){const i=decodeURIComponent(s.slice(2).join("/")).trim();if(i)return{view:"globalOverview",agentSegment:i}}}if(s.length>=2){const r=decodeURIComponent(s[0]||"").trim(),a=String(s[1]||"").trim().toLowerCase();if(r){if(a==="overview")return{view:"agentOverview",agentSegment:r};if(a==="authorization")return{view:"agentAuthorization",agentSegment:r};if(a==="plugins")return{view:"agentPlugins",agentSegment:r};if(a==="skills")return{view:"agentSkills",agentSegment:r};if(a==="services")return{view:"agentServices",agentSegment:r};if(a==="command")return{view:"agentCommand",agentSegment:r};if(a==="tasks"){const i=s.length>=3?decodeURIComponent(s.slice(2).join("/")):"";return{view:"agentTasks",agentSegment:r,taskTitle:i}}if(a==="logs")return{view:"agentLogs",agentSegment:r};if(a==="channel"){const i=s.length>=3?decodeURIComponent(String(s[2]||"").trim()):"";if(String(s[3]||"").trim().toLowerCase()==="chat"){const u=s.length>=5?decodeURIComponent(s.slice(4).join("/")):"";if(u)return{view:"contextWorkspace",agentSegment:r,channel:i,sessionId:u}}return{view:"contextOverview",agentSegment:r,channel:i}}if(a==="chat"){const i=s.length>=3?decodeURIComponent(s.slice(2).join("/")):"";return i?{view:"contextWorkspace",agentSegment:r,sessionId:i}:{view:"contextOverview",agentSegment:r}}}}return{view:"globalOverview"}}const U0="city.console-ui.context.debug-panels-collapsed";function _D(){const[e,t]=c.useState(()=>typeof window>"u"?"/global/overview":window.location.pathname),[n,s]=c.useState(()=>typeof window>"u"?"globalOverview":$a(window.location.pathname).view),[r,a]=c.useState(!1),[i,l]=c.useState(()=>typeof window>"u"?"":String($a(window.location.pathname).taskTitle||"").trim()),[u,d]=c.useState(""),[f,g]=c.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(U0)==="1"}catch{return!1}}),{agents:m,authInitializing:h,authBootstrapRequired:x,isAuthenticated:y,authRequired:w,authSubmitting:b,authErrorMessage:p,cityVersion:v,selectedAgentId:S,selectedAgent:j,overview:C,authorization:A,accessUser:M,accessTokens:O,accessLoading:P,latestIssuedAccessToken:$,services:z,skills:N,plugins:H,agentPlugins:R,chatChannels:I,sessions:T,selectedSessionId:E,channelHistory:q,sessionMessages:k,sessionArchives:D,selectedArchiveId:B,sessionArchiveMessages:Q,tasks:Z,logs:te,model:se,configStatus:ie,modelProviders:oe,modelPoolItems:pe,channelAccounts:_,globalEnvItems:Y,agentEnvItems:le,prompt:ne,topbarStatus:ue,topbarError:ae,loading:xe,sending:ee,clearingSessionMessages:W,clearingChatHistory:X,deletingSessionId:G,chatInput:L,toast:J,setChatInput:me,handleAgentChange:ge,handleSessionChange:U,refreshDashboard:ce,refreshSkills:F,refreshSessionArchives:K,controlService:he,runGlobalPluginAction:Te,runPluginAction:Se,runChatChannelAction:Fe,configureChatChannel:Ae,refreshAuthorization:Re,saveAuthorizationConfig:Ye,runAuthorizationAction:yt,clearLatestIssuedAccessToken:De,createAccessToken:ot,deleteAccessToken:_e,runSkillFind:Je,runSkillInstall:jt,runTask:Ct,setTaskStatus:zt,deleteTask:Ce,loadTaskRuns:rt,deleteTaskRun:et,clearTaskRuns:$e,loadTaskRunDetail:Ht,sendConsoleUiMessage:zn,clearSessionMessages:ms,clearChatHistory:Bs,deleteChatSession:In,loadSessionArchiveMessages:Sn,updateAgentExecution:Jn,startAgentFromHistory:vt,loadLocalModels:Ft,pickAgentDirectory:Es,inspectAgentDirectory:Aa,restartAgentFromHistory:Ue,stopAgentFromHistory:Ms,upsertModelProvider:ye,removeModelProvider:Ea,testModelProvider:Nf,discoverModelProvider:Tf,upsertModelPoolItem:Af,removeModelPoolItem:Ef,setModelPoolItemPaused:Mf,testModelPoolItem:Rf,upsertChannelAccount:Of,probeChannelAccount:zf,removeChannelAccount:If,upsertGlobalEnv:Df,removeGlobalEnv:_f,importGlobalEnv:Pr,upsertAgentEnv:Po,removeAgentEnv:Ps,importAgentEnv:Vi,executeAgentCommand:or,constants:ar,uiHelpers:Nn,submitAuthToken:Yi,logout:Ki}=MD(),$r=ID({agents:m,selectedAgentId:S,enabled:y&&!w}),Ur=c.useCallback(V=>{const re=String(V||"").trim();if(re){const Ke=m.find(It=>It.id===re);if(Ke)return Ko(Ke.agentId||Ke.id)}return j?Ko(j.agentId||j.id):S?Ko(S):"agent"},[m,j,S]),Yt=c.useCallback(V=>{const re=String(V||"").trim();if(!re)return"";const Ke=T.find(It=>String(It.sessionId||"").trim()===re);return ma(Ke||re)},[T]),gn=c.useMemo(()=>{const V=new Set;for(const jn of I){const Rs=String(jn.channel||"").trim().toLowerCase();Rs&&V.add(Rs)}for(const jn of T){const Rs=ma(jn);Rs&&V.add(Rs)}const re=["telegram","qq","feishu","consoleui","other"],Ke=re.filter(jn=>V.has(jn)),It=[...V].filter(jn=>!re.includes(jn)).sort((jn,Rs)=>jn.localeCompare(Rs));return[...Ke,...It]},[I,T]),Hr=c.useMemo(()=>{const V=String(u||"").trim().toLowerCase();return V&&gn.includes(V)?V:String(gn[0]||"").trim().toLowerCase()},[gn,u]),ir=c.useCallback(V=>{const re=Ko(String(V||""));if(!re)return"";const Ke=m.find(It=>{const jn=Ko(String(It.agentId||"")),Rs=Ko(String(It.id||""));return re===jn||re===Rs});return String((Ke==null?void 0:Ke.id)||"")},[m]),Kt=c.useCallback((V,re)=>{if(typeof window>"u")return;const Ke=V==="globalOverview"&&!!String((re==null?void 0:re.agentId)||"").trim(),It=$0(V,{sessionId:re==null?void 0:re.sessionId,taskTitle:re==null?void 0:re.taskTitle,channel:re==null?void 0:re.channel,agentSegment:Ke||V!=="globalOverview"?Ur(re==null?void 0:re.agentId):void 0});window.location.pathname!==It&&(re!=null&&re.replace?window.history.replaceState({},"",It):window.history.pushState({},"",It)),t(It),s(V),V==="agentTasks"?l(String((re==null?void 0:re.taskTitle)||"").trim()):V!=="contextWorkspace"&&l("")},[Ur]);c.useEffect(()=>{if(typeof window>"u"||r)return;const V=$a(window.location.pathname);t(window.location.pathname),s(V.view),l(String(V.taskTitle||"").trim()),d(String(V.channel||"").trim().toLowerCase());const re=!!String(V.agentSegment||"").trim();if(re&&m.length===0)return;const Ke=ir(V.agentSegment);if(re&&Ke&&Ke!==S){ge(Ke);return}if(V.view==="contextWorkspace"&&V.sessionId&&(!re||!Ke||Ke===S)){const It=String(V.channel||"").trim().toLowerCase();d(It||Yt(V.sessionId)),U(V.sessionId)}a(!0)},[m.length,U,ge,ir,r,S]),c.useEffect(()=>{if(typeof window>"u")return;const V=()=>{const re=$a(window.location.pathname);t(window.location.pathname),s(re.view),l(String(re.taskTitle||"").trim()),d(String(re.channel||"").trim().toLowerCase());const Ke=ir(re.agentSegment);if(Ke&&Ke!==S&&ge(Ke),re.view==="contextWorkspace"&&re.sessionId&&(!Ke||Ke===S)){const It=String(re.channel||"").trim().toLowerCase();d(It||Yt(re.sessionId)),U(re.sessionId)}};return window.addEventListener("popstate",V),()=>window.removeEventListener("popstate",V)},[U,ge,ir,S]),c.useEffect(()=>{if(typeof window>"u"||!r||!(n!=="globalOverview"&&n!=="globalWorkboard"&&n!=="globalApiKeys"&&n!=="globalEnv"&&n!=="globalModel"&&n!=="globalChannelAccounts"&&n!=="globalCommand"&&n!=="globalAgents"&&n!=="globalPlugins")||!S)return;const re=$0(n,{sessionId:n==="contextWorkspace"?E:void 0,taskTitle:n==="agentTasks"?i:void 0,channel:n==="contextOverview"?Hr:n==="contextWorkspace"?Yt(E):void 0,agentSegment:Ur(S)});window.location.pathname!==re&&window.history.replaceState({},"",re)},[n,Hr,Ur,Yt,r,S,E,i]),c.useEffect(()=>{if(n!=="agentTasks"||!i)return;Z.some(re=>String(re.title||"").trim()===i)||l("")},[n,i,Z]),c.useEffect(()=>{if(r){if(n==="agentServices"){Kt("agentOverview",{replace:!0});return}if(n==="agentCommand"){Kt("globalCommand",{replace:!0});return}if(n==="agentTasks"&&!i){Kt("agentOverview",{replace:!0});return}}},[n,Kt,r,i]),c.useEffect(()=>{d("")},[S]),c.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(U0,f?"1":"0")}catch{}},[f]),c.useEffect(()=>{if(n!=="contextOverview")return;const V=String(u||"").trim().toLowerCase();if(!!V&&gn.includes(V))return;const Ke=String(gn[0]||"").trim().toLowerCase();Ke&&d(Ke)},[n,gn,u]);const Xi=c.useMemo(()=>n!=="globalOverview"?!1:!!String($a(e).agentSegment||"").trim(),[n,e]),Fr=c.useMemo(()=>$a(e),[e]),kc=c.useMemo(()=>ir(Fr.agentSegment),[Fr.agentSegment,ir]);c.useEffect(()=>{String(Fr.agentSegment||"").trim()||S&&ge("")},[ge,Fr.agentSegment,S]);const Ma=()=>j&&j.running===!1?o.jsx("section",{children:o.jsx(Fz,{agent:j,model:se,onStart:V=>vt(V),onLoadLocalModels:V=>Ft(V),onUpdateExecution:V=>{S&&Jn({agentId:S,executionMode:V.executionMode,modelId:V.modelId,localModel:V.localModel,agentType:V.agentType})}})}):o.jsx("section",{className:"space-y-6",children:o.jsx(i7,{selectedAgent:j,overview:C,services:z,skills:N,tasks:Z,sessions:T,channelAccounts:_,consoleUiSessionId:ar.CONSOLEUI_SESSION_ID,configStatus:ie,model:se,onLoadLocalModels:V=>Ft(V),onUpdateExecution:V=>{S&&Jn({agentId:S,executionMode:V.executionMode,modelId:V.modelId,localModel:V.localModel,agentType:V.agentType})},onStartAgent:async()=>{S&&await vt(S)},onRestartAgent:async()=>{S&&await Ue(S)},onStopAgent:async()=>{S&&await Ms(S)},onOpenTask:V=>{const re=String(V||"").trim();re&&(l(re),Kt("agentTasks",{taskTitle:re}))},onOpenSession:V=>{const re=String(V||"").trim();re&&(Kt("contextWorkspace",{sessionId:re,channel:Yt(re)}),U(re))},onControlService:(V,re)=>he(V,re),chatChannels:I,onChatAction:(V,re)=>Fe(V,re)})}),Zi=()=>{switch(n){case"globalOverview":return Xi?Ma():o.jsx("section",{children:o.jsx(O0,{cityVersion:v,agents:m,modelPoolItems:pe,plugins:H,configStatus:ie,onPickAgentDirectory:()=>Es(),onInspectAgentDirectory:V=>Aa(V),onLoadLocalModels:V=>Ft(V),onStartAgent:V=>vt(V),onStartAgentWithInitialization:(V,re)=>vt(V,{initializeIfNeeded:!0,initialization:{projectRoot:V,id:re.id,executionMode:re.executionMode,modelId:re.modelId,localModel:re.localModel,agentType:re.agentType}}),onRestartAgent:V=>Ue(V),onStopAgent:V=>Ms(V)})});case"globalWorkboard":return o.jsx("section",{children:o.jsx(f7,{board:$r.board,loading:$r.loading,errorMessage:$r.errorMessage,onRefresh:()=>{$r.refresh()}})});case"globalApiKeys":return o.jsx("section",{children:o.jsx(Pz,{tokens:O,loading:P,latestIssuedToken:$,formatTime:V=>Nn.formatTime(V??void 0),onCreateToken:V=>ot(V),onDeleteToken:V=>_e(V),onClearLatestIssuedToken:De})});case"globalEnv":{const V=[...Y,...le].sort((re,Ke)=>{const It=String(re.scope||"global").localeCompare(String(Ke.scope||"global"));if(It!==0)return It;const jn=String(re.agentId||"").localeCompare(String(Ke.agentId||""));return jn!==0?jn:String(re.key||"").localeCompare(String(Ke.key||""))});return o.jsx("section",{children:o.jsx(bI,{title:"Env",description:"统一管理全局共享与 agent 私有 env,通过范围标签区分。",emptyText:"暂无 env,点击右上角 + 新建。",items:V,loading:xe,writable:!0,agentOptions:m.map(re=>({id:re.id,name:String(re.agentId||re.id||"").trim()||re.id})),onUpsert:re=>re.scope==="agent"?Po({agentId:String(re.agentId||"").trim(),key:re.key,description:re.description,value:re.value}):Df({key:re.key,description:re.description,value:re.value}),onRemove:re=>re.scope==="agent"?Ps(String(re.agentId||"").trim(),re.key):_f(re.key),onImport:re=>re.scope==="agent"?Vi(String(re.agentId||"").trim(),re.raw):Pr(re.raw)})})}case"agentOverview":return Ma();case"agentAuthorization":return o.jsx("section",{children:o.jsx(sI,{authorization:A,loading:xe,selectedAgent:j,formatTime:Nn.formatTime,onRefresh:()=>Re(S),onSaveConfig:V=>Ye(V),onRunAction:V=>yt(V)})});case"agentCommand":return o.jsx("section",{className:"flex min-h-0 flex-1",children:o.jsx(w0,{selectedAgentId:S,selectedAgentProjectId:String((j==null?void 0:j.agentId)||"").trim()||"agent",agents:m,persistSelectionInUrl:!1,onExecute:V=>or(V)})});case"globalAgents":return o.jsx("section",{children:o.jsx(O0,{cityVersion:v,agents:m,modelPoolItems:pe,plugins:H,configStatus:ie,onPickAgentDirectory:()=>Es(),onInspectAgentDirectory:V=>Aa(V),onLoadLocalModels:V=>Ft(V),onStartAgent:V=>vt(V),onStartAgentWithInitialization:(V,re)=>vt(V,{initializeIfNeeded:!0,initialization:{projectRoot:V,id:re.id,executionMode:re.executionMode,modelId:re.modelId,localModel:re.localModel,agentType:re.agentType}}),onRestartAgent:V=>Ue(V),onStopAgent:V=>Ms(V)})});case"globalModel":return o.jsx("section",{children:o.jsx(SI,{model:se,providers:oe,poolItems:pe,loading:xe,onUpsertProvider:V=>void ye(V),onRemoveProvider:V=>void Ea(V),onTestProvider:V=>void Nf(V),onDiscoverProvider:V=>Tf(V),onUpsertModel:V=>Af(V),onRemoveModel:V=>void Ef(V),onPauseModel:(V,re)=>void Mf(V,re),onTestModel:(V,re)=>void Rf(V,re)})});case"globalChannelAccounts":return o.jsx("section",{children:o.jsx(gI,{items:_,loading:xe,onUpsert:V=>Of(V),onProbe:V=>zf(V),onRemove:V=>If(V)})});case"globalCommand":return o.jsx("section",{className:"flex min-h-0 flex-1",children:o.jsx(w0,{selectedAgentId:S,selectedAgentProjectId:String((j==null?void 0:j.agentId)||"").trim()||"agent",agents:m,persistSelectionInUrl:!0,onExecute:V=>or(V)})});case"globalPlugins":return o.jsx("section",{children:o.jsx(E0,{scope:"global",plugins:H,formatTime:Nn.formatTime,statusBadgeVariant:Nn.statusBadgeVariant,onRunAction:(V,re,Ke)=>Te(V,re,Ke)})});case"agentPlugins":return o.jsx("section",{children:o.jsx(E0,{scope:"agent",plugins:R,hasRunningAgent:(j==null?void 0:j.running)===!0,selectedAgentProjectId:String((j==null?void 0:j.agentId)||"").trim(),formatTime:Nn.formatTime,statusBadgeVariant:Nn.statusBadgeVariant,onRunAction:(V,re,Ke)=>Se(V,re,Ke)})});case"agentSkills":return o.jsx("section",{children:o.jsx(t7,{skills:N,loading:xe,selectedAgentId:S,onRefreshSkills:()=>F(S),onFindSkill:V=>Je(V),onInstallSkill:V=>jt(V)})});case"agentTasks":return o.jsx("section",{children:o.jsx(u7,{tasks:Z,statusBadgeVariant:Nn.statusBadgeVariant,formatTime:Nn.formatTime,onRunTask:V=>void Ct(V),onSetTaskStatus:(V,re)=>zt(V,re),onDeleteTask:V=>Ce(V),onLoadTaskRuns:(V,re)=>rt(V,re),onDeleteTaskRun:(V,re)=>et(V,re),onClearTaskRuns:V=>$e(V),onLoadTaskRunDetail:(V,re)=>Ht(V,re),selectedTaskTitle:i,onSelectTaskTitle:V=>{const re=String(V||"").trim();l(re),Kt("agentTasks",re?{taskTitle:re}:void 0)}})});case"agentLogs":return o.jsx("section",{children:o.jsx(e7,{logs:te,formatTime:Nn.formatTime})});case"contextOverview":return o.jsx("section",{children:o.jsx(RI,{sessions:T,selectedSessionId:E,chatChannels:I,channelAccounts:_,focusedChannel:Hr,formatTime:Nn.formatTime,onOpenSession:V=>{d(Yt(V)),Kt("contextWorkspace",{sessionId:V,channel:Yt(V)}),U(V)},onDeleteSession:V=>{In(V)},deletingSessionId:G,onChatAction:(V,re)=>void Fe(V,re),onChatConfigure:(V,re)=>void Ae(V,re)})});case"contextWorkspace":return o.jsx("section",{className:"h-full min-h-0",children:o.jsx(UI,{selectedSessionId:E,sessions:T,channelHistory:q,chatChannels:I,sessionMessages:k,sessionArchives:D,selectedArchiveId:B,sessionArchiveMessages:Q,prompt:ne,chatInput:L,debugPanelsCollapsed:f,sending:ee,clearingSessionMessages:W,clearingChatHistory:X,deletingSession:!!G,formatTime:Nn.formatTime,onChangeInput:me,onSendConsoleUiMessage:()=>void zn(),onClearSessionMessages:()=>{E&&ms(E)},onClearChatHistory:()=>{E&&Bs(E)},onDeleteSession:()=>{E&&In(E)},onRefreshArchives:()=>{!S||!E||K(S,E)},onSelectArchive:V=>{!S||!E||Sn(S,E,V)},onSelectSession:V=>{Kt("contextWorkspace",{sessionId:V,channel:Yt(V)}),U(V)}})});default:return null}},Nc=o.jsx("div",{className:"flex items-center gap-2",children:n==="contextWorkspace"?o.jsx(be,{type:"button",size:"icon",variant:"ghost",className:"size-8 rounded-[11px] text-muted-foreground hover:bg-secondary hover:text-foreground",onClick:()=>{g(V=>!V)},"aria-label":f?"展开 Debug Panels":"折叠 Debug Panels",title:f?"展开 Debug Panels":"折叠 Debug Panels",children:f?o.jsx(Cw,{className:"size-4"}):o.jsx(Fm,{className:"size-4"})}):null});return h||!y?o.jsx(aI,{checking:h,bootstrapRequired:x,submitting:b,errorMessage:p,onSubmit:Yi}):o.jsxs(Sz,{style:{"--sidebar-width":"18.5rem","--header-height":"3.5rem"},children:[o.jsx(Bz,{activeView:n,agents:m,selectedAgentId:S,routePathname:e,routeAgentId:kc,sessions:T,chatChannels:I,selectedSessionId:E,tasks:Z,selectedTaskTitle:i,selectedChatChannel:Hr,onViewChange:V=>{if(V==="contextWorkspace"){const re=E||ar.CONSOLEUI_SESSION_ID;d(Yt(re)),Kt("contextWorkspace",{sessionId:re,channel:Yt(re)}),U(re);return}V!=="contextOverview"&&d(""),Kt(V)},onAgentChange:V=>{ge(V),d(""),Kt("globalOverview",{agentId:V})},onAgentEnter:V=>{ge(V),d(""),Kt("agentOverview",{agentId:V})},onTaskOpen:V=>{d(""),l(V),Kt("agentTasks",{taskTitle:V})},onChannelOpen:V=>{const re=String(V||"").trim().toLowerCase();d(re),Kt("contextOverview",{channel:re})},onSessionOpen:V=>{d(Yt(V)),Kt("contextWorkspace",{sessionId:V,channel:Yt(V)}),U(V)},topbarStatus:ue,topbarError:ae,loading:xe,onRefresh:()=>void ce(),user:M,tokens:O,onLogout:Ki,variant:"sidebar"}),o.jsxs(kz,{children:[o.jsx(g7,{viewLabel:Iz(n),rightActions:Nc}),o.jsx("main",{className:Me("mainview-shell flex flex-1 min-h-0 flex-col bg-transparent",n==="contextWorkspace"?"gap-0 overflow-hidden px-3 pb-3 pt-1 md:px-4 md:pb-4 md:pt-1":"gap-4 overflow-y-auto overflow-x-hidden px-3 pb-3 pt-1 md:px-4 md:pb-4 md:pt-1"),children:Zi()})]}),J?o.jsx(d7,{message:J.message,type:J.type}):null]})}const Yj=document.getElementById("root");if(!Yj)throw new Error("Missing #root element");PT.createRoot(Yj).render(o.jsx(c.StrictMode,{children:o.jsx(Jr,{children:o.jsx(qz,{children:o.jsx(_D,{})})})}));
|