@crewspaceai/server 2026.412.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/adapters/codex-models.d.ts +4 -0
- package/dist/adapters/codex-models.d.ts.map +1 -0
- package/dist/adapters/codex-models.js +98 -0
- package/dist/adapters/codex-models.js.map +1 -0
- package/dist/adapters/cursor-models.d.ts +13 -0
- package/dist/adapters/cursor-models.d.ts.map +1 -0
- package/dist/adapters/cursor-models.js +148 -0
- package/dist/adapters/cursor-models.js.map +1 -0
- package/dist/adapters/http/execute.d.ts +3 -0
- package/dist/adapters/http/execute.d.ts.map +1 -0
- package/dist/adapters/http/execute.js +39 -0
- package/dist/adapters/http/execute.js.map +1 -0
- package/dist/adapters/http/index.d.ts +3 -0
- package/dist/adapters/http/index.d.ts.map +1 -0
- package/dist/adapters/http/index.js +20 -0
- package/dist/adapters/http/index.js.map +1 -0
- package/dist/adapters/http/test.d.ts +3 -0
- package/dist/adapters/http/test.d.ts.map +1 -0
- package/dist/adapters/http/test.js +106 -0
- package/dist/adapters/http/test.js.map +1 -0
- package/dist/adapters/index.d.ts +4 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +3 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/process/execute.d.ts +3 -0
- package/dist/adapters/process/execute.d.ts.map +1 -0
- package/dist/adapters/process/execute.js +70 -0
- package/dist/adapters/process/execute.js.map +1 -0
- package/dist/adapters/process/index.d.ts +3 -0
- package/dist/adapters/process/index.d.ts.map +1 -0
- package/dist/adapters/process/index.js +23 -0
- package/dist/adapters/process/index.js.map +1 -0
- package/dist/adapters/process/test.d.ts +3 -0
- package/dist/adapters/process/test.d.ts.map +1 -0
- package/dist/adapters/process/test.js +77 -0
- package/dist/adapters/process/test.js.map +1 -0
- package/dist/adapters/registry.d.ts +14 -0
- package/dist/adapters/registry.d.ts.map +1 -0
- package/dist/adapters/registry.js +164 -0
- package/dist/adapters/registry.js.map +1 -0
- package/dist/adapters/types.d.ts +2 -0
- package/dist/adapters/types.d.ts.map +1 -0
- package/dist/adapters/types.js +2 -0
- package/dist/adapters/types.js.map +1 -0
- package/dist/adapters/utils.d.ts +41 -0
- package/dist/adapters/utils.d.ts.map +1 -0
- package/dist/adapters/utils.js +51 -0
- package/dist/adapters/utils.js.map +1 -0
- package/dist/agent-auth-jwt.d.ts +14 -0
- package/dist/agent-auth-jwt.d.ts.map +1 -0
- package/dist/agent-auth-jwt.js +117 -0
- package/dist/agent-auth-jwt.js.map +1 -0
- package/dist/app.d.ts +25 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/app.js +267 -0
- package/dist/app.js.map +1 -0
- package/dist/attachment-types.d.ts +33 -0
- package/dist/attachment-types.d.ts.map +1 -0
- package/dist/attachment-types.js +67 -0
- package/dist/attachment-types.js.map +1 -0
- package/dist/auth/better-auth.d.ts +24 -0
- package/dist/auth/better-auth.d.ts.map +1 -0
- package/dist/auth/better-auth.js +108 -0
- package/dist/auth/better-auth.js.map +1 -0
- package/dist/board-claim.d.ts +23 -0
- package/dist/board-claim.d.ts.map +1 -0
- package/dist/board-claim.js +115 -0
- package/dist/board-claim.js.map +1 -0
- package/dist/config-file.d.ts +3 -0
- package/dist/config-file.d.ts.map +1 -0
- package/dist/config-file.js +16 -0
- package/dist/config-file.js.map +1 -0
- package/dist/config.d.ts +38 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +164 -0
- package/dist/config.js.map +1 -0
- package/dist/dev-server-status.d.ts +27 -0
- package/dist/dev-server-status.d.ts.map +1 -0
- package/dist/dev-server-status.js +70 -0
- package/dist/dev-server-status.js.map +1 -0
- package/dist/dev-watch-ignore.d.ts +2 -0
- package/dist/dev-watch-ignore.d.ts.map +1 -0
- package/dist/dev-watch-ignore.js +33 -0
- package/dist/dev-watch-ignore.js.map +1 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +28 -0
- package/dist/errors.js.map +1 -0
- package/dist/home-paths.d.ts +17 -0
- package/dist/home-paths.d.ts.map +1 -0
- package/dist/home-paths.js +75 -0
- package/dist/home-paths.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +615 -0
- package/dist/index.js.map +1 -0
- package/dist/log-redaction.d.ts +11 -0
- package/dist/log-redaction.d.ts.map +1 -0
- package/dist/log-redaction.js +118 -0
- package/dist/log-redaction.js.map +1 -0
- package/dist/middleware/auth.d.ts +12 -0
- package/dist/middleware/auth.d.ts.map +1 -0
- package/dist/middleware/auth.js +144 -0
- package/dist/middleware/auth.js.map +1 -0
- package/dist/middleware/board-mutation-guard.d.ts +3 -0
- package/dist/middleware/board-mutation-guard.d.ts.map +1 -0
- package/dist/middleware/board-mutation-guard.js +60 -0
- package/dist/middleware/board-mutation-guard.js.map +1 -0
- package/dist/middleware/error-handler.d.ts +17 -0
- package/dist/middleware/error-handler.d.ts.map +1 -0
- package/dist/middleware/error-handler.js +37 -0
- package/dist/middleware/error-handler.js.map +1 -0
- package/dist/middleware/index.d.ts +4 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +4 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/logger.d.ts +4 -0
- package/dist/middleware/logger.d.ts.map +1 -0
- package/dist/middleware/logger.js +87 -0
- package/dist/middleware/logger.js.map +1 -0
- package/dist/middleware/private-hostname-guard.d.ts +11 -0
- package/dist/middleware/private-hostname-guard.d.ts.map +1 -0
- package/dist/middleware/private-hostname-guard.js +78 -0
- package/dist/middleware/private-hostname-guard.js.map +1 -0
- package/dist/middleware/validate.d.ts +4 -0
- package/dist/middleware/validate.d.ts.map +1 -0
- package/dist/middleware/validate.js +7 -0
- package/dist/middleware/validate.js.map +1 -0
- package/dist/onboarding-assets/ceo/AGENTS.md +54 -0
- package/dist/onboarding-assets/ceo/HEARTBEAT.md +72 -0
- package/dist/onboarding-assets/ceo/SOUL.md +33 -0
- package/dist/onboarding-assets/ceo/TOOLS.md +3 -0
- package/dist/onboarding-assets/default/AGENTS.md +3 -0
- package/dist/paths.d.ts +3 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +31 -0
- package/dist/paths.js.map +1 -0
- package/dist/realtime/live-events-ws.d.ts +28 -0
- package/dist/realtime/live-events-ws.d.ts.map +1 -0
- package/dist/realtime/live-events-ws.js +187 -0
- package/dist/realtime/live-events-ws.js.map +1 -0
- package/dist/redaction.d.ts +4 -0
- package/dist/redaction.d.ts.map +1 -0
- package/dist/redaction.js +63 -0
- package/dist/redaction.js.map +1 -0
- package/dist/routes/access.d.ts +62 -0
- package/dist/routes/access.d.ts.map +1 -0
- package/dist/routes/access.js +2296 -0
- package/dist/routes/access.js.map +1 -0
- package/dist/routes/activity.d.ts +3 -0
- package/dist/routes/activity.d.ts.map +1 -0
- package/dist/routes/activity.js +78 -0
- package/dist/routes/activity.js.map +1 -0
- package/dist/routes/agent-memories.d.ts +3 -0
- package/dist/routes/agent-memories.d.ts.map +1 -0
- package/dist/routes/agent-memories.js +148 -0
- package/dist/routes/agent-memories.js.map +1 -0
- package/dist/routes/agents.d.ts +3 -0
- package/dist/routes/agents.d.ts.map +1 -0
- package/dist/routes/agents.js +1999 -0
- package/dist/routes/agents.js.map +1 -0
- package/dist/routes/approvals.d.ts +3 -0
- package/dist/routes/approvals.d.ts.map +1 -0
- package/dist/routes/approvals.js +275 -0
- package/dist/routes/approvals.js.map +1 -0
- package/dist/routes/assets.d.ts +4 -0
- package/dist/routes/assets.d.ts.map +1 -0
- package/dist/routes/assets.js +309 -0
- package/dist/routes/assets.js.map +1 -0
- package/dist/routes/authz.d.ts +16 -0
- package/dist/routes/authz.d.ts.map +1 -0
- package/dist/routes/authz.js +47 -0
- package/dist/routes/authz.js.map +1 -0
- package/dist/routes/companies.d.ts +4 -0
- package/dist/routes/companies.d.ts.map +1 -0
- package/dist/routes/companies.js +303 -0
- package/dist/routes/companies.js.map +1 -0
- package/dist/routes/company-skills.d.ts +3 -0
- package/dist/routes/company-skills.d.ts.map +1 -0
- package/dist/routes/company-skills.js +228 -0
- package/dist/routes/company-skills.js.map +1 -0
- package/dist/routes/costs.d.ts +3 -0
- package/dist/routes/costs.d.ts.map +1 -0
- package/dist/routes/costs.js +268 -0
- package/dist/routes/costs.js.map +1 -0
- package/dist/routes/dashboard.d.ts +3 -0
- package/dist/routes/dashboard.d.ts.map +1 -0
- package/dist/routes/dashboard.js +15 -0
- package/dist/routes/dashboard.js.map +1 -0
- package/dist/routes/execution-workspaces.d.ts +3 -0
- package/dist/routes/execution-workspaces.d.ts.map +1 -0
- package/dist/routes/execution-workspaces.js +367 -0
- package/dist/routes/execution-workspaces.js.map +1 -0
- package/dist/routes/goals.d.ts +3 -0
- package/dist/routes/goals.d.ts.map +1 -0
- package/dist/routes/goals.js +95 -0
- package/dist/routes/goals.js.map +1 -0
- package/dist/routes/health.d.ts +9 -0
- package/dist/routes/health.d.ts.map +1 -0
- package/dist/routes/health.js +80 -0
- package/dist/routes/health.js.map +1 -0
- package/dist/routes/index.d.ts +18 -0
- package/dist/routes/index.d.ts.map +1 -0
- package/dist/routes/index.js +18 -0
- package/dist/routes/index.js.map +1 -0
- package/dist/routes/instance-settings.d.ts +3 -0
- package/dist/routes/instance-settings.d.ts.map +1 -0
- package/dist/routes/instance-settings.js +71 -0
- package/dist/routes/instance-settings.js.map +1 -0
- package/dist/routes/issues-checkout-wakeup.d.ts +9 -0
- package/dist/routes/issues-checkout-wakeup.d.ts.map +1 -0
- package/dist/routes/issues-checkout-wakeup.js +12 -0
- package/dist/routes/issues-checkout-wakeup.js.map +1 -0
- package/dist/routes/issues.d.ts +4 -0
- package/dist/routes/issues.d.ts.map +1 -0
- package/dist/routes/issues.js +1670 -0
- package/dist/routes/issues.js.map +1 -0
- package/dist/routes/llms.d.ts +3 -0
- package/dist/routes/llms.d.ts.map +1 -0
- package/dist/routes/llms.js +78 -0
- package/dist/routes/llms.js.map +1 -0
- package/dist/routes/org-chart-svg.d.ts +25 -0
- package/dist/routes/org-chart-svg.d.ts.map +1 -0
- package/dist/routes/org-chart-svg.js +656 -0
- package/dist/routes/org-chart-svg.js.map +1 -0
- package/dist/routes/plugin-ui-static.d.ts +69 -0
- package/dist/routes/plugin-ui-static.d.ts.map +1 -0
- package/dist/routes/plugin-ui-static.js +411 -0
- package/dist/routes/plugin-ui-static.js.map +1 -0
- package/dist/routes/plugins.d.ts +120 -0
- package/dist/routes/plugins.d.ts.map +1 -0
- package/dist/routes/plugins.js +1784 -0
- package/dist/routes/plugins.js.map +1 -0
- package/dist/routes/projects.d.ts +3 -0
- package/dist/routes/projects.d.ts.map +1 -0
- package/dist/routes/projects.js +386 -0
- package/dist/routes/projects.js.map +1 -0
- package/dist/routes/routines.d.ts +3 -0
- package/dist/routes/routines.d.ts.map +1 -0
- package/dist/routes/routines.js +277 -0
- package/dist/routes/routines.js.map +1 -0
- package/dist/routes/secrets.d.ts +3 -0
- package/dist/routes/secrets.d.ts.map +1 -0
- package/dist/routes/secrets.js +128 -0
- package/dist/routes/secrets.js.map +1 -0
- package/dist/routes/sidebar-badges.d.ts +3 -0
- package/dist/routes/sidebar-badges.d.ts.map +1 -0
- package/dist/routes/sidebar-badges.js +45 -0
- package/dist/routes/sidebar-badges.js.map +1 -0
- package/dist/secrets/external-stub-providers.d.ts +5 -0
- package/dist/secrets/external-stub-providers.d.ts.map +1 -0
- package/dist/secrets/external-stub-providers.js +21 -0
- package/dist/secrets/external-stub-providers.js.map +1 -0
- package/dist/secrets/local-encrypted-provider.d.ts +3 -0
- package/dist/secrets/local-encrypted-provider.d.ts.map +1 -0
- package/dist/secrets/local-encrypted-provider.js +116 -0
- package/dist/secrets/local-encrypted-provider.js.map +1 -0
- package/dist/secrets/provider-registry.d.ts +5 -0
- package/dist/secrets/provider-registry.d.ts.map +1 -0
- package/dist/secrets/provider-registry.js +20 -0
- package/dist/secrets/provider-registry.js.map +1 -0
- package/dist/secrets/types.d.ts +21 -0
- package/dist/secrets/types.d.ts.map +1 -0
- package/dist/secrets/types.js +2 -0
- package/dist/secrets/types.js.map +1 -0
- package/dist/services/access.d.ts +113 -0
- package/dist/services/access.d.ts.map +1 -0
- package/dist/services/access.js +247 -0
- package/dist/services/access.js.map +1 -0
- package/dist/services/activity-log.d.ts +17 -0
- package/dist/services/activity-log.d.ts.map +1 -0
- package/dist/services/activity-log.js +74 -0
- package/dist/services/activity-log.js.map +1 -0
- package/dist/services/activity.d.ts +764 -0
- package/dist/services/activity.d.ts.map +1 -0
- package/dist/services/activity.js +105 -0
- package/dist/services/activity.js.map +1 -0
- package/dist/services/agent-instructions.d.ts +91 -0
- package/dist/services/agent-instructions.d.ts.map +1 -0
- package/dist/services/agent-instructions.js +580 -0
- package/dist/services/agent-instructions.js.map +1 -0
- package/dist/services/agent-permissions.d.ts +6 -0
- package/dist/services/agent-permissions.d.ts.map +1 -0
- package/dist/services/agent-permissions.js +18 -0
- package/dist/services/agent-permissions.js.map +1 -0
- package/dist/services/agentMemories.d.ts +149 -0
- package/dist/services/agentMemories.d.ts.map +1 -0
- package/dist/services/agentMemories.js +109 -0
- package/dist/services/agentMemories.js.map +1 -0
- package/dist/services/agentMemoryExtraction.d.ts +32 -0
- package/dist/services/agentMemoryExtraction.d.ts.map +1 -0
- package/dist/services/agentMemoryExtraction.js +95 -0
- package/dist/services/agentMemoryExtraction.js.map +1 -0
- package/dist/services/agentTaskMemory.d.ts +28 -0
- package/dist/services/agentTaskMemory.d.ts.map +1 -0
- package/dist/services/agentTaskMemory.js +159 -0
- package/dist/services/agentTaskMemory.js.map +1 -0
- package/dist/services/agents.d.ts +1670 -0
- package/dist/services/agents.d.ts.map +1 -0
- package/dist/services/agents.js +566 -0
- package/dist/services/agents.js.map +1 -0
- package/dist/services/approvals.d.ts +546 -0
- package/dist/services/approvals.d.ts.map +1 -0
- package/dist/services/approvals.js +212 -0
- package/dist/services/approvals.js.map +1 -0
- package/dist/services/assets.d.ts +33 -0
- package/dist/services/assets.d.ts.map +1 -0
- package/dist/services/assets.js +17 -0
- package/dist/services/assets.js.map +1 -0
- package/dist/services/board-auth.d.ts +234 -0
- package/dist/services/board-auth.d.ts.map +1 -0
- package/dist/services/board-auth.js +295 -0
- package/dist/services/board-auth.js.map +1 -0
- package/dist/services/budgets.d.ts +38 -0
- package/dist/services/budgets.d.ts.map +1 -0
- package/dist/services/budgets.js +784 -0
- package/dist/services/budgets.js.map +1 -0
- package/dist/services/companies.d.ts +124 -0
- package/dist/services/companies.d.ts.map +1 -0
- package/dist/services/companies.js +256 -0
- package/dist/services/companies.js.map +1 -0
- package/dist/services/company-export-readme.d.ts +17 -0
- package/dist/services/company-export-readme.d.ts.map +1 -0
- package/dist/services/company-export-readme.js +148 -0
- package/dist/services/company-export-readme.js.map +1 -0
- package/dist/services/company-portability.d.ts +23 -0
- package/dist/services/company-portability.d.ts.map +1 -0
- package/dist/services/company-portability.js +3739 -0
- package/dist/services/company-portability.js.map +1 -0
- package/dist/services/company-skills.d.ts +77 -0
- package/dist/services/company-skills.d.ts.map +1 -0
- package/dist/services/company-skills.js +2042 -0
- package/dist/services/company-skills.js.map +1 -0
- package/dist/services/costs.d.ts +114 -0
- package/dist/services/costs.d.ts.map +1 -0
- package/dist/services/costs.js +294 -0
- package/dist/services/costs.js.map +1 -0
- package/dist/services/cron.d.ts +80 -0
- package/dist/services/cron.d.ts.map +1 -0
- package/dist/services/cron.js +300 -0
- package/dist/services/cron.js.map +1 -0
- package/dist/services/dashboard.d.ts +26 -0
- package/dist/services/dashboard.d.ts.map +1 -0
- package/dist/services/dashboard.js +98 -0
- package/dist/services/dashboard.js.map +1 -0
- package/dist/services/default-agent-instructions.d.ts +9 -0
- package/dist/services/default-agent-instructions.d.ts.map +1 -0
- package/dist/services/default-agent-instructions.js +20 -0
- package/dist/services/default-agent-instructions.js.map +1 -0
- package/dist/services/documents.d.ts +194 -0
- package/dist/services/documents.d.ts.map +1 -0
- package/dist/services/documents.js +407 -0
- package/dist/services/documents.js.map +1 -0
- package/dist/services/execution-workspace-policy.d.ts +21 -0
- package/dist/services/execution-workspace-policy.d.ts.map +1 -0
- package/dist/services/execution-workspace-policy.js +177 -0
- package/dist/services/execution-workspace-policy.js.map +1 -0
- package/dist/services/execution-workspaces.d.ts +22 -0
- package/dist/services/execution-workspaces.d.ts.map +1 -0
- package/dist/services/execution-workspaces.js +551 -0
- package/dist/services/execution-workspaces.js.map +1 -0
- package/dist/services/finance.d.ts +93 -0
- package/dist/services/finance.d.ts.map +1 -0
- package/dist/services/finance.js +120 -0
- package/dist/services/finance.js.map +1 -0
- package/dist/services/goals.d.ts +433 -0
- package/dist/services/goals.d.ts.map +1 -0
- package/dist/services/goals.js +54 -0
- package/dist/services/goals.js.map +1 -0
- package/dist/services/heartbeat-run-summary.d.ts +2 -0
- package/dist/services/heartbeat-run-summary.d.ts.map +1 -0
- package/dist/services/heartbeat-run-summary.js +30 -0
- package/dist/services/heartbeat-run-summary.js.map +1 -0
- package/dist/services/heartbeat.d.ts +839 -0
- package/dist/services/heartbeat.d.ts.map +1 -0
- package/dist/services/heartbeat.js +3303 -0
- package/dist/services/heartbeat.js.map +1 -0
- package/dist/services/hire-hook.d.ts +14 -0
- package/dist/services/hire-hook.d.ts.map +1 -0
- package/dist/services/hire-hook.js +85 -0
- package/dist/services/hire-hook.js.map +1 -0
- package/dist/services/index.d.ts +33 -0
- package/dist/services/index.d.ts.map +1 -0
- package/dist/services/index.js +33 -0
- package/dist/services/index.js.map +1 -0
- package/dist/services/instance-settings.d.ts +11 -0
- package/dist/services/instance-settings.d.ts.map +1 -0
- package/dist/services/instance-settings.js +116 -0
- package/dist/services/instance-settings.js.map +1 -0
- package/dist/services/issue-approvals.d.ts +56 -0
- package/dist/services/issue-approvals.d.ts.map +1 -0
- package/dist/services/issue-approvals.js +153 -0
- package/dist/services/issue-approvals.js.map +1 -0
- package/dist/services/issue-assignment-wakeup.d.ts +29 -0
- package/dist/services/issue-assignment-wakeup.d.ts.map +1 -0
- package/dist/services/issue-assignment-wakeup.js +22 -0
- package/dist/services/issue-assignment-wakeup.js.map +1 -0
- package/dist/services/issue-goal-fallback.d.ts +18 -0
- package/dist/services/issue-goal-fallback.d.ts.map +1 -0
- package/dist/services/issue-goal-fallback.js +33 -0
- package/dist/services/issue-goal-fallback.js.map +1 -0
- package/dist/services/issues.d.ts +564 -0
- package/dist/services/issues.d.ts.map +1 -0
- package/dist/services/issues.js +1541 -0
- package/dist/services/issues.js.map +1 -0
- package/dist/services/live-events.d.ts +17 -0
- package/dist/services/live-events.d.ts.map +1 -0
- package/dist/services/live-events.js +33 -0
- package/dist/services/live-events.js.map +1 -0
- package/dist/services/local-service-supervisor.d.ts +55 -0
- package/dist/services/local-service-supervisor.d.ts.map +1 -0
- package/dist/services/local-service-supervisor.js +240 -0
- package/dist/services/local-service-supervisor.js.map +1 -0
- package/dist/services/memoryExtractor.d.ts +34 -0
- package/dist/services/memoryExtractor.d.ts.map +1 -0
- package/dist/services/memoryExtractor.js +121 -0
- package/dist/services/memoryExtractor.js.map +1 -0
- package/dist/services/plugin-capability-validator.d.ts +108 -0
- package/dist/services/plugin-capability-validator.d.ts.map +1 -0
- package/dist/services/plugin-capability-validator.js +268 -0
- package/dist/services/plugin-capability-validator.js.map +1 -0
- package/dist/services/plugin-config-validator.d.ts +26 -0
- package/dist/services/plugin-config-validator.d.ts.map +1 -0
- package/dist/services/plugin-config-validator.js +41 -0
- package/dist/services/plugin-config-validator.js.map +1 -0
- package/dist/services/plugin-dev-watcher.d.ts +30 -0
- package/dist/services/plugin-dev-watcher.d.ts.map +1 -0
- package/dist/services/plugin-dev-watcher.js +241 -0
- package/dist/services/plugin-dev-watcher.js.map +1 -0
- package/dist/services/plugin-event-bus.d.ts +149 -0
- package/dist/services/plugin-event-bus.d.ts.map +1 -0
- package/dist/services/plugin-event-bus.js +258 -0
- package/dist/services/plugin-event-bus.js.map +1 -0
- package/dist/services/plugin-host-service-cleanup.d.ts +14 -0
- package/dist/services/plugin-host-service-cleanup.d.ts.map +1 -0
- package/dist/services/plugin-host-service-cleanup.js +37 -0
- package/dist/services/plugin-host-service-cleanup.js.map +1 -0
- package/dist/services/plugin-host-services.d.ts +13 -0
- package/dist/services/plugin-host-services.d.ts.map +1 -0
- package/dist/services/plugin-host-services.js +969 -0
- package/dist/services/plugin-host-services.js.map +1 -0
- package/dist/services/plugin-job-coordinator.d.ts +81 -0
- package/dist/services/plugin-job-coordinator.d.ts.map +1 -0
- package/dist/services/plugin-job-coordinator.js +172 -0
- package/dist/services/plugin-job-coordinator.js.map +1 -0
- package/dist/services/plugin-job-scheduler.d.ts +163 -0
- package/dist/services/plugin-job-scheduler.d.ts.map +1 -0
- package/dist/services/plugin-job-scheduler.js +454 -0
- package/dist/services/plugin-job-scheduler.js.map +1 -0
- package/dist/services/plugin-job-store.d.ts +208 -0
- package/dist/services/plugin-job-store.d.ts.map +1 -0
- package/dist/services/plugin-job-store.js +350 -0
- package/dist/services/plugin-job-store.js.map +1 -0
- package/dist/services/plugin-lifecycle.d.ts +203 -0
- package/dist/services/plugin-lifecycle.d.ts.map +1 -0
- package/dist/services/plugin-lifecycle.js +476 -0
- package/dist/services/plugin-lifecycle.js.map +1 -0
- package/dist/services/plugin-loader.d.ts +441 -0
- package/dist/services/plugin-loader.d.ts.map +1 -0
- package/dist/services/plugin-loader.js +1192 -0
- package/dist/services/plugin-loader.js.map +1 -0
- package/dist/services/plugin-log-retention.d.ts +20 -0
- package/dist/services/plugin-log-retention.d.ts.map +1 -0
- package/dist/services/plugin-log-retention.js +63 -0
- package/dist/services/plugin-log-retention.js.map +1 -0
- package/dist/services/plugin-manifest-validator.d.ts +79 -0
- package/dist/services/plugin-manifest-validator.d.ts.map +1 -0
- package/dist/services/plugin-manifest-validator.js +84 -0
- package/dist/services/plugin-manifest-validator.js.map +1 -0
- package/dist/services/plugin-registry.d.ts +2542 -0
- package/dist/services/plugin-registry.d.ts.map +1 -0
- package/dist/services/plugin-registry.js +539 -0
- package/dist/services/plugin-registry.js.map +1 -0
- package/dist/services/plugin-runtime-sandbox.d.ts +40 -0
- package/dist/services/plugin-runtime-sandbox.d.ts.map +1 -0
- package/dist/services/plugin-runtime-sandbox.js +154 -0
- package/dist/services/plugin-runtime-sandbox.js.map +1 -0
- package/dist/services/plugin-secrets-handler.d.ts +81 -0
- package/dist/services/plugin-secrets-handler.d.ts.map +1 -0
- package/dist/services/plugin-secrets-handler.js +275 -0
- package/dist/services/plugin-secrets-handler.js.map +1 -0
- package/dist/services/plugin-state-store.d.ts +92 -0
- package/dist/services/plugin-state-store.d.ts.map +1 -0
- package/dist/services/plugin-state-store.js +190 -0
- package/dist/services/plugin-state-store.js.map +1 -0
- package/dist/services/plugin-stream-bus.d.ts +29 -0
- package/dist/services/plugin-stream-bus.d.ts.map +1 -0
- package/dist/services/plugin-stream-bus.js +48 -0
- package/dist/services/plugin-stream-bus.js.map +1 -0
- package/dist/services/plugin-tool-dispatcher.d.ts +180 -0
- package/dist/services/plugin-tool-dispatcher.d.ts.map +1 -0
- package/dist/services/plugin-tool-dispatcher.js +224 -0
- package/dist/services/plugin-tool-dispatcher.js.map +1 -0
- package/dist/services/plugin-tool-registry.d.ts +192 -0
- package/dist/services/plugin-tool-registry.d.ts.map +1 -0
- package/dist/services/plugin-tool-registry.js +224 -0
- package/dist/services/plugin-tool-registry.js.map +1 -0
- package/dist/services/plugin-worker-manager.d.ts +260 -0
- package/dist/services/plugin-worker-manager.d.ts.map +1 -0
- package/dist/services/plugin-worker-manager.js +835 -0
- package/dist/services/plugin-worker-manager.js.map +1 -0
- package/dist/services/project-workspace-runtime-config.d.ts +4 -0
- package/dist/services/project-workspace-runtime-config.d.ts.map +1 -0
- package/dist/services/project-workspace-runtime-config.js +43 -0
- package/dist/services/project-workspace-runtime-config.js.map +1 -0
- package/dist/services/projects.d.ts +88 -0
- package/dist/services/projects.d.ts.map +1 -0
- package/dist/services/projects.js +669 -0
- package/dist/services/projects.js.map +1 -0
- package/dist/services/quota-windows.d.ts +9 -0
- package/dist/services/quota-windows.d.ts.map +1 -0
- package/dist/services/quota-windows.js +56 -0
- package/dist/services/quota-windows.js.map +1 -0
- package/dist/services/routines.d.ts +135 -0
- package/dist/services/routines.d.ts.map +1 -0
- package/dist/services/routines.js +1105 -0
- package/dist/services/routines.js.map +1 -0
- package/dist/services/run-log-store.d.ts +34 -0
- package/dist/services/run-log-store.d.ts.map +1 -0
- package/dist/services/run-log-store.js +109 -0
- package/dist/services/run-log-store.js.map +1 -0
- package/dist/services/secrets.d.ts +511 -0
- package/dist/services/secrets.d.ts.map +1 -0
- package/dist/services/secrets.js +289 -0
- package/dist/services/secrets.js.map +1 -0
- package/dist/services/sidebar-badges.d.ts +9 -0
- package/dist/services/sidebar-badges.d.ts.map +1 -0
- package/dist/services/sidebar-badges.js +33 -0
- package/dist/services/sidebar-badges.js.map +1 -0
- package/dist/services/work-products.d.ts +14 -0
- package/dist/services/work-products.d.ts.map +1 -0
- package/dist/services/work-products.js +100 -0
- package/dist/services/work-products.js.map +1 -0
- package/dist/services/workspace-operation-log-store.d.ts +33 -0
- package/dist/services/workspace-operation-log-store.d.ts.map +1 -0
- package/dist/services/workspace-operation-log-store.js +110 -0
- package/dist/services/workspace-operation-log-store.js.map +1 -0
- package/dist/services/workspace-operations.d.ts +44 -0
- package/dist/services/workspace-operations.d.ts.map +1 -0
- package/dist/services/workspace-operations.js +211 -0
- package/dist/services/workspace-operations.js.map +1 -0
- package/dist/services/workspace-runtime.d.ts +187 -0
- package/dist/services/workspace-runtime.d.ts.map +1 -0
- package/dist/services/workspace-runtime.js +1702 -0
- package/dist/services/workspace-runtime.js.map +1 -0
- package/dist/startup-banner.d.ts +31 -0
- package/dist/startup-banner.d.ts.map +1 -0
- package/dist/startup-banner.js +117 -0
- package/dist/startup-banner.js.map +1 -0
- package/dist/storage/index.d.ts +6 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +29 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/local-disk-provider.d.ts +3 -0
- package/dist/storage/local-disk-provider.d.ts.map +1 -0
- package/dist/storage/local-disk-provider.js +79 -0
- package/dist/storage/local-disk-provider.js.map +1 -0
- package/dist/storage/provider-registry.d.ts +4 -0
- package/dist/storage/provider-registry.d.ts.map +1 -0
- package/dist/storage/provider-registry.js +15 -0
- package/dist/storage/provider-registry.js.map +1 -0
- package/dist/storage/s3-provider.d.ts +11 -0
- package/dist/storage/s3-provider.d.ts.map +1 -0
- package/dist/storage/s3-provider.js +123 -0
- package/dist/storage/s3-provider.js.map +1 -0
- package/dist/storage/service.d.ts +3 -0
- package/dist/storage/service.d.ts.map +1 -0
- package/dist/storage/service.js +120 -0
- package/dist/storage/service.js.map +1 -0
- package/dist/storage/types.d.ts +55 -0
- package/dist/storage/types.d.ts.map +1 -0
- package/dist/storage/types.js +2 -0
- package/dist/storage/types.js.map +1 -0
- package/dist/ui-branding.d.ts +13 -0
- package/dist/ui-branding.d.ts.map +1 -0
- package/dist/ui-branding.js +187 -0
- package/dist/ui-branding.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/dist/worktree-config.d.ts +19 -0
- package/dist/worktree-config.d.ts.map +1 -0
- package/dist/worktree-config.js +365 -0
- package/dist/worktree-config.js.map +1 -0
- package/package.json +91 -0
- package/skills/crewspace/SKILL.md +367 -0
- package/skills/crewspace/references/api-reference.md +676 -0
- package/skills/crewspace/references/company-skills.md +193 -0
- package/skills/crewspace-create-agent/SKILL.md +142 -0
- package/skills/crewspace-create-agent/references/api-reference.md +105 -0
- package/skills/crewspace-create-plugin/SKILL.md +101 -0
- package/skills/para-memory-files/SKILL.md +104 -0
- package/skills/para-memory-files/references/schemas.md +35 -0
- package/ui-dist/android-chrome-192x192.png +0 -0
- package/ui-dist/android-chrome-512x512.png +0 -0
- package/ui-dist/apple-touch-icon.png +0 -0
- package/ui-dist/assets/Office-JSp1M1WZ.js +1 -0
- package/ui-dist/assets/_basePickBy-s4e5ujOx.js +1 -0
- package/ui-dist/assets/_baseUniq-CZlZWBgA.js +1 -0
- package/ui-dist/assets/apl-B4CMkyY2.js +1 -0
- package/ui-dist/assets/arc-CKpxyOmJ.js +1 -0
- package/ui-dist/assets/architectureDiagram-VXUJARFQ-DGSV8xDY.js +36 -0
- package/ui-dist/assets/asciiarmor-Df11BRmG.js +1 -0
- package/ui-dist/assets/asn1-EdZsLKOL.js +1 -0
- package/ui-dist/assets/asterisk-B-8jnY81.js +1 -0
- package/ui-dist/assets/blockDiagram-VD42YOAC-D_3nEA4B.js +122 -0
- package/ui-dist/assets/brainfuck-C4LP7Hcl.js +1 -0
- package/ui-dist/assets/c4Diagram-YG6GDRKO-NqPZTfn7.js +10 -0
- package/ui-dist/assets/channel-D7AdA9V2.js +1 -0
- package/ui-dist/assets/chunk-4BX2VUAB-tMK9zEr7.js +1 -0
- package/ui-dist/assets/chunk-55IACEB6-DWaKiROy.js +1 -0
- package/ui-dist/assets/chunk-B4BG7PRW-CbA_TqG9.js +165 -0
- package/ui-dist/assets/chunk-DI55MBZ5-BWa54S__.js +220 -0
- package/ui-dist/assets/chunk-FMBD7UC4-DXu8dZmI.js +15 -0
- package/ui-dist/assets/chunk-QN33PNHL-BqB6ArE4.js +1 -0
- package/ui-dist/assets/chunk-QZHKN3VN-CERctbKo.js +1 -0
- package/ui-dist/assets/chunk-TZMSLE5B-Dp8FkMIs.js +1 -0
- package/ui-dist/assets/classDiagram-2ON5EDUG-DzVRFXNT.js +1 -0
- package/ui-dist/assets/classDiagram-v2-WZHVMYZB-DzVRFXNT.js +1 -0
- package/ui-dist/assets/clike-B9uivgTg.js +1 -0
- package/ui-dist/assets/clojure-BMjYHr_A.js +1 -0
- package/ui-dist/assets/clone-C_VGIz_D.js +1 -0
- package/ui-dist/assets/cmake-BQqOBYOt.js +1 -0
- package/ui-dist/assets/cobol-CWcv1MsR.js +1 -0
- package/ui-dist/assets/coffeescript-S37ZYGWr.js +1 -0
- package/ui-dist/assets/commonlisp-DBKNyK5s.js +1 -0
- package/ui-dist/assets/cose-bilkent-S5V4N54A-nuFb9gZh.js +1 -0
- package/ui-dist/assets/crystal-SjHAIU92.js +1 -0
- package/ui-dist/assets/css-BnMrqG3P.js +1 -0
- package/ui-dist/assets/cypher-C_CwsFkJ.js +1 -0
- package/ui-dist/assets/cytoscape.esm-BQaXIfA_.js +331 -0
- package/ui-dist/assets/d-pRatUO7H.js +1 -0
- package/ui-dist/assets/dagre-6UL2VRFP-COXI_RP-.js +4 -0
- package/ui-dist/assets/defaultLocale-DX6XiGOO.js +1 -0
- package/ui-dist/assets/diagram-PSM6KHXK-Cv3_gSji.js +24 -0
- package/ui-dist/assets/diagram-QEK2KX5R-EnFKfz5j.js +43 -0
- package/ui-dist/assets/diagram-S2PKOQOG-DFk9MizC.js +24 -0
- package/ui-dist/assets/diff-DbItnlRl.js +1 -0
- package/ui-dist/assets/dockerfile-BKs6k2Af.js +1 -0
- package/ui-dist/assets/dtd-DF_7sFjM.js +1 -0
- package/ui-dist/assets/dylan-DwRh75JA.js +1 -0
- package/ui-dist/assets/ebnf-CDyGwa7X.js +1 -0
- package/ui-dist/assets/ecl-Cabwm37j.js +1 -0
- package/ui-dist/assets/eiffel-CnydiIhH.js +1 -0
- package/ui-dist/assets/elm-vLlmbW-K.js +1 -0
- package/ui-dist/assets/erDiagram-Q2GNP2WA-BzTGjR4m.js +60 -0
- package/ui-dist/assets/erlang-BNw1qcRV.js +1 -0
- package/ui-dist/assets/factor-kuTfRLto.js +1 -0
- package/ui-dist/assets/fcl-Kvtd6kyn.js +1 -0
- package/ui-dist/assets/flowDiagram-NV44I4VS-BhxG9HVf.js +162 -0
- package/ui-dist/assets/forth-Ffai-XNe.js +1 -0
- package/ui-dist/assets/fortran-DYz_wnZ1.js +1 -0
- package/ui-dist/assets/ganttDiagram-JELNMOA3-D7x-T2Wm.js +267 -0
- package/ui-dist/assets/gas-Bneqetm1.js +1 -0
- package/ui-dist/assets/gherkin-heZmZLOM.js +1 -0
- package/ui-dist/assets/gitGraphDiagram-V2S2FVAM-3XW2I3EE.js +65 -0
- package/ui-dist/assets/graph-BVl_UcnC.js +1 -0
- package/ui-dist/assets/groovy-D9Dt4D0W.js +1 -0
- package/ui-dist/assets/haskell-Cw1EW3IL.js +1 -0
- package/ui-dist/assets/haxe-H-WmDvRZ.js +1 -0
- package/ui-dist/assets/http-DBlCnlav.js +1 -0
- package/ui-dist/assets/idl-BEugSyMb.js +1 -0
- package/ui-dist/assets/index-1uTJjl8a.js +1 -0
- package/ui-dist/assets/index-B7hacZaa.js +3 -0
- package/ui-dist/assets/index-BHf1Hzdf.css +1 -0
- package/ui-dist/assets/index-BSW5JwaH.js +1 -0
- package/ui-dist/assets/index-BZnHexpx.js +1 -0
- package/ui-dist/assets/index-BiQcZBBL.js +1 -0
- package/ui-dist/assets/index-BpFmY7hp.js +1 -0
- package/ui-dist/assets/index-C8TA_OLZ.js +1 -0
- package/ui-dist/assets/index-CMWIT5Av.js +1 -0
- package/ui-dist/assets/index-CVMKjtie.js +1 -0
- package/ui-dist/assets/index-Ce_rFd0H.js +2 -0
- package/ui-dist/assets/index-Cq0h5Zql.js +1 -0
- package/ui-dist/assets/index-Cz2Ibuki.js +227 -0
- package/ui-dist/assets/index-D5wnSweq.js +7 -0
- package/ui-dist/assets/index-DRpI4zkj.js +1 -0
- package/ui-dist/assets/index-DbELJA96.js +1 -0
- package/ui-dist/assets/index-IzLA2Fcd.js +1 -0
- package/ui-dist/assets/index-kLee7BdF.js +1 -0
- package/ui-dist/assets/index-vmBmu2hn.js +1 -0
- package/ui-dist/assets/infoDiagram-HS3SLOUP-BQIlcg9w.js +2 -0
- package/ui-dist/assets/init-Gi6I4Gst.js +1 -0
- package/ui-dist/assets/javascript-iXu5QeM3.js +1 -0
- package/ui-dist/assets/journeyDiagram-XKPGCS4Q-ob8GRXev.js +139 -0
- package/ui-dist/assets/julia-DuME0IfC.js +1 -0
- package/ui-dist/assets/kanban-definition-3W4ZIXB7-DRnEFfcR.js +89 -0
- package/ui-dist/assets/katex-O9d3_IXG.js +261 -0
- package/ui-dist/assets/layout-EfaGCOrM.js +1 -0
- package/ui-dist/assets/linear-DPC6vJZk.js +1 -0
- package/ui-dist/assets/livescript-BwQOo05w.js +1 -0
- package/ui-dist/assets/lua-BgMRiT3U.js +1 -0
- package/ui-dist/assets/mathematica-DTrFuWx2.js +1 -0
- package/ui-dist/assets/mbox-CNhZ1qSd.js +1 -0
- package/ui-dist/assets/mermaid.core-Cma2jq_8.js +256 -0
- package/ui-dist/assets/mindmap-definition-VGOIOE7T-D7BZyIVg.js +68 -0
- package/ui-dist/assets/mirc-CjQqDB4T.js +1 -0
- package/ui-dist/assets/mllike-CXdrOF99.js +1 -0
- package/ui-dist/assets/modelica-Dc1JOy9r.js +1 -0
- package/ui-dist/assets/mscgen-BA5vi2Kp.js +1 -0
- package/ui-dist/assets/mumps-BT43cFF4.js +1 -0
- package/ui-dist/assets/nginx-DdIZxoE0.js +1 -0
- package/ui-dist/assets/nsis-LdVXkNf5.js +1 -0
- package/ui-dist/assets/ntriples-BfvgReVJ.js +1 -0
- package/ui-dist/assets/octave-Ck1zUtKM.js +1 -0
- package/ui-dist/assets/ordinal-Cboi1Yqb.js +1 -0
- package/ui-dist/assets/oz-BzwKVEFT.js +1 -0
- package/ui-dist/assets/pascal--L3eBynH.js +1 -0
- package/ui-dist/assets/perl-CdXCOZ3F.js +1 -0
- package/ui-dist/assets/pieDiagram-ADFJNKIX-BvJHngd-.js +30 -0
- package/ui-dist/assets/pig-CevX1Tat.js +1 -0
- package/ui-dist/assets/powershell-CFHJl5sT.js +1 -0
- package/ui-dist/assets/properties-C78fOPTZ.js +1 -0
- package/ui-dist/assets/protobuf-ChK-085T.js +1 -0
- package/ui-dist/assets/pug-DeIclll2.js +1 -0
- package/ui-dist/assets/puppet-DMA9R1ak.js +1 -0
- package/ui-dist/assets/python-BuPzkPfP.js +1 -0
- package/ui-dist/assets/q-pXgVlZs6.js +1 -0
- package/ui-dist/assets/quadrantDiagram-AYHSOK5B-D_aE_NAU.js +7 -0
- package/ui-dist/assets/r-B6wPVr8A.js +1 -0
- package/ui-dist/assets/requirementDiagram-UZGBJVZJ-Co7ddlL_.js +64 -0
- package/ui-dist/assets/rpm-CTu-6PCP.js +1 -0
- package/ui-dist/assets/ruby-B2Rjki9n.js +1 -0
- package/ui-dist/assets/sankeyDiagram-TZEHDZUN-R0_C3AmA.js +10 -0
- package/ui-dist/assets/sas-B4kiWyti.js +1 -0
- package/ui-dist/assets/scheme-C41bIUwD.js +1 -0
- package/ui-dist/assets/sequenceDiagram-WL72ISMW-BcVqSpRw.js +145 -0
- package/ui-dist/assets/shell-CjFT_Tl9.js +1 -0
- package/ui-dist/assets/sieve-C3Gn_uJK.js +1 -0
- package/ui-dist/assets/simple-mode-GW_nhZxv.js +1 -0
- package/ui-dist/assets/smalltalk-CnHTOXQT.js +1 -0
- package/ui-dist/assets/solr-DehyRSwq.js +1 -0
- package/ui-dist/assets/sparql-DkYu6x3z.js +1 -0
- package/ui-dist/assets/spreadsheet-BCZA_wO0.js +1 -0
- package/ui-dist/assets/sql-D0XecflT.js +1 -0
- package/ui-dist/assets/stateDiagram-FKZM4ZOC-DYU4zTpw.js +1 -0
- package/ui-dist/assets/stateDiagram-v2-4FDKWEC3-BTQNL-wM.js +1 -0
- package/ui-dist/assets/stex-C3f8Ysf7.js +1 -0
- package/ui-dist/assets/stylus-B533Al4x.js +1 -0
- package/ui-dist/assets/swift-BzpIVaGY.js +1 -0
- package/ui-dist/assets/tcl-DVfN8rqt.js +1 -0
- package/ui-dist/assets/textile-CnDTJFAw.js +1 -0
- package/ui-dist/assets/tiddlywiki-DO-Gjzrf.js +1 -0
- package/ui-dist/assets/tiki-DGYXhP31.js +1 -0
- package/ui-dist/assets/timeline-definition-IT6M3QCI-CS7a2_SC.js +61 -0
- package/ui-dist/assets/toml-Bm5Em-hy.js +1 -0
- package/ui-dist/assets/treemap-GDKQZRPO-DXGAnUr4.js +162 -0
- package/ui-dist/assets/troff-wAsdV37c.js +1 -0
- package/ui-dist/assets/ttcn-CfJYG6tj.js +1 -0
- package/ui-dist/assets/ttcn-cfg-B9xdYoR4.js +1 -0
- package/ui-dist/assets/turtle-B1tBg_DP.js +1 -0
- package/ui-dist/assets/vb-CmGdzxic.js +1 -0
- package/ui-dist/assets/vbscript-BuJXcnF6.js +1 -0
- package/ui-dist/assets/velocity-D8B20fx6.js +1 -0
- package/ui-dist/assets/vendor-editor-C6NiDIhH.js +176 -0
- package/ui-dist/assets/vendor-query-Cn7TC_2z.js +9 -0
- package/ui-dist/assets/vendor-r3f-CKsrCNAb.js +98 -0
- package/ui-dist/assets/vendor-react-DGHjaq9o.js +28 -0
- package/ui-dist/assets/vendor-three-DXQ-izGk.js +3827 -0
- package/ui-dist/assets/vendor-ui-yncrCeEA.js +801 -0
- package/ui-dist/assets/verilog-C6RDOZhf.js +1 -0
- package/ui-dist/assets/vhdl-lSbBsy5d.js +1 -0
- package/ui-dist/assets/webidl-ZXfAyPTL.js +1 -0
- package/ui-dist/assets/xquery-DzFWVndE.js +1 -0
- package/ui-dist/assets/xychartDiagram-PRI3JC2R-D7cecXuv.js +7 -0
- package/ui-dist/assets/yacas-BJ4BC0dw.js +1 -0
- package/ui-dist/assets/z80-Hz9HOZM7.js +1 -0
- package/ui-dist/brands/opencode-logo-dark-square.svg +18 -0
- package/ui-dist/brands/opencode-logo-light-square.svg +18 -0
- package/ui-dist/favicon-16x16.png +0 -0
- package/ui-dist/favicon-32x32.png +0 -0
- package/ui-dist/favicon.ico +0 -0
- package/ui-dist/favicon.svg +9 -0
- package/ui-dist/index.html +55 -0
- package/ui-dist/models/agent-figure.glb +0 -0
- package/ui-dist/models/cars/1987_ferrari_f40.glb +0 -0
- package/ui-dist/models/cars/1987_mazda_rx-7_fc.glb +0 -0
- package/ui-dist/models/cars/1997_veilside_fortune_mazda_rx-7_fd_tokyo_drift.glb +0 -0
- package/ui-dist/models/cars/2010_r_magic_fd_armor_mazda_rx-7_fd3s.glb +0 -0
- package/ui-dist/models/cars/2023_lbsuper_silhouette_mazda_fd3s_rx-7.glb +0 -0
- package/ui-dist/models/chair.glb +0 -0
- package/ui-dist/models/filing-cabinet.glb +0 -0
- package/ui-dist/models/logos/nike_logo.glb +0 -0
- package/ui-dist/models/monitor.glb +0 -0
- package/ui-dist/models/movie_sonic_sonic_rumble.glb +0 -0
- package/ui-dist/models/office_chair (4).glb +0 -0
- package/ui-dist/models/plant-hanging.glb +0 -0
- package/ui-dist/models/plant-small.glb +0 -0
- package/ui-dist/models/plant-tall.glb +0 -0
- package/ui-dist/models/programmer_desktop_3d_pc.glb +0 -0
- package/ui-dist/models/rhyzome_plant.glb +0 -0
- package/ui-dist/models/server-rack.glb +0 -0
- package/ui-dist/models/simple_bunk_bed.glb +0 -0
- package/ui-dist/models/sofa.glb +0 -0
- package/ui-dist/models/table-round.glb +0 -0
- package/ui-dist/models/table.glb +0 -0
- package/ui-dist/models/tree/mango_tree.glb +0 -0
- package/ui-dist/models/whiteboard.glb +0 -0
- package/ui-dist/site.webmanifest +30 -0
- package/ui-dist/sw.js +42 -0
- package/ui-dist/worktree-favicon-16x16.png +0 -0
- package/ui-dist/worktree-favicon-32x32.png +0 -0
- package/ui-dist/worktree-favicon.ico +0 -0
- package/ui-dist/worktree-favicon.svg +9 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-Cma2jq_8.js","assets/vendor-editor-C6NiDIhH.js","assets/vendor-react-DGHjaq9o.js","assets/vendor-query-Cn7TC_2z.js","assets/Office-JSp1M1WZ.js","assets/vendor-r3f-CKsrCNAb.js","assets/vendor-three-DXQ-izGk.js","assets/vendor-ui-yncrCeEA.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var ik=Object.defineProperty;var lk=(t,n,s)=>n in t?ik(t,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[n]=s;var Ci=(t,n,s)=>lk(t,typeof n!="symbol"?n+"":n,s);import{a as at,u as oe,b as ge,j as e,c as gf,Q as ck,d as dk}from"./vendor-query-Cn7TC_2z.js";import{r as c,L as Zi,N as uk,u as Xn,h as fn,i as mk,j as pk,R as Bt,a as Lo,O as Rb,g as Pb,k as xk,l as ui,m as fk,n as _e,B as hk,o as gk,b as bk}from"./vendor-react-DGHjaq9o.js";import{r as yk,f as vk}from"./vendor-r3f-CKsrCNAb.js";import{x as jd,P as Lt,y as jr,z as kt,A as ur,B as As,D as Yi,F as po,G as br,H as jk,J as wk,K as hp,R as Nk,M as kk,O as Ck,Q as Mb,S as wd,T as Sk,U as Ik,V as $b,W as _k,X as Ak,Y as Ek,Z as Tk,$ as Rk,a0 as Db,a1 as Pk,a2 as Mk,a3 as $k,a4 as Qa,a5 as Dk,a6 as gp,a7 as Ok,a8 as Lk,a9 as Fk,aa as qk,ab as Uk,ac as Bk,ad as Kk,ae as zk,af as Wk,ag as Hk,ah as bp,ai as yp,aj as vp,ak as jp,al as Nd,am as Ob,an as Lb,ao as Fb,ap as qb,aq as Vk,ar as Qk,as as Gk,at as bf,au as Jk,av as Zk,aw as Yk,ax as Xk,ay as eC,az as tC,aA as nC,aB as sC,aC as rC,aD as aC,aE as oC,aF as iC,aG as lC,aH as cC,aI as dC,aJ as uC,aK as mC,aL as pC,aM as xC,aN as fC,aO as da,aP as yf,aQ as wp,aR as hC,aS as mi,aT as Ub,aU as gC,aV as bC,aW as yC,aX as vC,aY as vf,aZ as Zo,a_ as Np,a$ as wl,b0 as jC,b1 as wC,b2 as NC,b3 as kC,b4 as CC,b5 as SC,b6 as kp,b7 as Xi,b8 as Cr,b9 as IC,ba as _C,bb as Bb,bc as AC,bd as EC,be as TC,bf as RC,w as Kb,bg as PC,bh as MC,bi as $C,bj as DC,bk as OC,bl as LC,bm as FC,bn as qC,bo as UC,bp as BC,bq as KC,br as zC,bs as WC}from"./vendor-editor-C6NiDIhH.js";import{t as HC,c as VC,b as Cp,P as Ot,D as wr,C as sn,F as QC,d as GC,H as Sr,G as Sp,e as JC,f as ZC,T as YC,g as XC,R as e1,h as t1,A as n1,i as s1,j as Ir,k as Bo,l as el,m as Yo,n as r1,o as zb,p as Wb,L as a1,q as Hb,r as o1,s as i1,B as l1,u as c1,v as $i,w as d1,x as xo,y as Vb,z as u1,E as tl,I as ws,J as pi,K as Ip,N as kd,O as _p,Q as hm,Z as Xo,V as Ko,X as gm,Y as ss,_ as Ap,$ as Ka,a0 as Ga,a1 as rs,a2 as m1,a3 as Ja,a4 as nl,a5 as bm,a6 as wc,a7 as xc,a8 as Cd,a9 as sl,aa as zr,ab as rl,ac as Nl,ad as Sd,ae as p1,af as zt,ag as Nn,ah as ir,ai as Qb,aj as Ep,ak as Tp,al as Rp,am as Pp,an as rn,ao as Id,ap as Gb,aq as xi,ar as Nc,as as kn,at as x1,au as f1,av as zo,aw as Jb,ax as fo,ay as Zb,az as h1,U as Mp,aA as g1,aB as Wr,aC as b1,aD as ym,S as jf,M as wf,aE as al,aF as Ki,aG as Fo,aH as Ns,aI as _d,aJ as vm,aK as Is,aL as $p,aM as kc,aN as _r,aO as ho,aP as fi,aQ as Yb,aR as Cc,aS as Ls,aT as Xb,aU as kl,aV as Dp,aW as y1,aX as v1,aY as Op,aZ as ey,a_ as _s,a$ as j1,b0 as w1,b1 as N1,b2 as k1,b3 as Sc,b4 as ty,b5 as C1,b6 as S1,b7 as I1,b8 as _1,b9 as ei,ba as ti,bb as A1,bc as E1,bd as ny,be as sy,bf as Lp,bg as ry,bh as Za,bi as ay,bj as T1,bk as jm,bl as wm,bm as R1,bn as ol,bo as P1,bp as oy,bq as M1,br as $1,bs as D1,bt as O1,bu as Nf,bv as L1,bw as F1,bx as q1,by as U1,bz as B1,bA as K1}from"./vendor-ui-yncrCeEA.js";import"./vendor-three-DXQ-izGk.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function s(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(a){if(a.ep)return;a.ep=!0;const o=s(a);fetch(a.href,o)}})();const z1="/api";class Qr extends Error{constructor(s,r,a){super(s);Ci(this,"status");Ci(this,"body");this.name="ApiError",this.status=r,this.body=a}}async function jo(t,n){const s=new Headers((n==null?void 0:n.headers)??void 0);!((n==null?void 0:n.body)instanceof FormData)&&!s.has("Content-Type")&&s.set("Content-Type","application/json");const a=await fetch(`${z1}${t}`,{headers:s,credentials:"include",...n});if(!a.ok){const o=await a.json().catch(()=>null);throw new Qr((o==null?void 0:o.error)??`Request failed: ${a.status}`,a.status,o)}if(a.status!==204)return a.json()}const ne={get:t=>jo(t),post:(t,n)=>jo(t,{method:"POST",body:JSON.stringify(n)}),postForm:(t,n)=>jo(t,{method:"POST",body:n}),put:(t,n)=>jo(t,{method:"PUT",body:JSON.stringify(n)}),patch:(t,n)=>jo(t,{method:"PATCH",body:JSON.stringify(n)}),delete:t=>jo(t,{method:"DELETE"})},ls={list:()=>ne.get("/companies"),get:t=>ne.get(`/companies/${t}`),stats:()=>ne.get("/companies/stats"),create:t=>ne.post("/companies",t),update:(t,n)=>ne.patch(`/companies/${t}`,n),updateBranding:(t,n)=>ne.patch(`/companies/${t}/branding`,n),archive:t=>ne.post(`/companies/${t}/archive`,{}),remove:t=>ne.delete(`/companies/${t}`),exportBundle:(t,n)=>ne.post(`/companies/${t}/export`,n),exportPreview:(t,n)=>ne.post(`/companies/${t}/exports/preview`,n),exportPackage:(t,n)=>ne.post(`/companies/${t}/exports`,n),importPreview:t=>ne.post("/companies/import/preview",t),importBundle:t=>ne.post("/companies/import",t)},N={companies:{all:["companies"],detail:t=>["companies",t],stats:["companies","stats"]},companySkills:{list:t=>["company-skills",t],detail:(t,n)=>["company-skills",t,n],updateStatus:(t,n)=>["company-skills",t,n,"update-status"],file:(t,n,s)=>["company-skills",t,n,"file",s]},agents:{list:t=>["agents",t],detail:t=>["agents","detail",t],runtimeState:t=>["agents","runtime-state",t],taskSessions:t=>["agents","task-sessions",t],skills:t=>["agents","skills",t],instructionsBundle:t=>["agents","instructions-bundle",t],instructionsFile:(t,n)=>["agents","instructions-bundle",t,"file",n],keys:t=>["agents","keys",t],configRevisions:t=>["agents","config-revisions",t],adapterModels:(t,n)=>["agents",t,"adapter-models",n],detectModel:(t,n)=>["agents",t,"detect-model",n]},issues:{list:t=>["issues",t],search:(t,n,s)=>["issues",t,"search",n,s??"__all-projects__"],listAssignedToMe:t=>["issues",t,"assigned-to-me"],listMineByMe:t=>["issues",t,"mine-by-me"],listTouchedByMe:t=>["issues",t,"touched-by-me"],listUnreadTouchedByMe:t=>["issues",t,"unread-touched-by-me"],labels:t=>["issues",t,"labels"],listByProject:(t,n)=>["issues",t,"project",n],listByExecutionWorkspace:(t,n)=>["issues",t,"execution-workspace",n],detail:t=>["issues","detail",t],comments:t=>["issues","comments",t],attachments:t=>["issues","attachments",t],documents:t=>["issues","documents",t],documentRevisions:(t,n)=>["issues","document-revisions",t,n],activity:t=>["issues","activity",t],runs:t=>["issues","runs",t],approvals:t=>["issues","approvals",t],liveRuns:t=>["issues","live-runs",t],activeRun:t=>["issues","active-run",t],workProducts:t=>["issues","work-products",t]},routines:{list:t=>["routines",t],detail:t=>["routines","detail",t],runs:t=>["routines","runs",t],activity:(t,n)=>["routines","activity",t,n]},executionWorkspaces:{list:(t,n)=>["execution-workspaces",t,n??{}],detail:t=>["execution-workspaces","detail",t],closeReadiness:t=>["execution-workspaces","close-readiness",t],workspaceOperations:t=>["execution-workspaces","workspace-operations",t]},projects:{list:t=>["projects",t],detail:t=>["projects","detail",t]},goals:{list:t=>["goals",t],detail:t=>["goals","detail",t]},budgets:{overview:t=>["budgets","overview",t]},approvals:{list:(t,n)=>["approvals",t,n],detail:t=>["approvals","detail",t],comments:t=>["approvals","comments",t],issues:t=>["approvals","issues",t]},access:{joinRequests:(t,n="pending_approval")=>["access","join-requests",t,n],invite:t=>["access","invite",t]},auth:{session:["auth","session"]},instance:{generalSettings:["instance","general-settings"],schedulerHeartbeats:["instance","scheduler-heartbeats"],experimentalSettings:["instance","experimental-settings"]},health:["health"],secrets:{list:t=>["secrets",t],providers:t=>["secret-providers",t]},dashboard:t=>["dashboard",t],sidebarBadges:t=>["sidebar-badges",t],activity:t=>["activity",t],costs:(t,n,s)=>["costs",t,n,s],usageByProvider:(t,n,s)=>["usage-by-provider",t,n,s],usageByBiller:(t,n,s)=>["usage-by-biller",t,n,s],financeSummary:(t,n,s)=>["finance-summary",t,n,s],financeByBiller:(t,n,s)=>["finance-by-biller",t,n,s],financeByKind:(t,n,s)=>["finance-by-kind",t,n,s],financeEvents:(t,n,s,r=100)=>["finance-events",t,n,s,r],usageWindowSpend:t=>["usage-window-spend",t],usageQuotaWindows:t=>["usage-quota-windows",t],heartbeats:(t,n)=>["heartbeats",t,n],runDetail:t=>["heartbeat-run",t],runWorkspaceOperations:t=>["heartbeat-run",t,"workspace-operations"],liveRuns:t=>["live-runs",t],runIssues:t=>["run-issues",t],org:t=>["org",t],skills:{available:["skills","available"]},plugins:{all:["plugins"],examples:["plugins","examples"],detail:t=>["plugins",t],health:t=>["plugins",t,"health"],uiContributions:["plugins","ui-contributions"],config:t=>["plugins",t,"config"],dashboard:t=>["plugins",t,"dashboard"],logs:t=>["plugins",t,"logs"]},memories:{graph:t=>["memories","graph",t]}},Kl="crewspace.selectedCompanyId",iy=c.createContext(null);function W1({children:t}){const n=at(),[s,r]=c.useState("bootstrap"),[a,o]=c.useState(()=>localStorage.getItem(Kl)),{data:i=[],isLoading:l,error:u}=oe({queryKey:N.companies.all,queryFn:async()=>{try{return await ls.list()}catch(b){if(b instanceof Qr&&b.status===401)return[];throw b}},retry:!1}),d=c.useMemo(()=>i.filter(b=>b.status!=="archived"),[i]);c.useEffect(()=>{if(i.length===0)return;const b=d.length>0?d:i,g=localStorage.getItem(Kl);if(g&&b.some(v=>v.id===g)||a&&b.some(v=>v.id===a))return;const y=b[0].id;o(y),r("bootstrap"),localStorage.setItem(Kl,y)},[i,a,d]);const m=c.useCallback((b,g)=>{o(b),r((g==null?void 0:g.source)??"manual"),localStorage.setItem(Kl,b)},[]),p=c.useCallback(async()=>{await n.invalidateQueries({queryKey:N.companies.all})},[n]),x=ge({mutationFn:b=>ls.create(b),onSuccess:b=>{n.invalidateQueries({queryKey:N.companies.all}),m(b.id)}}),f=c.useCallback(async b=>x.mutateAsync(b),[x]),h=c.useMemo(()=>i.find(b=>b.id===a)??null,[i,a]),j=c.useMemo(()=>({companies:i,selectedCompanyId:a,selectedCompany:h,selectionSource:s,loading:l,error:u,setSelectedCompanyId:m,reloadCompanies:p,createCompany:f}),[i,a,h,s,l,u,m,p,f]);return e.jsx(iy.Provider,{value:j,children:t})}function et(){const t=c.useContext(iy);if(!t)throw new Error("useCompany must be used within CompanyProvider");return t}const ly=new Set(["dashboard","companies","company","skills","org","agents","projects","execution-workspaces","issues","routines","goals","approvals","costs","usage","activity","inbox","design-guide"]),Fp=new Set(["auth","invite","board-claim","cli-auth","docs","instance"]);function va(t){return t.trim().toUpperCase()}function cy(t){const n=t.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);return{pathname:(n==null?void 0:n[1])??t,search:(n==null?void 0:n[2])??"",hash:(n==null?void 0:n[3])??""}}function H1(t){return t.split("/").filter(Boolean)[0]??null}function V1(t){if(t==="/")return!0;const n=H1(t);return n?Fp.has(n.toLowerCase()):!0}function qp(t){const n=t.split("/").filter(Boolean);if(n.length===0)return null;const s=n[0].toLowerCase();return Fp.has(s)||ly.has(s)?null:va(n[0])}function kf(t,n){const{pathname:s,search:r,hash:a}=cy(t);if(!s.startsWith("/")||V1(s)||!n)return t;const o=va(n);return qp(s)?t:`/${o}${s}${r}${a}`}function Up(t){const{pathname:n,search:s,hash:r}=cy(t),a=n.split("/").filter(Boolean);if(a.length>=2){const o=a[1].toLowerCase();if(!Fp.has(a[0].toLowerCase())&&ly.has(o))return`/${a.slice(1).join("/")}${s}${r}`}return`${n}${s}${r}`}function Ad(t,n){if(typeof t=="string")return kf(t,n);if(t.pathname&&t.pathname.startsWith("/")){const s=kf(t.pathname,n);if(s!==t.pathname)return{...t,pathname:s}}return t}function Ed(){const{selectedCompany:t}=et(),n=Xn(),s=fn();if(n.companyPrefix)return va(n.companyPrefix);const r=qp(s.pathname);return r||(t?va(t.issuePrefix):null)}const Oe=c.forwardRef(function({to:n,...s},r){const a=Ed();return e.jsx(Zi,{ref:r,to:Ad(n,a),...s})}),Cl=c.forwardRef(function({to:n,...s},r){const a=Ed();return e.jsx(uk,{ref:r,to:Ad(n,a),...s})});function Zt({to:t,...n}){const s=Ed();return e.jsx(pk,{to:Ad(t,s),...n})}function Sn(){const t=mk(),n=Ed();return c.useCallback(((s,r)=>{if(typeof s=="number"){t(s);return}t(Ad(s,n),r)}),[t,n])}var Td="Collapsible",[Q1]=po(Td),[G1,Bp]=Q1(Td),dy=c.forwardRef((t,n)=>{const{__scopeCollapsible:s,open:r,defaultOpen:a,disabled:o,onOpenChange:i,...l}=t,[u,d]=jd({prop:r,defaultProp:a??!1,onChange:i,caller:Td});return e.jsx(G1,{scope:s,disabled:o,contentId:jr(),open:u,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),children:e.jsx(Lt.div,{"data-state":zp(u),"data-disabled":o?"":void 0,...l,ref:n})})});dy.displayName=Td;var uy="CollapsibleTrigger",my=c.forwardRef((t,n)=>{const{__scopeCollapsible:s,...r}=t,a=Bp(uy,s);return e.jsx(Lt.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":zp(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:n,onClick:kt(t.onClick,a.onOpenToggle)})});my.displayName=uy;var Kp="CollapsibleContent",py=c.forwardRef((t,n)=>{const{forceMount:s,...r}=t,a=Bp(Kp,t.__scopeCollapsible);return e.jsx(ur,{present:s||a.open,children:({present:o})=>e.jsx(J1,{...r,ref:n,present:o})})});py.displayName=Kp;var J1=c.forwardRef((t,n)=>{const{__scopeCollapsible:s,present:r,children:a,...o}=t,i=Bp(Kp,s),[l,u]=c.useState(r),d=c.useRef(null),m=As(n,d),p=c.useRef(0),x=p.current,f=c.useRef(0),h=f.current,j=i.open||l,b=c.useRef(j),g=c.useRef(void 0);return c.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),Yi(()=>{const y=d.current;if(y){g.current=g.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const v=y.getBoundingClientRect();p.current=v.height,f.current=v.width,b.current||(y.style.transitionDuration=g.current.transitionDuration,y.style.animationName=g.current.animationName),u(r)}},[i.open,r]),e.jsx(Lt.div,{"data-state":zp(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!j,...o,ref:m,style:{"--radix-collapsible-content-height":x?`${x}px`:void 0,"--radix-collapsible-content-width":h?`${h}px`:void 0,...t.style},children:j&&a})});function zp(t){return t?"open":"closed"}var Z1=dy,Y1=yk();function X1(){return Y1.useSyncExternalStore(eS,()=>!0,()=>!1)}function eS(){return()=>{}}var Wp="Avatar",[tS]=po(Wp),[nS,xy]=tS(Wp),fy=c.forwardRef((t,n)=>{const{__scopeAvatar:s,...r}=t,[a,o]=c.useState("idle");return e.jsx(nS,{scope:s,imageLoadingStatus:a,onImageLoadingStatusChange:o,children:e.jsx(Lt.span,{...r,ref:n})})});fy.displayName=Wp;var hy="AvatarImage",gy=c.forwardRef((t,n)=>{const{__scopeAvatar:s,src:r,onLoadingStatusChange:a=()=>{},...o}=t,i=xy(hy,s),l=sS(r,o),u=br(d=>{a(d),i.onImageLoadingStatusChange(d)});return Yi(()=>{l!=="idle"&&u(l)},[l,u]),l==="loaded"?e.jsx(Lt.img,{...o,ref:n,src:r}):null});gy.displayName=hy;var by="AvatarFallback",yy=c.forwardRef((t,n)=>{const{__scopeAvatar:s,delayMs:r,...a}=t,o=xy(by,s),[i,l]=c.useState(r===void 0);return c.useEffect(()=>{if(r!==void 0){const u=window.setTimeout(()=>l(!0),r);return()=>window.clearTimeout(u)}},[r]),i&&o.imageLoadingStatus!=="loaded"?e.jsx(Lt.span,{...a,ref:n}):null});yy.displayName=by;function Cf(t,n){return t?n?(t.src!==n&&(t.src=n),t.complete&&t.naturalWidth>0?"loaded":"loading"):"error":"idle"}function sS(t,{referrerPolicy:n,crossOrigin:s}){const r=X1(),a=c.useRef(null),o=r?(a.current||(a.current=new window.Image),a.current):null,[i,l]=c.useState(()=>Cf(o,t));return Yi(()=>{l(Cf(o,t))},[o,t]),Yi(()=>{const u=p=>()=>{l(p)};if(!o)return;const d=u("loaded"),m=u("error");return o.addEventListener("load",d),o.addEventListener("error",m),n&&(o.referrerPolicy=n),typeof s=="string"&&(o.crossOrigin=s),()=>{o.removeEventListener("load",d),o.removeEventListener("error",m)}},[o,s,n]),i}var rS=fy,aS=gy,oS=yy,Rd="Checkbox",[iS]=po(Rd),[lS,Hp]=iS(Rd);function cS(t){const{__scopeCheckbox:n,checked:s,children:r,defaultChecked:a,disabled:o,form:i,name:l,onCheckedChange:u,required:d,value:m="on",internal_do_not_use_render:p}=t,[x,f]=jd({prop:s,defaultProp:a??!1,onChange:u,caller:Rd}),[h,j]=c.useState(null),[b,g]=c.useState(null),y=c.useRef(!1),v=h?!!i||!!h.closest("form"):!0,_={checked:x,disabled:o,setChecked:f,control:h,setControl:j,name:l,form:i,value:m,hasConsumerStoppedPropagationRef:y,required:d,defaultChecked:xa(a)?!1:a,isFormControl:v,bubbleInput:b,setBubbleInput:g};return e.jsx(lS,{scope:n,..._,children:dS(p)?p(_):r})}var vy="CheckboxTrigger",jy=c.forwardRef(({__scopeCheckbox:t,onKeyDown:n,onClick:s,...r},a)=>{const{control:o,value:i,disabled:l,checked:u,required:d,setControl:m,setChecked:p,hasConsumerStoppedPropagationRef:x,isFormControl:f,bubbleInput:h}=Hp(vy,t),j=As(a,m),b=c.useRef(u);return c.useEffect(()=>{const g=o==null?void 0:o.form;if(g){const y=()=>p(b.current);return g.addEventListener("reset",y),()=>g.removeEventListener("reset",y)}},[o,p]),e.jsx(Lt.button,{type:"button",role:"checkbox","aria-checked":xa(u)?"mixed":u,"aria-required":d,"data-state":Iy(u),"data-disabled":l?"":void 0,disabled:l,value:i,...r,ref:j,onKeyDown:kt(n,g=>{g.key==="Enter"&&g.preventDefault()}),onClick:kt(s,g=>{p(y=>xa(y)?!0:!y),h&&f&&(x.current=g.isPropagationStopped(),x.current||g.stopPropagation())})})});jy.displayName=vy;var wy=c.forwardRef((t,n)=>{const{__scopeCheckbox:s,name:r,checked:a,defaultChecked:o,required:i,disabled:l,value:u,onCheckedChange:d,form:m,...p}=t;return e.jsx(cS,{__scopeCheckbox:s,checked:a,defaultChecked:o,disabled:l,required:i,onCheckedChange:d,name:r,form:m,value:u,internal_do_not_use_render:({isFormControl:x})=>e.jsxs(e.Fragment,{children:[e.jsx(jy,{...p,ref:n,__scopeCheckbox:s}),x&&e.jsx(Sy,{__scopeCheckbox:s})]})})});wy.displayName=Rd;var Ny="CheckboxIndicator",ky=c.forwardRef((t,n)=>{const{__scopeCheckbox:s,forceMount:r,...a}=t,o=Hp(Ny,s);return e.jsx(ur,{present:r||xa(o.checked)||o.checked===!0,children:e.jsx(Lt.span,{"data-state":Iy(o.checked),"data-disabled":o.disabled?"":void 0,...a,ref:n,style:{pointerEvents:"none",...t.style}})})});ky.displayName=Ny;var Cy="CheckboxBubbleInput",Sy=c.forwardRef(({__scopeCheckbox:t,...n},s)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:o,defaultChecked:i,required:l,disabled:u,name:d,value:m,form:p,bubbleInput:x,setBubbleInput:f}=Hp(Cy,t),h=As(s,f),j=jk(o),b=wk(r);c.useEffect(()=>{const y=x;if(!y)return;const v=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(v,"checked").set,S=!a.current;if(j!==o&&E){const M=new Event("click",{bubbles:S});y.indeterminate=xa(o),E.call(y,xa(o)?!1:o),y.dispatchEvent(M)}},[x,j,o,a]);const g=c.useRef(xa(o)?!1:o);return e.jsx(Lt.input,{type:"checkbox","aria-hidden":!0,defaultChecked:i??g.current,required:l,disabled:u,name:d,value:m,form:p,...n,tabIndex:-1,ref:h,style:{...n.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Sy.displayName=Cy;function dS(t){return typeof t=="function"}function xa(t){return t==="indeterminate"}function Iy(t){return xa(t)?"indeterminate":t?"checked":"unchecked"}var Nm=["Enter"," "],uS=["ArrowDown","PageUp","Home"],_y=["ArrowUp","PageDown","End"],mS=[...uS,..._y],pS={ltr:[...Nm,"ArrowRight"],rtl:[...Nm,"ArrowLeft"]},xS={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Sl="Menu",[il,fS,hS]=Sk(Sl),[go,Ay]=po(Sl,[hS,Mb,wd]),Pd=Mb(),Ey=wd(),[gS,bo]=go(Sl),[bS,Il]=go(Sl),Ty=t=>{const{__scopeMenu:n,open:s=!1,children:r,dir:a,onOpenChange:o,modal:i=!0}=t,l=Pd(n),[u,d]=c.useState(null),m=c.useRef(!1),p=br(o),x=hp(a);return c.useEffect(()=>{const f=()=>{m.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>m.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),e.jsx(Nk,{...l,children:e.jsx(gS,{scope:n,open:s,onOpenChange:p,content:u,onContentChange:d,children:e.jsx(bS,{scope:n,onClose:c.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:m,dir:x,modal:i,children:r})})})};Ty.displayName=Sl;var yS="MenuAnchor",Vp=c.forwardRef((t,n)=>{const{__scopeMenu:s,...r}=t,a=Pd(s);return e.jsx(kk,{...a,...r,ref:n})});Vp.displayName=yS;var Qp="MenuPortal",[vS,Ry]=go(Qp,{forceMount:void 0}),Py=t=>{const{__scopeMenu:n,forceMount:s,children:r,container:a}=t,o=bo(Qp,n);return e.jsx(vS,{scope:n,forceMount:s,children:e.jsx(ur,{present:s||o.open,children:e.jsx(Ck,{asChild:!0,container:a,children:r})})})};Py.displayName=Qp;var Js="MenuContent",[jS,Gp]=go(Js),My=c.forwardRef((t,n)=>{const s=Ry(Js,t.__scopeMenu),{forceMount:r=s.forceMount,...a}=t,o=bo(Js,t.__scopeMenu),i=Il(Js,t.__scopeMenu);return e.jsx(il.Provider,{scope:t.__scopeMenu,children:e.jsx(ur,{present:r||o.open,children:e.jsx(il.Slot,{scope:t.__scopeMenu,children:i.modal?e.jsx(wS,{...a,ref:n}):e.jsx(NS,{...a,ref:n})})})})}),wS=c.forwardRef((t,n)=>{const s=bo(Js,t.__scopeMenu),r=c.useRef(null),a=As(n,r);return c.useEffect(()=>{const o=r.current;if(o)return Ik(o)},[]),e.jsx(Jp,{...t,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,disableOutsideScroll:!0,onFocusOutside:kt(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>s.onOpenChange(!1)})}),NS=c.forwardRef((t,n)=>{const s=bo(Js,t.__scopeMenu);return e.jsx(Jp,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>s.onOpenChange(!1)})}),kS=Mk("MenuContent.ScrollLock"),Jp=c.forwardRef((t,n)=>{const{__scopeMenu:s,loop:r=!1,trapFocus:a,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:x,onDismiss:f,disableOutsideScroll:h,...j}=t,b=bo(Js,s),g=Il(Js,s),y=Pd(s),v=Ey(s),_=fS(s),[E,S]=c.useState(null),M=c.useRef(null),B=As(n,M,b.onContentChange),k=c.useRef(0),L=c.useRef(""),$=c.useRef(0),C=c.useRef(null),I=c.useRef("right"),K=c.useRef(0),T=h?Ek:c.Fragment,z=h?{as:kS,allowPinchZoom:!0}:void 0,w=A=>{var J,Y;const R=L.current+A,Q=_().filter(de=>!de.disabled),H=document.activeElement,U=(J=Q.find(de=>de.ref.current===H))==null?void 0:J.textValue,Z=Q.map(de=>de.textValue),V=DS(Z,R,U),W=(Y=Q.find(de=>de.textValue===V))==null?void 0:Y.ref.current;(function de(fe){L.current=fe,window.clearTimeout(k.current),fe!==""&&(k.current=window.setTimeout(()=>de(""),1e3))})(R),W&&setTimeout(()=>W.focus())};c.useEffect(()=>()=>window.clearTimeout(k.current),[]),Ak();const F=c.useCallback(A=>{var Q,H;return I.current===((Q=C.current)==null?void 0:Q.side)&&LS(A,(H=C.current)==null?void 0:H.area)},[]);return e.jsx(jS,{scope:s,searchRef:L,onItemEnter:c.useCallback(A=>{F(A)&&A.preventDefault()},[F]),onItemLeave:c.useCallback(A=>{var R;F(A)||((R=M.current)==null||R.focus(),S(null))},[F]),onTriggerLeave:c.useCallback(A=>{F(A)&&A.preventDefault()},[F]),pointerGraceTimerRef:$,onPointerGraceIntentChange:c.useCallback(A=>{C.current=A},[]),children:e.jsx(T,{...z,children:e.jsx(Tk,{asChild:!0,trapped:a,onMountAutoFocus:kt(o,A=>{var R;A.preventDefault(),(R=M.current)==null||R.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:e.jsx(Rk,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:x,onDismiss:f,children:e.jsx(Db,{asChild:!0,...v,dir:g.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:S,onEntryFocus:kt(u,A=>{g.isUsingKeyboardRef.current||A.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(Pk,{role:"menu","aria-orientation":"vertical","data-state":Jy(b.open),"data-radix-menu-content":"",dir:g.dir,...y,...j,ref:B,style:{outline:"none",...j.style},onKeyDown:kt(j.onKeyDown,A=>{const Q=A.target.closest("[data-radix-menu-content]")===A.currentTarget,H=A.ctrlKey||A.altKey||A.metaKey,U=A.key.length===1;Q&&(A.key==="Tab"&&A.preventDefault(),!H&&U&&w(A.key));const Z=M.current;if(A.target!==Z||!mS.includes(A.key))return;A.preventDefault();const W=_().filter(J=>!J.disabled).map(J=>J.ref.current);_y.includes(A.key)&&W.reverse(),MS(W)}),onBlur:kt(t.onBlur,A=>{A.currentTarget.contains(A.target)||(window.clearTimeout(k.current),L.current="")}),onPointerMove:kt(t.onPointerMove,ll(A=>{const R=A.target,Q=K.current!==A.clientX;if(A.currentTarget.contains(R)&&Q){const H=A.clientX>K.current?"right":"left";I.current=H,K.current=A.clientX}}))})})})})})})});My.displayName=Js;var CS="MenuGroup",Zp=c.forwardRef((t,n)=>{const{__scopeMenu:s,...r}=t;return e.jsx(Lt.div,{role:"group",...r,ref:n})});Zp.displayName=CS;var SS="MenuLabel",$y=c.forwardRef((t,n)=>{const{__scopeMenu:s,...r}=t;return e.jsx(Lt.div,{...r,ref:n})});$y.displayName=SS;var Ic="MenuItem",Sf="menu.itemSelect",Md=c.forwardRef((t,n)=>{const{disabled:s=!1,onSelect:r,...a}=t,o=c.useRef(null),i=Il(Ic,t.__scopeMenu),l=Gp(Ic,t.__scopeMenu),u=As(n,o),d=c.useRef(!1),m=()=>{const p=o.current;if(!s&&p){const x=new CustomEvent(Sf,{bubbles:!0,cancelable:!0});p.addEventListener(Sf,f=>r==null?void 0:r(f),{once:!0}),_k(p,x),x.defaultPrevented?d.current=!1:i.onClose()}};return e.jsx(Dy,{...a,ref:u,disabled:s,onClick:kt(t.onClick,m),onPointerDown:p=>{var x;(x=t.onPointerDown)==null||x.call(t,p),d.current=!0},onPointerUp:kt(t.onPointerUp,p=>{var x;d.current||(x=p.currentTarget)==null||x.click()}),onKeyDown:kt(t.onKeyDown,p=>{const x=l.searchRef.current!=="";s||x&&p.key===" "||Nm.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});Md.displayName=Ic;var Dy=c.forwardRef((t,n)=>{const{__scopeMenu:s,disabled:r=!1,textValue:a,...o}=t,i=Gp(Ic,s),l=Ey(s),u=c.useRef(null),d=As(n,u),[m,p]=c.useState(!1),[x,f]=c.useState("");return c.useEffect(()=>{const h=u.current;h&&f((h.textContent??"").trim())},[o.children]),e.jsx(il.ItemSlot,{scope:s,disabled:r,textValue:a??x,children:e.jsx($b,{asChild:!0,...l,focusable:!r,children:e.jsx(Lt.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:d,onPointerMove:kt(t.onPointerMove,ll(h=>{r?i.onItemLeave(h):(i.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:kt(t.onPointerLeave,ll(h=>i.onItemLeave(h))),onFocus:kt(t.onFocus,()=>p(!0)),onBlur:kt(t.onBlur,()=>p(!1))})})})}),IS="MenuCheckboxItem",Oy=c.forwardRef((t,n)=>{const{checked:s=!1,onCheckedChange:r,...a}=t;return e.jsx(By,{scope:t.__scopeMenu,checked:s,children:e.jsx(Md,{role:"menuitemcheckbox","aria-checked":_c(s)?"mixed":s,...a,ref:n,"data-state":Xp(s),onSelect:kt(a.onSelect,()=>r==null?void 0:r(_c(s)?!0:!s),{checkForDefaultPrevented:!1})})})});Oy.displayName=IS;var Ly="MenuRadioGroup",[_S,AS]=go(Ly,{value:void 0,onValueChange:()=>{}}),Fy=c.forwardRef((t,n)=>{const{value:s,onValueChange:r,...a}=t,o=br(r);return e.jsx(_S,{scope:t.__scopeMenu,value:s,onValueChange:o,children:e.jsx(Zp,{...a,ref:n})})});Fy.displayName=Ly;var qy="MenuRadioItem",Uy=c.forwardRef((t,n)=>{const{value:s,...r}=t,a=AS(qy,t.__scopeMenu),o=s===a.value;return e.jsx(By,{scope:t.__scopeMenu,checked:o,children:e.jsx(Md,{role:"menuitemradio","aria-checked":o,...r,ref:n,"data-state":Xp(o),onSelect:kt(r.onSelect,()=>{var i;return(i=a.onValueChange)==null?void 0:i.call(a,s)},{checkForDefaultPrevented:!1})})})});Uy.displayName=qy;var Yp="MenuItemIndicator",[By,ES]=go(Yp,{checked:!1}),Ky=c.forwardRef((t,n)=>{const{__scopeMenu:s,forceMount:r,...a}=t,o=ES(Yp,s);return e.jsx(ur,{present:r||_c(o.checked)||o.checked===!0,children:e.jsx(Lt.span,{...a,ref:n,"data-state":Xp(o.checked)})})});Ky.displayName=Yp;var TS="MenuSeparator",zy=c.forwardRef((t,n)=>{const{__scopeMenu:s,...r}=t;return e.jsx(Lt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:n})});zy.displayName=TS;var RS="MenuArrow",Wy=c.forwardRef((t,n)=>{const{__scopeMenu:s,...r}=t,a=Pd(s);return e.jsx($k,{...a,...r,ref:n})});Wy.displayName=RS;var PS="MenuSub",[nW,Hy]=go(PS),Di="MenuSubTrigger",Vy=c.forwardRef((t,n)=>{const s=bo(Di,t.__scopeMenu),r=Il(Di,t.__scopeMenu),a=Hy(Di,t.__scopeMenu),o=Gp(Di,t.__scopeMenu),i=c.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=o,d={__scopeMenu:t.__scopeMenu},m=c.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return c.useEffect(()=>m,[m]),c.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),e.jsx(Vp,{asChild:!0,...d,children:e.jsx(Dy,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":a.contentId,"data-state":Jy(s.open),...t,ref:Qa(n,a.onTriggerChange),onClick:p=>{var x;(x=t.onClick)==null||x.call(t,p),!(t.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),s.open||s.onOpenChange(!0))},onPointerMove:kt(t.onPointerMove,ll(p=>{o.onItemEnter(p),!p.defaultPrevented&&!t.disabled&&!s.open&&!i.current&&(o.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{s.onOpenChange(!0),m()},100))})),onPointerLeave:kt(t.onPointerLeave,ll(p=>{var f,h;m();const x=(f=s.content)==null?void 0:f.getBoundingClientRect();if(x){const j=(h=s.content)==null?void 0:h.dataset.side,b=j==="right",g=b?-5:5,y=x[b?"left":"right"],v=x[b?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+g,y:p.clientY},{x:y,y:x.top},{x:v,y:x.top},{x:v,y:x.bottom},{x:y,y:x.bottom}],side:j}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(p),p.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:kt(t.onKeyDown,p=>{var f;const x=o.searchRef.current!=="";t.disabled||x&&p.key===" "||pS[r.dir].includes(p.key)&&(s.onOpenChange(!0),(f=s.content)==null||f.focus(),p.preventDefault())})})})});Vy.displayName=Di;var Qy="MenuSubContent",Gy=c.forwardRef((t,n)=>{const s=Ry(Js,t.__scopeMenu),{forceMount:r=s.forceMount,...a}=t,o=bo(Js,t.__scopeMenu),i=Il(Js,t.__scopeMenu),l=Hy(Qy,t.__scopeMenu),u=c.useRef(null),d=As(n,u);return e.jsx(il.Provider,{scope:t.__scopeMenu,children:e.jsx(ur,{present:r||o.open,children:e.jsx(il.Slot,{scope:t.__scopeMenu,children:e.jsx(Jp,{id:l.contentId,"aria-labelledby":l.triggerId,...a,ref:d,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;i.isUsingKeyboardRef.current&&((p=u.current)==null||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:kt(t.onFocusOutside,m=>{m.target!==l.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:kt(t.onEscapeKeyDown,m=>{i.onClose(),m.preventDefault()}),onKeyDown:kt(t.onKeyDown,m=>{var f;const p=m.currentTarget.contains(m.target),x=xS[i.dir].includes(m.key);p&&x&&(o.onOpenChange(!1),(f=l.trigger)==null||f.focus(),m.preventDefault())})})})})})});Gy.displayName=Qy;function Jy(t){return t?"open":"closed"}function _c(t){return t==="indeterminate"}function Xp(t){return _c(t)?"indeterminate":t?"checked":"unchecked"}function MS(t){const n=document.activeElement;for(const s of t)if(s===n||(s.focus(),document.activeElement!==n))return}function $S(t,n){return t.map((s,r)=>t[(n+r)%t.length])}function DS(t,n,s){const a=n.length>1&&Array.from(n).every(d=>d===n[0])?n[0]:n,o=s?t.indexOf(s):-1;let i=$S(t,Math.max(o,0));a.length===1&&(i=i.filter(d=>d!==s));const u=i.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return u!==s?u:void 0}function OS(t,n){const{x:s,y:r}=t;let a=!1;for(let o=0,i=n.length-1;o<n.length;i=o++){const l=n[o],u=n[i],d=l.x,m=l.y,p=u.x,x=u.y;m>r!=x>r&&s<(p-d)*(r-m)/(x-m)+d&&(a=!a)}return a}function LS(t,n){if(!n)return!1;const s={x:t.clientX,y:t.clientY};return OS(s,n)}function ll(t){return n=>n.pointerType==="mouse"?t(n):void 0}var FS=Ty,qS=Vp,US=Py,BS=My,KS=Zp,zS=$y,WS=Md,HS=Oy,VS=Fy,QS=Uy,GS=Ky,JS=zy,ZS=Wy,YS=Vy,XS=Gy,$d="DropdownMenu",[eI]=po($d,[Ay]),hs=Ay(),[tI,Zy]=eI($d),Yy=t=>{const{__scopeDropdownMenu:n,children:s,dir:r,open:a,defaultOpen:o,onOpenChange:i,modal:l=!0}=t,u=hs(n),d=c.useRef(null),[m,p]=jd({prop:a,defaultProp:o??!1,onChange:i,caller:$d});return e.jsx(tI,{scope:n,triggerId:jr(),triggerRef:d,contentId:jr(),open:m,onOpenChange:p,onOpenToggle:c.useCallback(()=>p(x=>!x),[p]),modal:l,children:e.jsx(FS,{...u,open:m,onOpenChange:p,dir:r,modal:l,children:s})})};Yy.displayName=$d;var Xy="DropdownMenuTrigger",ev=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,disabled:r=!1,...a}=t,o=Zy(Xy,s),i=hs(s);return e.jsx(qS,{asChild:!0,...i,children:e.jsx(Lt.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:Qa(n,o.triggerRef),onPointerDown:kt(t.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(o.onOpenToggle(),o.open||l.preventDefault())}),onKeyDown:kt(t.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&o.onOpenToggle(),l.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});ev.displayName=Xy;var nI="DropdownMenuPortal",tv=t=>{const{__scopeDropdownMenu:n,...s}=t,r=hs(n);return e.jsx(US,{...r,...s})};tv.displayName=nI;var nv="DropdownMenuContent",sv=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=Zy(nv,s),o=hs(s),i=c.useRef(!1);return e.jsx(BS,{id:a.contentId,"aria-labelledby":a.triggerId,...o,...r,ref:n,onCloseAutoFocus:kt(t.onCloseAutoFocus,l=>{var u;i.current||(u=a.triggerRef.current)==null||u.focus(),i.current=!1,l.preventDefault()}),onInteractOutside:kt(t.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,m=u.button===2||d;(!a.modal||m)&&(i.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});sv.displayName=nv;var sI="DropdownMenuGroup",rI=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(KS,{...a,...r,ref:n})});rI.displayName=sI;var aI="DropdownMenuLabel",rv=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(zS,{...a,...r,ref:n})});rv.displayName=aI;var oI="DropdownMenuItem",av=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(WS,{...a,...r,ref:n})});av.displayName=oI;var iI="DropdownMenuCheckboxItem",ov=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(HS,{...a,...r,ref:n})});ov.displayName=iI;var lI="DropdownMenuRadioGroup",iv=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(VS,{...a,...r,ref:n})});iv.displayName=lI;var cI="DropdownMenuRadioItem",lv=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(QS,{...a,...r,ref:n})});lv.displayName=cI;var dI="DropdownMenuItemIndicator",cv=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(GS,{...a,...r,ref:n})});cv.displayName=dI;var uI="DropdownMenuSeparator",dv=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(JS,{...a,...r,ref:n})});dv.displayName=uI;var mI="DropdownMenuArrow",pI=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(ZS,{...a,...r,ref:n})});pI.displayName=mI;var xI="DropdownMenuSubTrigger",fI=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(YS,{...a,...r,ref:n})});fI.displayName=xI;var hI="DropdownMenuSubContent",gI=c.forwardRef((t,n)=>{const{__scopeDropdownMenu:s,...r}=t,a=hs(s);return e.jsx(XS,{...a,...r,ref:n,style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});gI.displayName=hI;var bI=Yy,yI=ev,vI=tv,jI=sv,wI=rv,NI=av,kI=ov,CI=iv,SI=lv,uv=cv,II=dv,_I="Label",mv=c.forwardRef((t,n)=>e.jsx(Lt.label,{...t,ref:n,onMouseDown:s=>{var a;s.target.closest("button, input, select, textarea")||((a=t.onMouseDown)==null||a.call(t,s),!s.defaultPrevented&&s.detail>1&&s.preventDefault())}}));mv.displayName=_I;var AI=mv;function EI(t,n){return c.useReducer((s,r)=>n[s][r]??s,t)}var ex="ScrollArea",[pv]=po(ex),[TI,er]=pv(ex),xv=c.forwardRef((t,n)=>{const{__scopeScrollArea:s,type:r="hover",dir:a,scrollHideDelay:o=600,...i}=t,[l,u]=c.useState(null),[d,m]=c.useState(null),[p,x]=c.useState(null),[f,h]=c.useState(null),[j,b]=c.useState(null),[g,y]=c.useState(0),[v,_]=c.useState(0),[E,S]=c.useState(!1),[M,B]=c.useState(!1),k=As(n,$=>u($)),L=hp(a);return e.jsx(TI,{scope:s,type:r,dir:L,scrollHideDelay:o,scrollArea:l,viewport:d,onViewportChange:m,content:p,onContentChange:x,scrollbarX:f,onScrollbarXChange:h,scrollbarXEnabled:E,onScrollbarXEnabledChange:S,scrollbarY:j,onScrollbarYChange:b,scrollbarYEnabled:M,onScrollbarYEnabledChange:B,onCornerWidthChange:y,onCornerHeightChange:_,children:e.jsx(Lt.div,{dir:L,...i,ref:k,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":v+"px",...t.style}})})});xv.displayName=ex;var fv="ScrollAreaViewport",hv=c.forwardRef((t,n)=>{const{__scopeScrollArea:s,children:r,nonce:a,...o}=t,i=er(fv,s),l=c.useRef(null),u=As(n,l,i.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:a}),e.jsx(Lt.div,{"data-radix-scroll-area-viewport":"",...o,ref:u,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...t.style},children:e.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});hv.displayName=fv;var Mr="ScrollAreaScrollbar",gv=c.forwardRef((t,n)=>{const{forceMount:s,...r}=t,a=er(Mr,t.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:i}=a,l=t.orientation==="horizontal";return c.useEffect(()=>(l?o(!0):i(!0),()=>{l?o(!1):i(!1)}),[l,o,i]),a.type==="hover"?e.jsx(RI,{...r,ref:n,forceMount:s}):a.type==="scroll"?e.jsx(PI,{...r,ref:n,forceMount:s}):a.type==="auto"?e.jsx(bv,{...r,ref:n,forceMount:s}):a.type==="always"?e.jsx(tx,{...r,ref:n}):null});gv.displayName=Mr;var RI=c.forwardRef((t,n)=>{const{forceMount:s,...r}=t,a=er(Mr,t.__scopeScrollArea),[o,i]=c.useState(!1);return c.useEffect(()=>{const l=a.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),i(!0)},m=()=>{u=window.setTimeout(()=>i(!1),a.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",m),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",m)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(ur,{present:s||o,children:e.jsx(bv,{"data-state":o?"visible":"hidden",...r,ref:n})})}),PI=c.forwardRef((t,n)=>{const{forceMount:s,...r}=t,a=er(Mr,t.__scopeScrollArea),o=t.orientation==="horizontal",i=Od(()=>u("SCROLL_END"),100),[l,u]=EI("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return c.useEffect(()=>{if(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,a.scrollHideDelay,u]),c.useEffect(()=>{const d=a.viewport,m=o?"scrollLeft":"scrollTop";if(d){let p=d[m];const x=()=>{const f=d[m];p!==f&&(u("SCROLL"),i()),p=f};return d.addEventListener("scroll",x),()=>d.removeEventListener("scroll",x)}},[a.viewport,o,u,i]),e.jsx(ur,{present:s||l!=="hidden",children:e.jsx(tx,{"data-state":l==="hidden"?"hidden":"visible",...r,ref:n,onPointerEnter:kt(t.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:kt(t.onPointerLeave,()=>u("POINTER_LEAVE"))})})}),bv=c.forwardRef((t,n)=>{const s=er(Mr,t.__scopeScrollArea),{forceMount:r,...a}=t,[o,i]=c.useState(!1),l=t.orientation==="horizontal",u=Od(()=>{if(s.viewport){const d=s.viewport.offsetWidth<s.viewport.scrollWidth,m=s.viewport.offsetHeight<s.viewport.scrollHeight;i(l?d:m)}},10);return ni(s.viewport,u),ni(s.content,u),e.jsx(ur,{present:r||o,children:e.jsx(tx,{"data-state":o?"visible":"hidden",...a,ref:n})})}),tx=c.forwardRef((t,n)=>{const{orientation:s="vertical",...r}=t,a=er(Mr,t.__scopeScrollArea),o=c.useRef(null),i=c.useRef(0),[l,u]=c.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Nv(l.viewport,l.content),m={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:x=>o.current=x,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:x=>i.current=x};function p(x,f){return FI(x,i.current,l,f)}return s==="horizontal"?e.jsx(MI,{...m,ref:n,onThumbPositionChange:()=>{if(a.viewport&&o.current){const x=a.viewport.scrollLeft,f=If(x,l,a.dir);o.current.style.transform=`translate3d(${f}px, 0, 0)`}},onWheelScroll:x=>{a.viewport&&(a.viewport.scrollLeft=x)},onDragScroll:x=>{a.viewport&&(a.viewport.scrollLeft=p(x,a.dir))}}):s==="vertical"?e.jsx($I,{...m,ref:n,onThumbPositionChange:()=>{if(a.viewport&&o.current){const x=a.viewport.scrollTop,f=If(x,l);o.current.style.transform=`translate3d(0, ${f}px, 0)`}},onWheelScroll:x=>{a.viewport&&(a.viewport.scrollTop=x)},onDragScroll:x=>{a.viewport&&(a.viewport.scrollTop=p(x))}}):null}),MI=c.forwardRef((t,n)=>{const{sizes:s,onSizesChange:r,...a}=t,o=er(Mr,t.__scopeScrollArea),[i,l]=c.useState(),u=c.useRef(null),d=As(n,u,o.onScrollbarXChange);return c.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),e.jsx(vv,{"data-orientation":"horizontal",...a,ref:d,sizes:s,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Dd(s)+"px",...t.style},onThumbPointerDown:m=>t.onThumbPointerDown(m.x),onDragScroll:m=>t.onDragScroll(m.x),onWheelScroll:(m,p)=>{if(o.viewport){const x=o.viewport.scrollLeft+m.deltaX;t.onWheelScroll(x),Cv(x,p)&&m.preventDefault()}},onResize:()=>{u.current&&o.viewport&&i&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Ec(i.paddingLeft),paddingEnd:Ec(i.paddingRight)}})}})}),$I=c.forwardRef((t,n)=>{const{sizes:s,onSizesChange:r,...a}=t,o=er(Mr,t.__scopeScrollArea),[i,l]=c.useState(),u=c.useRef(null),d=As(n,u,o.onScrollbarYChange);return c.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),e.jsx(vv,{"data-orientation":"vertical",...a,ref:d,sizes:s,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Dd(s)+"px",...t.style},onThumbPointerDown:m=>t.onThumbPointerDown(m.y),onDragScroll:m=>t.onDragScroll(m.y),onWheelScroll:(m,p)=>{if(o.viewport){const x=o.viewport.scrollTop+m.deltaY;t.onWheelScroll(x),Cv(x,p)&&m.preventDefault()}},onResize:()=>{u.current&&o.viewport&&i&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Ec(i.paddingTop),paddingEnd:Ec(i.paddingBottom)}})}})}),[DI,yv]=pv(Mr),vv=c.forwardRef((t,n)=>{const{__scopeScrollArea:s,sizes:r,hasThumb:a,onThumbChange:o,onThumbPointerUp:i,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:m,onResize:p,...x}=t,f=er(Mr,s),[h,j]=c.useState(null),b=As(n,k=>j(k)),g=c.useRef(null),y=c.useRef(""),v=f.viewport,_=r.content-r.viewport,E=br(m),S=br(u),M=Od(p,10);function B(k){if(g.current){const L=k.clientX-g.current.left,$=k.clientY-g.current.top;d({x:L,y:$})}}return c.useEffect(()=>{const k=L=>{const $=L.target;(h==null?void 0:h.contains($))&&E(L,_)};return document.addEventListener("wheel",k,{passive:!1}),()=>document.removeEventListener("wheel",k,{passive:!1})},[v,h,_,E]),c.useEffect(S,[r,S]),ni(h,M),ni(f.content,M),e.jsx(DI,{scope:s,scrollbar:h,hasThumb:a,onThumbChange:br(o),onThumbPointerUp:br(i),onThumbPositionChange:S,onThumbPointerDown:br(l),children:e.jsx(Lt.div,{...x,ref:b,style:{position:"absolute",...x.style},onPointerDown:kt(t.onPointerDown,k=>{k.button===0&&(k.target.setPointerCapture(k.pointerId),g.current=h.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",f.viewport&&(f.viewport.style.scrollBehavior="auto"),B(k))}),onPointerMove:kt(t.onPointerMove,B),onPointerUp:kt(t.onPointerUp,k=>{const L=k.target;L.hasPointerCapture(k.pointerId)&&L.releasePointerCapture(k.pointerId),document.body.style.webkitUserSelect=y.current,f.viewport&&(f.viewport.style.scrollBehavior=""),g.current=null})})})}),Ac="ScrollAreaThumb",jv=c.forwardRef((t,n)=>{const{forceMount:s,...r}=t,a=yv(Ac,t.__scopeScrollArea);return e.jsx(ur,{present:s||a.hasThumb,children:e.jsx(OI,{ref:n,...r})})}),OI=c.forwardRef((t,n)=>{const{__scopeScrollArea:s,style:r,...a}=t,o=er(Ac,s),i=yv(Ac,s),{onThumbPositionChange:l}=i,u=As(n,p=>i.onThumbChange(p)),d=c.useRef(void 0),m=Od(()=>{d.current&&(d.current(),d.current=void 0)},100);return c.useEffect(()=>{const p=o.viewport;if(p){const x=()=>{if(m(),!d.current){const f=qI(p,l);d.current=f,l()}};return l(),p.addEventListener("scroll",x),()=>p.removeEventListener("scroll",x)}},[o.viewport,m,l]),e.jsx(Lt.div,{"data-state":i.hasThumb?"visible":"hidden",...a,ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:kt(t.onPointerDownCapture,p=>{const f=p.target.getBoundingClientRect(),h=p.clientX-f.left,j=p.clientY-f.top;i.onThumbPointerDown({x:h,y:j})}),onPointerUp:kt(t.onPointerUp,i.onThumbPointerUp)})});jv.displayName=Ac;var nx="ScrollAreaCorner",wv=c.forwardRef((t,n)=>{const s=er(nx,t.__scopeScrollArea),r=!!(s.scrollbarX&&s.scrollbarY);return s.type!=="scroll"&&r?e.jsx(LI,{...t,ref:n}):null});wv.displayName=nx;var LI=c.forwardRef((t,n)=>{const{__scopeScrollArea:s,...r}=t,a=er(nx,s),[o,i]=c.useState(0),[l,u]=c.useState(0),d=!!(o&&l);return ni(a.scrollbarX,()=>{var p;const m=((p=a.scrollbarX)==null?void 0:p.offsetHeight)||0;a.onCornerHeightChange(m),u(m)}),ni(a.scrollbarY,()=>{var p;const m=((p=a.scrollbarY)==null?void 0:p.offsetWidth)||0;a.onCornerWidthChange(m),i(m)}),d?e.jsx(Lt.div,{...r,ref:n,style:{width:o,height:l,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null});function Ec(t){return t?parseInt(t,10):0}function Nv(t,n){const s=t/n;return isNaN(s)?0:s}function Dd(t){const n=Nv(t.viewport,t.content),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,r=(t.scrollbar.size-s)*n;return Math.max(r,18)}function FI(t,n,s,r="ltr"){const a=Dd(s),o=a/2,i=n||o,l=a-i,u=s.scrollbar.paddingStart+i,d=s.scrollbar.size-s.scrollbar.paddingEnd-l,m=s.content-s.viewport,p=r==="ltr"?[0,m]:[m*-1,0];return kv([u,d],p)(t)}function If(t,n,s="ltr"){const r=Dd(n),a=n.scrollbar.paddingStart+n.scrollbar.paddingEnd,o=n.scrollbar.size-a,i=n.content-n.viewport,l=o-r,u=s==="ltr"?[0,i]:[i*-1,0],d=Dk(t,u);return kv([0,i],[0,l])(d)}function kv(t,n){return s=>{if(t[0]===t[1]||n[0]===n[1])return n[0];const r=(n[1]-n[0])/(t[1]-t[0]);return n[0]+r*(s-t[0])}}function Cv(t,n){return t>0&&t<n}var qI=(t,n=()=>{})=>{let s={left:t.scrollLeft,top:t.scrollTop},r=0;return(function a(){const o={left:t.scrollLeft,top:t.scrollTop},i=s.left!==o.left,l=s.top!==o.top;(i||l)&&n(),s=o,r=window.requestAnimationFrame(a)})(),()=>window.cancelAnimationFrame(r)};function Od(t,n){const s=br(t),r=c.useRef(0);return c.useEffect(()=>()=>window.clearTimeout(r.current),[]),c.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(s,n)},[s,n])}function ni(t,n){const s=br(n);Yi(()=>{let r=0;if(t){const a=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(s)});return a.observe(t),()=>{window.cancelAnimationFrame(r),a.unobserve(t)}}},[t,s])}var UI=xv,BI=hv,KI=wv,Ld="Tabs",[zI]=po(Ld,[wd]),Sv=wd(),[WI,sx]=zI(Ld),Iv=c.forwardRef((t,n)=>{const{__scopeTabs:s,value:r,onValueChange:a,defaultValue:o,orientation:i="horizontal",dir:l,activationMode:u="automatic",...d}=t,m=hp(l),[p,x]=jd({prop:r,onChange:a,defaultProp:o??"",caller:Ld});return e.jsx(WI,{scope:s,baseId:jr(),value:p,onValueChange:x,orientation:i,dir:m,activationMode:u,children:e.jsx(Lt.div,{dir:m,"data-orientation":i,...d,ref:n})})});Iv.displayName=Ld;var _v="TabsList",Av=c.forwardRef((t,n)=>{const{__scopeTabs:s,loop:r=!0,...a}=t,o=sx(_v,s),i=Sv(s);return e.jsx(Db,{asChild:!0,...i,orientation:o.orientation,dir:o.dir,loop:r,children:e.jsx(Lt.div,{role:"tablist","aria-orientation":o.orientation,...a,ref:n})})});Av.displayName=_v;var Ev="TabsTrigger",Tv=c.forwardRef((t,n)=>{const{__scopeTabs:s,value:r,disabled:a=!1,...o}=t,i=sx(Ev,s),l=Sv(s),u=Mv(i.baseId,r),d=$v(i.baseId,r),m=r===i.value;return e.jsx($b,{asChild:!0,...l,focusable:!a,active:m,children:e.jsx(Lt.button,{type:"button",role:"tab","aria-selected":m,"aria-controls":d,"data-state":m?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:u,...o,ref:n,onMouseDown:kt(t.onMouseDown,p=>{!a&&p.button===0&&p.ctrlKey===!1?i.onValueChange(r):p.preventDefault()}),onKeyDown:kt(t.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&i.onValueChange(r)}),onFocus:kt(t.onFocus,()=>{const p=i.activationMode!=="manual";!m&&!a&&p&&i.onValueChange(r)})})})});Tv.displayName=Ev;var Rv="TabsContent",Pv=c.forwardRef((t,n)=>{const{__scopeTabs:s,value:r,forceMount:a,children:o,...i}=t,l=sx(Rv,s),u=Mv(l.baseId,r),d=$v(l.baseId,r),m=r===l.value,p=c.useRef(m);return c.useEffect(()=>{const x=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(x)},[]),e.jsx(ur,{present:a||m,children:({present:x})=>e.jsx(Lt.div,{"data-state":m?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!x,id:d,tabIndex:0,...i,ref:n,style:{...t.style,animationDuration:p.current?"0s":void 0},children:x&&o})})});Pv.displayName=Rv;function Mv(t,n){return`${t}-trigger-${n}`}function $v(t,n){return`${t}-content-${n}`}var HI=Iv,VI=Av,QI=Tv,GI=Pv;const JI=["active","paused","archived"],ZI=["local_trusted","authenticated"],YI=["private","public"],XI=["auto","explicit"],e2=["active","paused","idle","running","error","pending_approval","terminated"],_l=["process","http","claude_local","codex_local","gemini_local","opencode_local","pi_local","cursor","openclaw_gateway","hermes_local"],Dv=["ceo","cto","cmo","cfo","engineer","designer","pm","qa","devops","researcher","general"],rx={ceo:"CEO",cto:"CTO",cmo:"CMO",cfo:"CFO",engineer:"Engineer",designer:"Designer",pm:"PM",qa:"QA",devops:"DevOps",researcher:"Researcher",general:"General"},ax=["bot","cpu","brain","zap","rocket","code","terminal","shield","eye","search","wrench","hammer","lightbulb","sparkles","star","heart","flame","bug","cog","database","globe","lock","mail","message-square","file-code","git-branch","package","puzzle","target","wand","atom","circuit-board","radar","swords","telescope","microscope","crown","gem","hexagon","pentagon","fingerprint"],Ov=["backlog","todo","in_progress","in_review","done","blocked","cancelled"],t2=["backlog","todo","in_progress","in_review","blocked","done"],km=t2.join(","),Lv=["critical","high","medium","low"],ox=["company","team","agent","task"],ix=["planned","active","achieved","cancelled"],n2=["backlog","planned","in_progress","completed","cancelled"],s2=["active","paused","archived"],r2=["coalesce_if_active","always_enqueue","skip_if_active"],a2=["skip_missed","enqueue_missed_with_cap"],Fv=["bearer","hmac_sha256"],Cm=["#6366f1","#8b5cf6","#ec4899","#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#06b6d4","#3b82f6"],o2=["hire_agent","approve_ceo_strategy","budget_override_required"],qv=["local_encrypted","aws_secrets_manager","gcp_secret_manager","vault"],i2=["local_disk","s3"],l2=["metered_api","subscription_included","subscription_overage","credits","fixed","unknown"],c2=["inference_charge","platform_fee","credit_purchase","credit_refund","credit_expiry","byok_fee","gateway_overhead","log_storage_charge","logpush_charge","provisioned_capacity_charge","training_charge","custom_model_import_charge","custom_model_storage_charge","manual_adjustment"],d2=["debit","credit"],u2=["input_token","output_token","cached_input_token","request","credit_usd","credit_unit","model_unit_minute","model_unit_hour","gb_month","train_token","unknown"],m2=["company","agent","project"],p2=["billed_cents"],x2=["calendar_month_utc","lifetime"],f2=["keep_paused","raise_budget_and_resume"],h2=["human","agent","both"],Uv=["human","agent"],g2=["pending_approval","approved","rejected"],b2=["agents:create","users:invite","users:manage_permissions","tasks:assign","tasks:assign_scope","joins:approve"],y2=["installed","ready","disabled","error","upgrade_pending","uninstalled"],v2=["connector","workspace","automation","ui"],j2=["companies.read","projects.read","project.workspaces.read","issues.read","issue.comments.read","issue.documents.read","agents.read","goals.read","goals.create","goals.update","activity.read","costs.read","issues.create","issues.update","issue.comments.create","issue.documents.write","agents.pause","agents.resume","agents.invoke","agent.sessions.create","agent.sessions.list","agent.sessions.send","agent.sessions.close","activity.log.write","metrics.write","plugin.state.read","plugin.state.write","events.subscribe","events.emit","jobs.schedule","webhooks.receive","http.outbound","secrets.read-ref","agent.tools.register","instance.settings.register","ui.sidebar.register","ui.page.register","ui.detailTab.register","ui.dashboardWidget.register","ui.commentAnnotation.register","ui.action.register"],w2=["page","detailTab","taskDetailView","dashboardWidget","sidebar","sidebarPanel","projectSidebarItem","globalToolbarButton","toolbarButton","contextMenuItem","commentAnnotation","commentContextMenuItem","settingsPage"],N2=["dashboard","onboarding","companies","company","settings","plugins","org","agents","projects","issues","goals","approvals","costs","activity","inbox","design-guide","tests"],k2=["page","detailTab","taskDetailView","dashboardWidget","sidebar","sidebarPanel","projectSidebarItem","globalToolbarButton","toolbarButton","contextMenuItem","commentAnnotation","commentContextMenuItem","settingsPage"],C2=["navigate","openModal","openDrawer","openPopover","performAction","deepLink"],Bv=["inline","compact","default","wide","full"],S2=["hostInline","hostOverlay","hostRoute","external","iframe"],Kv=["project","issue","agent","goal","run","comment"],lx=["instance","company","project","project_workspace","agent","issue","goal","run"];var $t;(function(t){t.assertEqual=a=>{};function n(a){}t.assertIs=n;function s(a){throw new Error}t.assertNever=s,t.arrayToEnum=a=>{const o={};for(const i of a)o[i]=i;return o},t.getValidEnumValues=a=>{const o=t.objectKeys(a).filter(l=>typeof a[a[l]]!="number"),i={};for(const l of o)i[l]=a[l];return t.objectValues(i)},t.objectValues=a=>t.objectKeys(a).map(function(o){return a[o]}),t.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const o=[];for(const i in a)Object.prototype.hasOwnProperty.call(a,i)&&o.push(i);return o},t.find=(a,o)=>{for(const i of a)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function r(a,o=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(a,o)=>typeof o=="bigint"?o.toString():o})($t||($t={}));var _f;(function(t){t.mergeShapes=(n,s)=>({...n,...s})})(_f||(_f={}));const Qe=$t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ia=t=>{switch(typeof t){case"undefined":return Qe.undefined;case"string":return Qe.string;case"number":return Number.isNaN(t)?Qe.nan:Qe.number;case"boolean":return Qe.boolean;case"function":return Qe.function;case"bigint":return Qe.bigint;case"symbol":return Qe.symbol;case"object":return Array.isArray(t)?Qe.array:t===null?Qe.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Qe.promise:typeof Map<"u"&&t instanceof Map?Qe.map:typeof Set<"u"&&t instanceof Set?Qe.set:typeof Date<"u"&&t instanceof Date?Qe.date:Qe.object;default:return Qe.unknown}},ve=$t.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Hr extends Error{get errors(){return this.issues}constructor(n){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=n}format(n){const s=n||function(o){return o.message},r={_errors:[]},a=o=>{for(const i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)r._errors.push(s(i));else{let l=r,u=0;for(;u<i.path.length;){const d=i.path[u];u===i.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(s(i))):l[d]=l[d]||{_errors:[]},l=l[d],u++}}};return a(this),r}static assert(n){if(!(n instanceof Hr))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$t.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=s=>s.message){const s={},r=[];for(const a of this.issues)if(a.path.length>0){const o=a.path[0];s[o]=s[o]||[],s[o].push(n(a))}else r.push(n(a));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}Hr.create=t=>new Hr(t);const Sm=(t,n)=>{let s;switch(t.code){case ve.invalid_type:t.received===Qe.undefined?s="Required":s=`Expected ${t.expected}, received ${t.received}`;break;case ve.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,$t.jsonStringifyReplacer)}`;break;case ve.unrecognized_keys:s=`Unrecognized key(s) in object: ${$t.joinValues(t.keys,", ")}`;break;case ve.invalid_union:s="Invalid input";break;case ve.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${$t.joinValues(t.options)}`;break;case ve.invalid_enum_value:s=`Invalid enum value. Expected ${$t.joinValues(t.options)}, received '${t.received}'`;break;case ve.invalid_arguments:s="Invalid function arguments";break;case ve.invalid_return_type:s="Invalid function return type";break;case ve.invalid_date:s="Invalid date";break;case ve.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?s=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?s=`Invalid input: must end with "${t.validation.endsWith}"`:$t.assertNever(t.validation):t.validation!=="regex"?s=`Invalid ${t.validation}`:s="Invalid";break;case ve.too_small:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:s="Invalid input";break;case ve.too_big:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:s="Invalid input";break;case ve.custom:s="Invalid input";break;case ve.invalid_intersection_types:s="Intersection results could not be merged";break;case ve.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case ve.not_finite:s="Number must be finite";break;default:s=n.defaultError,$t.assertNever(t)}return{message:s}};let I2=Sm;function _2(){return I2}const A2=t=>{const{data:n,path:s,errorMaps:r,issueData:a}=t,o=[...s,...a.path||[]],i={...a,path:o};if(a.message!==void 0)return{...a,path:o,message:a.message};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(i,{data:n,defaultError:l}).message;return{...a,path:o,message:l}};function ze(t,n){const s=_2(),r=A2({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===Sm?void 0:Sm].filter(a=>!!a)});t.common.issues.push(r)}class fs{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(n,s){const r=[];for(const a of s){if(a.status==="aborted")return dt;a.status==="dirty"&&n.dirty(),r.push(a.value)}return{status:n.value,value:r}}static async mergeObjectAsync(n,s){const r=[];for(const a of s){const o=await a.key,i=await a.value;r.push({key:o,value:i})}return fs.mergeObjectSync(n,r)}static mergeObjectSync(n,s){const r={};for(const a of s){const{key:o,value:i}=a;if(o.status==="aborted"||i.status==="aborted")return dt;o.status==="dirty"&&n.dirty(),i.status==="dirty"&&n.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(r[o.value]=i.value)}return{status:n.value,value:r}}}const dt=Object.freeze({status:"aborted"}),Oi=t=>({status:"dirty",value:t}),tr=t=>({status:"valid",value:t}),Af=t=>t.status==="aborted",Ef=t=>t.status==="dirty",si=t=>t.status==="valid",Tc=t=>typeof Promise<"u"&&t instanceof Promise;var Ye;(function(t){t.errToObj=n=>typeof n=="string"?{message:n}:n||{},t.toString=n=>typeof n=="string"?n:n==null?void 0:n.message})(Ye||(Ye={}));class Ar{constructor(n,s,r,a){this._cachedPath=[],this.parent=n,this.data=s,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Tf=(t,n)=>{if(si(n))return{success:!0,data:n.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new Hr(t.common.issues);return this._error=s,this._error}}};function jt(t){if(!t)return{};const{errorMap:n,invalid_type_error:s,required_error:r,description:a}=t;if(n&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return n?{errorMap:n,description:a}:{errorMap:(i,l)=>{const{message:u}=t;return i.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:i.code!=="invalid_type"?{message:l.defaultError}:{message:u??s??l.defaultError}},description:a}}class Tt{get description(){return this._def.description}_getType(n){return ia(n.data)}_getOrReturnCtx(n,s){return s||{common:n.parent.common,data:n.data,parsedType:ia(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new fs,ctx:{common:n.parent.common,data:n.data,parsedType:ia(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){const s=this._parse(n);if(Tc(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(n){const s=this._parse(n);return Promise.resolve(s)}parse(n,s){const r=this.safeParse(n,s);if(r.success)return r.data;throw r.error}safeParse(n,s){const r={common:{issues:[],async:(s==null?void 0:s.async)??!1,contextualErrorMap:s==null?void 0:s.errorMap},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:ia(n)},a=this._parseSync({data:n,path:r.path,parent:r});return Tf(r,a)}"~validate"(n){var r,a;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:ia(n)};if(!this["~standard"].async)try{const o=this._parseSync({data:n,path:[],parent:s});return si(o)?{value:o.value}:{issues:s.common.issues}}catch(o){(a=(r=o==null?void 0:o.message)==null?void 0:r.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:n,path:[],parent:s}).then(o=>si(o)?{value:o.value}:{issues:s.common.issues})}async parseAsync(n,s){const r=await this.safeParseAsync(n,s);if(r.success)return r.data;throw r.error}async safeParseAsync(n,s){const r={common:{issues:[],contextualErrorMap:s==null?void 0:s.errorMap,async:!0},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:ia(n)},a=this._parse({data:n,path:r.path,parent:r}),o=await(Tc(a)?a:Promise.resolve(a));return Tf(r,o)}refine(n,s){const r=a=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(a):s;return this._refinement((a,o)=>{const i=n(a),l=()=>o.addIssue({code:ve.custom,...r(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(l(),!1)):i?!0:(l(),!1)})}refinement(n,s){return this._refinement((r,a)=>n(r)?!0:(a.addIssue(typeof s=="function"?s(r,a):s),!1))}_refinement(n){return new wa({schema:this,typeName:ut.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}constructor(n){this.spa=this.safeParseAsync,this._def=n,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return Br.create(this,this._def)}nullable(){return no.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nr.create(this)}promise(){return Oc.create(this,this._def)}or(n){return Pc.create([this,n],this._def)}and(n){return Mc.create(this,n,this._def)}transform(n){return new wa({...jt(this._def),schema:this,typeName:ut.ZodEffects,effect:{type:"transform",transform:n}})}default(n){const s=typeof n=="function"?n:()=>n;return new Lc({...jt(this._def),innerType:this,defaultValue:s,typeName:ut.ZodDefault})}brand(){return new Vv({typeName:ut.ZodBranded,type:this,...jt(this._def)})}catch(n){const s=typeof n=="function"?n:()=>n;return new Fc({...jt(this._def),innerType:this,catchValue:s,typeName:ut.ZodCatch})}describe(n){const s=this.constructor;return new s({...this._def,description:n})}pipe(n){return dx.create(this,n)}readonly(){return qc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const E2=/^c[^\s-]{8,}$/i,T2=/^[0-9a-z]+$/,R2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,P2=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,M2=/^[a-z0-9_-]{21}$/i,$2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,D2=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,O2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let du;const F2=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,q2=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,U2=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,B2=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,K2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zv="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",W2=new RegExp(`^${zv}$`);function Wv(t){let n="[0-5]\\d";t.precision?n=`${n}\\.\\d{${t.precision}}`:t.precision==null&&(n=`${n}(\\.\\d+)?`);const s=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${s}`}function H2(t){return new RegExp(`^${Wv(t)}$`)}function V2(t){let n=`${zv}T${Wv(t)}`;const s=[];return s.push(t.local?"Z?":"Z"),t.offset&&s.push("([+-]\\d{2}:?\\d{2})"),n=`${n}(${s.join("|")})`,new RegExp(`^${n}$`)}function Q2(t,n){return!!((n==="v4"||!n)&&F2.test(t)||(n==="v6"||!n)&&U2.test(t))}function G2(t,n){if(!$2.test(t))return!1;try{const[s]=t.split(".");if(!s)return!1;const r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),a=JSON.parse(atob(r));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||n&&a.alg!==n)}catch{return!1}}function J2(t,n){return!!((n==="v4"||!n)&&q2.test(t)||(n==="v6"||!n)&&B2.test(t))}class vr extends Tt{_parse(n){if(this._def.coerce&&(n.data=String(n.data)),this._getType(n)!==Qe.string){const o=this._getOrReturnCtx(n);return ze(o,{code:ve.invalid_type,expected:Qe.string,received:o.parsedType}),dt}const r=new fs;let a;for(const o of this._def.checks)if(o.kind==="min")n.data.length<o.value&&(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")n.data.length>o.value&&(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const i=n.data.length>o.value,l=n.data.length<o.value;(i||l)&&(a=this._getOrReturnCtx(n,a),i?ze(a,{code:ve.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):l&&ze(a,{code:ve.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")O2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"email",code:ve.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")du||(du=new RegExp(L2,"u")),du.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"emoji",code:ve.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")P2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"uuid",code:ve.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")M2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"nanoid",code:ve.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")E2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"cuid",code:ve.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")T2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"cuid2",code:ve.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")R2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"ulid",code:ve.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(n.data)}catch{a=this._getOrReturnCtx(n,a),ze(a,{validation:"url",code:ve.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"regex",code:ve.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?n.data=n.data.trim():o.kind==="includes"?n.data.includes(o.value,o.position)||(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?n.data=n.data.toLowerCase():o.kind==="toUpperCase"?n.data=n.data.toUpperCase():o.kind==="startsWith"?n.data.startsWith(o.value)||(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?n.data.endsWith(o.value)||(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?V2(o).test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?W2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?H2(o).test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?D2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"duration",code:ve.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Q2(n.data,o.version)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"ip",code:ve.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?G2(n.data,o.alg)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"jwt",code:ve.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?J2(n.data,o.version)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"cidr",code:ve.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?K2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"base64",code:ve.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?z2.test(n.data)||(a=this._getOrReturnCtx(n,a),ze(a,{validation:"base64url",code:ve.invalid_string,message:o.message}),r.dirty()):$t.assertNever(o);return{status:r.value,value:n.data}}_regex(n,s,r){return this.refinement(a=>n.test(a),{validation:s,code:ve.invalid_string,...Ye.errToObj(r)})}_addCheck(n){return new vr({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...Ye.errToObj(n)})}url(n){return this._addCheck({kind:"url",...Ye.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...Ye.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...Ye.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...Ye.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...Ye.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...Ye.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...Ye.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...Ye.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...Ye.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...Ye.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...Ye.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...Ye.errToObj(n)})}datetime(n){return typeof n=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n}):this._addCheck({kind:"datetime",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,offset:(n==null?void 0:n.offset)??!1,local:(n==null?void 0:n.local)??!1,...Ye.errToObj(n==null?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){return typeof n=="string"?this._addCheck({kind:"time",precision:null,message:n}):this._addCheck({kind:"time",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,...Ye.errToObj(n==null?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...Ye.errToObj(n)})}regex(n,s){return this._addCheck({kind:"regex",regex:n,...Ye.errToObj(s)})}includes(n,s){return this._addCheck({kind:"includes",value:n,position:s==null?void 0:s.position,...Ye.errToObj(s==null?void 0:s.message)})}startsWith(n,s){return this._addCheck({kind:"startsWith",value:n,...Ye.errToObj(s)})}endsWith(n,s){return this._addCheck({kind:"endsWith",value:n,...Ye.errToObj(s)})}min(n,s){return this._addCheck({kind:"min",value:n,...Ye.errToObj(s)})}max(n,s){return this._addCheck({kind:"max",value:n,...Ye.errToObj(s)})}length(n,s){return this._addCheck({kind:"length",value:n,...Ye.errToObj(s)})}nonempty(n){return this.min(1,Ye.errToObj(n))}trim(){return new vr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new vr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new vr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(n=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find(n=>n.kind==="date")}get isTime(){return!!this._def.checks.find(n=>n.kind==="time")}get isDuration(){return!!this._def.checks.find(n=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find(n=>n.kind==="email")}get isURL(){return!!this._def.checks.find(n=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find(n=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find(n=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(n=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(n=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(n=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find(n=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find(n=>n.kind==="ip")}get isCIDR(){return!!this._def.checks.find(n=>n.kind==="cidr")}get isBase64(){return!!this._def.checks.find(n=>n.kind==="base64")}get isBase64url(){return!!this._def.checks.find(n=>n.kind==="base64url")}get minLength(){let n=null;for(const s of this._def.checks)s.kind==="min"&&(n===null||s.value>n)&&(n=s.value);return n}get maxLength(){let n=null;for(const s of this._def.checks)s.kind==="max"&&(n===null||s.value<n)&&(n=s.value);return n}}vr.create=t=>new vr({checks:[],typeName:ut.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...jt(t)});function Z2(t,n){const s=(t.toString().split(".")[1]||"").length,r=(n.toString().split(".")[1]||"").length,a=s>r?s:r,o=Number.parseInt(t.toFixed(a).replace(".","")),i=Number.parseInt(n.toFixed(a).replace(".",""));return o%i/10**a}class Ya extends Tt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce&&(n.data=Number(n.data)),this._getType(n)!==Qe.number){const o=this._getOrReturnCtx(n);return ze(o,{code:ve.invalid_type,expected:Qe.number,received:o.parsedType}),dt}let r;const a=new fs;for(const o of this._def.checks)o.kind==="int"?$t.isInteger(n.data)||(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.invalid_type,expected:"integer",received:"float",message:o.message}),a.dirty()):o.kind==="min"?(o.inclusive?n.data<o.value:n.data<=o.value)&&(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?n.data>o.value:n.data>=o.value)&&(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty()):o.kind==="multipleOf"?Z2(n.data,o.value)!==0&&(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):o.kind==="finite"?Number.isFinite(n.data)||(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.not_finite,message:o.message}),a.dirty()):$t.assertNever(o);return{status:a.value,value:n.data}}gte(n,s){return this.setLimit("min",n,!0,Ye.toString(s))}gt(n,s){return this.setLimit("min",n,!1,Ye.toString(s))}lte(n,s){return this.setLimit("max",n,!0,Ye.toString(s))}lt(n,s){return this.setLimit("max",n,!1,Ye.toString(s))}setLimit(n,s,r,a){return new Ya({...this._def,checks:[...this._def.checks,{kind:n,value:s,inclusive:r,message:Ye.toString(a)}]})}_addCheck(n){return new Ya({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:Ye.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ye.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ye.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ye.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ye.toString(n)})}multipleOf(n,s){return this._addCheck({kind:"multipleOf",value:n,message:Ye.toString(s)})}finite(n){return this._addCheck({kind:"finite",message:Ye.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ye.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ye.toString(n)})}get minValue(){let n=null;for(const s of this._def.checks)s.kind==="min"&&(n===null||s.value>n)&&(n=s.value);return n}get maxValue(){let n=null;for(const s of this._def.checks)s.kind==="max"&&(n===null||s.value<n)&&(n=s.value);return n}get isInt(){return!!this._def.checks.find(n=>n.kind==="int"||n.kind==="multipleOf"&&$t.isInteger(n.value))}get isFinite(){let n=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(n===null||r.value<n)&&(n=r.value)}return Number.isFinite(s)&&Number.isFinite(n)}}Ya.create=t=>new Ya({checks:[],typeName:ut.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...jt(t)});class Xa extends Tt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)try{n.data=BigInt(n.data)}catch{return this._getInvalidInput(n)}if(this._getType(n)!==Qe.bigint)return this._getInvalidInput(n);let r;const a=new fs;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?n.data<o.value:n.data<=o.value)&&(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?n.data>o.value:n.data>=o.value)&&(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="multipleOf"?n.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(n,r),ze(r,{code:ve.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):$t.assertNever(o);return{status:a.value,value:n.data}}_getInvalidInput(n){const s=this._getOrReturnCtx(n);return ze(s,{code:ve.invalid_type,expected:Qe.bigint,received:s.parsedType}),dt}gte(n,s){return this.setLimit("min",n,!0,Ye.toString(s))}gt(n,s){return this.setLimit("min",n,!1,Ye.toString(s))}lte(n,s){return this.setLimit("max",n,!0,Ye.toString(s))}lt(n,s){return this.setLimit("max",n,!1,Ye.toString(s))}setLimit(n,s,r,a){return new Xa({...this._def,checks:[...this._def.checks,{kind:n,value:s,inclusive:r,message:Ye.toString(a)}]})}_addCheck(n){return new Xa({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ye.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ye.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ye.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ye.toString(n)})}multipleOf(n,s){return this._addCheck({kind:"multipleOf",value:n,message:Ye.toString(s)})}get minValue(){let n=null;for(const s of this._def.checks)s.kind==="min"&&(n===null||s.value>n)&&(n=s.value);return n}get maxValue(){let n=null;for(const s of this._def.checks)s.kind==="max"&&(n===null||s.value<n)&&(n=s.value);return n}}Xa.create=t=>new Xa({checks:[],typeName:ut.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...jt(t)});class Rc extends Tt{_parse(n){if(this._def.coerce&&(n.data=!!n.data),this._getType(n)!==Qe.boolean){const r=this._getOrReturnCtx(n);return ze(r,{code:ve.invalid_type,expected:Qe.boolean,received:r.parsedType}),dt}return tr(n.data)}}Rc.create=t=>new Rc({typeName:ut.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...jt(t)});class ri extends Tt{_parse(n){if(this._def.coerce&&(n.data=new Date(n.data)),this._getType(n)!==Qe.date){const o=this._getOrReturnCtx(n);return ze(o,{code:ve.invalid_type,expected:Qe.date,received:o.parsedType}),dt}if(Number.isNaN(n.data.getTime())){const o=this._getOrReturnCtx(n);return ze(o,{code:ve.invalid_date}),dt}const r=new fs;let a;for(const o of this._def.checks)o.kind==="min"?n.data.getTime()<o.value&&(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?n.data.getTime()>o.value&&(a=this._getOrReturnCtx(n,a),ze(a,{code:ve.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):$t.assertNever(o);return{status:r.value,value:new Date(n.data.getTime())}}_addCheck(n){return new ri({...this._def,checks:[...this._def.checks,n]})}min(n,s){return this._addCheck({kind:"min",value:n.getTime(),message:Ye.toString(s)})}max(n,s){return this._addCheck({kind:"max",value:n.getTime(),message:Ye.toString(s)})}get minDate(){let n=null;for(const s of this._def.checks)s.kind==="min"&&(n===null||s.value>n)&&(n=s.value);return n!=null?new Date(n):null}get maxDate(){let n=null;for(const s of this._def.checks)s.kind==="max"&&(n===null||s.value<n)&&(n=s.value);return n!=null?new Date(n):null}}ri.create=t=>new ri({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:ut.ZodDate,...jt(t)});class Rf extends Tt{_parse(n){if(this._getType(n)!==Qe.symbol){const r=this._getOrReturnCtx(n);return ze(r,{code:ve.invalid_type,expected:Qe.symbol,received:r.parsedType}),dt}return tr(n.data)}}Rf.create=t=>new Rf({typeName:ut.ZodSymbol,...jt(t)});class Im extends Tt{_parse(n){if(this._getType(n)!==Qe.undefined){const r=this._getOrReturnCtx(n);return ze(r,{code:ve.invalid_type,expected:Qe.undefined,received:r.parsedType}),dt}return tr(n.data)}}Im.create=t=>new Im({typeName:ut.ZodUndefined,...jt(t)});class _m extends Tt{_parse(n){if(this._getType(n)!==Qe.null){const r=this._getOrReturnCtx(n);return ze(r,{code:ve.invalid_type,expected:Qe.null,received:r.parsedType}),dt}return tr(n.data)}}_m.create=t=>new _m({typeName:ut.ZodNull,...jt(t)});class Pf extends Tt{constructor(){super(...arguments),this._any=!0}_parse(n){return tr(n.data)}}Pf.create=t=>new Pf({typeName:ut.ZodAny,...jt(t)});class Am extends Tt{constructor(){super(...arguments),this._unknown=!0}_parse(n){return tr(n.data)}}Am.create=t=>new Am({typeName:ut.ZodUnknown,...jt(t)});class ja extends Tt{_parse(n){const s=this._getOrReturnCtx(n);return ze(s,{code:ve.invalid_type,expected:Qe.never,received:s.parsedType}),dt}}ja.create=t=>new ja({typeName:ut.ZodNever,...jt(t)});class Mf extends Tt{_parse(n){if(this._getType(n)!==Qe.undefined){const r=this._getOrReturnCtx(n);return ze(r,{code:ve.invalid_type,expected:Qe.void,received:r.parsedType}),dt}return tr(n.data)}}Mf.create=t=>new Mf({typeName:ut.ZodVoid,...jt(t)});class Nr extends Tt{_parse(n){const{ctx:s,status:r}=this._processInputParams(n),a=this._def;if(s.parsedType!==Qe.array)return ze(s,{code:ve.invalid_type,expected:Qe.array,received:s.parsedType}),dt;if(a.exactLength!==null){const i=s.data.length>a.exactLength.value,l=s.data.length<a.exactLength.value;(i||l)&&(ze(s,{code:i?ve.too_big:ve.too_small,minimum:l?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(a.minLength!==null&&s.data.length<a.minLength.value&&(ze(s,{code:ve.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),a.maxLength!==null&&s.data.length>a.maxLength.value&&(ze(s,{code:ve.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((i,l)=>a.type._parseAsync(new Ar(s,i,s.path,l)))).then(i=>fs.mergeArray(r,i));const o=[...s.data].map((i,l)=>a.type._parseSync(new Ar(s,i,s.path,l)));return fs.mergeArray(r,o)}get element(){return this._def.type}min(n,s){return new Nr({...this._def,minLength:{value:n,message:Ye.toString(s)}})}max(n,s){return new Nr({...this._def,maxLength:{value:n,message:Ye.toString(s)}})}length(n,s){return new Nr({...this._def,exactLength:{value:n,message:Ye.toString(s)}})}nonempty(n){return this.min(1,n)}}Nr.create=(t,n)=>new Nr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ut.ZodArray,...jt(n)});function Mo(t){if(t instanceof Rn){const n={};for(const s in t.shape){const r=t.shape[s];n[s]=Br.create(Mo(r))}return new Rn({...t._def,shape:()=>n})}else return t instanceof Nr?new Nr({...t._def,type:Mo(t.element)}):t instanceof Br?Br.create(Mo(t.unwrap())):t instanceof no?no.create(Mo(t.unwrap())):t instanceof eo?eo.create(t.items.map(n=>Mo(n))):t}class Rn extends Tt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const n=this._def.shape(),s=$t.objectKeys(n);return this._cached={shape:n,keys:s},this._cached}_parse(n){if(this._getType(n)!==Qe.object){const d=this._getOrReturnCtx(n);return ze(d,{code:ve.invalid_type,expected:Qe.object,received:d.parsedType}),dt}const{status:r,ctx:a}=this._processInputParams(n),{shape:o,keys:i}=this._getCached(),l=[];if(!(this._def.catchall instanceof ja&&this._def.unknownKeys==="strip"))for(const d in a.data)i.includes(d)||l.push(d);const u=[];for(const d of i){const m=o[d],p=a.data[d];u.push({key:{status:"valid",value:d},value:m._parse(new Ar(a,p,a.path,d)),alwaysSet:d in a.data})}if(this._def.catchall instanceof ja){const d=this._def.unknownKeys;if(d==="passthrough")for(const m of l)u.push({key:{status:"valid",value:m},value:{status:"valid",value:a.data[m]}});else if(d==="strict")l.length>0&&(ze(a,{code:ve.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const m of l){const p=a.data[m];u.push({key:{status:"valid",value:m},value:d._parse(new Ar(a,p,a.path,m)),alwaysSet:m in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const d=[];for(const m of u){const p=await m.key,x=await m.value;d.push({key:p,value:x,alwaysSet:m.alwaysSet})}return d}).then(d=>fs.mergeObjectSync(r,d)):fs.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(n){return Ye.errToObj,new Rn({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(s,r)=>{var o,i;const a=((i=(o=this._def).errorMap)==null?void 0:i.call(o,s,r).message)??r.defaultError;return s.code==="unrecognized_keys"?{message:Ye.errToObj(n).message??a}:{message:a}}}:{}})}strip(){return new Rn({...this._def,unknownKeys:"strip"})}passthrough(){return new Rn({...this._def,unknownKeys:"passthrough"})}extend(n){return new Rn({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new Rn({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:ut.ZodObject})}setKey(n,s){return this.augment({[n]:s})}catchall(n){return new Rn({...this._def,catchall:n})}pick(n){const s={};for(const r of $t.objectKeys(n))n[r]&&this.shape[r]&&(s[r]=this.shape[r]);return new Rn({...this._def,shape:()=>s})}omit(n){const s={};for(const r of $t.objectKeys(this.shape))n[r]||(s[r]=this.shape[r]);return new Rn({...this._def,shape:()=>s})}deepPartial(){return Mo(this)}partial(n){const s={};for(const r of $t.objectKeys(this.shape)){const a=this.shape[r];n&&!n[r]?s[r]=a:s[r]=a.optional()}return new Rn({...this._def,shape:()=>s})}required(n){const s={};for(const r of $t.objectKeys(this.shape))if(n&&!n[r])s[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Br;)o=o._def.innerType;s[r]=o}return new Rn({...this._def,shape:()=>s})}keyof(){return Hv($t.objectKeys(this.shape))}}Rn.create=(t,n)=>new Rn({shape:()=>t,unknownKeys:"strip",catchall:ja.create(),typeName:ut.ZodObject,...jt(n)});Rn.strictCreate=(t,n)=>new Rn({shape:()=>t,unknownKeys:"strict",catchall:ja.create(),typeName:ut.ZodObject,...jt(n)});Rn.lazycreate=(t,n)=>new Rn({shape:t,unknownKeys:"strip",catchall:ja.create(),typeName:ut.ZodObject,...jt(n)});class Pc extends Tt{_parse(n){const{ctx:s}=this._processInputParams(n),r=this._def.options;function a(o){for(const l of o)if(l.result.status==="valid")return l.result;for(const l of o)if(l.result.status==="dirty")return s.common.issues.push(...l.ctx.common.issues),l.result;const i=o.map(l=>new Hr(l.ctx.common.issues));return ze(s,{code:ve.invalid_union,unionErrors:i}),dt}if(s.common.async)return Promise.all(r.map(async o=>{const i={...s,common:{...s.common,issues:[]},parent:null};return{result:await o._parseAsync({data:s.data,path:s.path,parent:i}),ctx:i}})).then(a);{let o;const i=[];for(const u of r){const d={...s,common:{...s.common,issues:[]},parent:null},m=u._parseSync({data:s.data,path:s.path,parent:d});if(m.status==="valid")return m;m.status==="dirty"&&!o&&(o={result:m,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(o)return s.common.issues.push(...o.ctx.common.issues),o.result;const l=i.map(u=>new Hr(u));return ze(s,{code:ve.invalid_union,unionErrors:l}),dt}}get options(){return this._def.options}}Pc.create=(t,n)=>new Pc({options:t,typeName:ut.ZodUnion,...jt(n)});const qr=t=>t instanceof Tm?qr(t.schema):t instanceof wa?qr(t.innerType()):t instanceof Dc?[t.value]:t instanceof to?t.options:t instanceof Rm?$t.objectValues(t.enum):t instanceof Lc?qr(t._def.innerType):t instanceof Im?[void 0]:t instanceof _m?[null]:t instanceof Br?[void 0,...qr(t.unwrap())]:t instanceof no?[null,...qr(t.unwrap())]:t instanceof Vv||t instanceof qc?qr(t.unwrap()):t instanceof Fc?qr(t._def.innerType):[];class cx extends Tt{_parse(n){const{ctx:s}=this._processInputParams(n);if(s.parsedType!==Qe.object)return ze(s,{code:ve.invalid_type,expected:Qe.object,received:s.parsedType}),dt;const r=this.discriminator,a=s.data[r],o=this.optionsMap.get(a);return o?s.common.async?o._parseAsync({data:s.data,path:s.path,parent:s}):o._parseSync({data:s.data,path:s.path,parent:s}):(ze(s,{code:ve.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),dt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,s,r){const a=new Map;for(const o of s){const i=qr(o.shape[n]);if(!i.length)throw new Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(const l of i){if(a.has(l))throw new Error(`Discriminator property ${String(n)} has duplicate value ${String(l)}`);a.set(l,o)}}return new cx({typeName:ut.ZodDiscriminatedUnion,discriminator:n,options:s,optionsMap:a,...jt(r)})}}function Em(t,n){const s=ia(t),r=ia(n);if(t===n)return{valid:!0,data:t};if(s===Qe.object&&r===Qe.object){const a=$t.objectKeys(n),o=$t.objectKeys(t).filter(l=>a.indexOf(l)!==-1),i={...t,...n};for(const l of o){const u=Em(t[l],n[l]);if(!u.valid)return{valid:!1};i[l]=u.data}return{valid:!0,data:i}}else if(s===Qe.array&&r===Qe.array){if(t.length!==n.length)return{valid:!1};const a=[];for(let o=0;o<t.length;o++){const i=t[o],l=n[o],u=Em(i,l);if(!u.valid)return{valid:!1};a.push(u.data)}return{valid:!0,data:a}}else return s===Qe.date&&r===Qe.date&&+t==+n?{valid:!0,data:t}:{valid:!1}}class Mc extends Tt{_parse(n){const{status:s,ctx:r}=this._processInputParams(n),a=(o,i)=>{if(Af(o)||Af(i))return dt;const l=Em(o.value,i.value);return l.valid?((Ef(o)||Ef(i))&&s.dirty(),{status:s.value,value:l.data}):(ze(r,{code:ve.invalid_intersection_types}),dt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>a(o,i)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Mc.create=(t,n,s)=>new Mc({left:t,right:n,typeName:ut.ZodIntersection,...jt(s)});class eo extends Tt{_parse(n){const{status:s,ctx:r}=this._processInputParams(n);if(r.parsedType!==Qe.array)return ze(r,{code:ve.invalid_type,expected:Qe.array,received:r.parsedType}),dt;if(r.data.length<this._def.items.length)return ze(r,{code:ve.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),dt;!this._def.rest&&r.data.length>this._def.items.length&&(ze(r,{code:ve.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const o=[...r.data].map((i,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ar(r,i,r.path,l)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>fs.mergeArray(s,i)):fs.mergeArray(s,o)}get items(){return this._def.items}rest(n){return new eo({...this._def,rest:n})}}eo.create=(t,n)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new eo({items:t,typeName:ut.ZodTuple,rest:null,...jt(n)})};class $c extends Tt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:s,ctx:r}=this._processInputParams(n);if(r.parsedType!==Qe.object)return ze(r,{code:ve.invalid_type,expected:Qe.object,received:r.parsedType}),dt;const a=[],o=this._def.keyType,i=this._def.valueType;for(const l in r.data)a.push({key:o._parse(new Ar(r,l,r.path,l)),value:i._parse(new Ar(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?fs.mergeObjectAsync(s,a):fs.mergeObjectSync(s,a)}get element(){return this._def.valueType}static create(n,s,r){return s instanceof Tt?new $c({keyType:n,valueType:s,typeName:ut.ZodRecord,...jt(r)}):new $c({keyType:vr.create(),valueType:n,typeName:ut.ZodRecord,...jt(s)})}}class $f extends Tt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:s,ctx:r}=this._processInputParams(n);if(r.parsedType!==Qe.map)return ze(r,{code:ve.invalid_type,expected:Qe.map,received:r.parsedType}),dt;const a=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([l,u],d)=>({key:a._parse(new Ar(r,l,r.path,[d,"key"])),value:o._parse(new Ar(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of i){const d=await u.key,m=await u.value;if(d.status==="aborted"||m.status==="aborted")return dt;(d.status==="dirty"||m.status==="dirty")&&s.dirty(),l.set(d.value,m.value)}return{status:s.value,value:l}})}else{const l=new Map;for(const u of i){const d=u.key,m=u.value;if(d.status==="aborted"||m.status==="aborted")return dt;(d.status==="dirty"||m.status==="dirty")&&s.dirty(),l.set(d.value,m.value)}return{status:s.value,value:l}}}}$f.create=(t,n,s)=>new $f({valueType:n,keyType:t,typeName:ut.ZodMap,...jt(s)});class cl extends Tt{_parse(n){const{status:s,ctx:r}=this._processInputParams(n);if(r.parsedType!==Qe.set)return ze(r,{code:ve.invalid_type,expected:Qe.set,received:r.parsedType}),dt;const a=this._def;a.minSize!==null&&r.data.size<a.minSize.value&&(ze(r,{code:ve.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),s.dirty()),a.maxSize!==null&&r.data.size>a.maxSize.value&&(ze(r,{code:ve.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),s.dirty());const o=this._def.valueType;function i(u){const d=new Set;for(const m of u){if(m.status==="aborted")return dt;m.status==="dirty"&&s.dirty(),d.add(m.value)}return{status:s.value,value:d}}const l=[...r.data.values()].map((u,d)=>o._parse(new Ar(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>i(u)):i(l)}min(n,s){return new cl({...this._def,minSize:{value:n,message:Ye.toString(s)}})}max(n,s){return new cl({...this._def,maxSize:{value:n,message:Ye.toString(s)}})}size(n,s){return this.min(n,s).max(n,s)}nonempty(n){return this.min(1,n)}}cl.create=(t,n)=>new cl({valueType:t,minSize:null,maxSize:null,typeName:ut.ZodSet,...jt(n)});class Tm extends Tt{get schema(){return this._def.getter()}_parse(n){const{ctx:s}=this._processInputParams(n);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}Tm.create=(t,n)=>new Tm({getter:t,typeName:ut.ZodLazy,...jt(n)});class Dc extends Tt{_parse(n){if(n.data!==this._def.value){const s=this._getOrReturnCtx(n);return ze(s,{received:s.data,code:ve.invalid_literal,expected:this._def.value}),dt}return{status:"valid",value:n.data}}get value(){return this._def.value}}Dc.create=(t,n)=>new Dc({value:t,typeName:ut.ZodLiteral,...jt(n)});function Hv(t,n){return new to({values:t,typeName:ut.ZodEnum,...jt(n)})}class to extends Tt{_parse(n){if(typeof n.data!="string"){const s=this._getOrReturnCtx(n),r=this._def.values;return ze(s,{expected:$t.joinValues(r),received:s.parsedType,code:ve.invalid_type}),dt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(n.data)){const s=this._getOrReturnCtx(n),r=this._def.values;return ze(s,{received:s.data,code:ve.invalid_enum_value,options:r}),dt}return tr(n.data)}get options(){return this._def.values}get enum(){const n={};for(const s of this._def.values)n[s]=s;return n}get Values(){const n={};for(const s of this._def.values)n[s]=s;return n}get Enum(){const n={};for(const s of this._def.values)n[s]=s;return n}extract(n,s=this._def){return to.create(n,{...this._def,...s})}exclude(n,s=this._def){return to.create(this.options.filter(r=>!n.includes(r)),{...this._def,...s})}}to.create=Hv;class Rm extends Tt{_parse(n){const s=$t.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(n);if(r.parsedType!==Qe.string&&r.parsedType!==Qe.number){const a=$t.objectValues(s);return ze(r,{expected:$t.joinValues(a),received:r.parsedType,code:ve.invalid_type}),dt}if(this._cache||(this._cache=new Set($t.getValidEnumValues(this._def.values))),!this._cache.has(n.data)){const a=$t.objectValues(s);return ze(r,{received:r.data,code:ve.invalid_enum_value,options:a}),dt}return tr(n.data)}get enum(){return this._def.values}}Rm.create=(t,n)=>new Rm({values:t,typeName:ut.ZodNativeEnum,...jt(n)});class Oc extends Tt{unwrap(){return this._def.type}_parse(n){const{ctx:s}=this._processInputParams(n);if(s.parsedType!==Qe.promise&&s.common.async===!1)return ze(s,{code:ve.invalid_type,expected:Qe.promise,received:s.parsedType}),dt;const r=s.parsedType===Qe.promise?s.data:Promise.resolve(s.data);return tr(r.then(a=>this._def.type.parseAsync(a,{path:s.path,errorMap:s.common.contextualErrorMap})))}}Oc.create=(t,n)=>new Oc({type:t,typeName:ut.ZodPromise,...jt(n)});class wa extends Tt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ut.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){const{status:s,ctx:r}=this._processInputParams(n),a=this._def.effect||null,o={addIssue:i=>{ze(r,i),i.fatal?s.abort():s.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),a.type==="preprocess"){const i=a.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async l=>{if(s.value==="aborted")return dt;const u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?dt:u.status==="dirty"||s.value==="dirty"?Oi(u.value):u});{if(s.value==="aborted")return dt;const l=this._def.schema._parseSync({data:i,path:r.path,parent:r});return l.status==="aborted"?dt:l.status==="dirty"||s.value==="dirty"?Oi(l.value):l}}if(a.type==="refinement"){const i=l=>{const u=a.refinement(l,o);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?dt:(l.status==="dirty"&&s.dirty(),i(l.value),{status:s.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?dt:(l.status==="dirty"&&s.dirty(),i(l.value).then(()=>({status:s.value,value:l.value}))))}if(a.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!si(i))return dt;const l=a.transform(i.value,o);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>si(i)?Promise.resolve(a.transform(i.value,o)).then(l=>({status:s.value,value:l})):dt);$t.assertNever(a)}}wa.create=(t,n,s)=>new wa({schema:t,typeName:ut.ZodEffects,effect:n,...jt(s)});wa.createWithPreprocess=(t,n,s)=>new wa({schema:n,effect:{type:"preprocess",transform:t},typeName:ut.ZodEffects,...jt(s)});class Br extends Tt{_parse(n){return this._getType(n)===Qe.undefined?tr(void 0):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Br.create=(t,n)=>new Br({innerType:t,typeName:ut.ZodOptional,...jt(n)});class no extends Tt{_parse(n){return this._getType(n)===Qe.null?tr(null):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}no.create=(t,n)=>new no({innerType:t,typeName:ut.ZodNullable,...jt(n)});class Lc extends Tt{_parse(n){const{ctx:s}=this._processInputParams(n);let r=s.data;return s.parsedType===Qe.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Lc.create=(t,n)=>new Lc({innerType:t,typeName:ut.ZodDefault,defaultValue:typeof n.default=="function"?n.default:()=>n.default,...jt(n)});class Fc extends Tt{_parse(n){const{ctx:s}=this._processInputParams(n),r={...s,common:{...s.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Tc(a)?a.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Hr(r.common.issues)},input:r.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Hr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Fc.create=(t,n)=>new Fc({innerType:t,typeName:ut.ZodCatch,catchValue:typeof n.catch=="function"?n.catch:()=>n.catch,...jt(n)});class Df extends Tt{_parse(n){if(this._getType(n)!==Qe.nan){const r=this._getOrReturnCtx(n);return ze(r,{code:ve.invalid_type,expected:Qe.nan,received:r.parsedType}),dt}return{status:"valid",value:n.data}}}Df.create=t=>new Df({typeName:ut.ZodNaN,...jt(t)});class Vv extends Tt{_parse(n){const{ctx:s}=this._processInputParams(n),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class dx extends Tt{_parse(n){const{status:s,ctx:r}=this._processInputParams(n);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?dt:o.status==="dirty"?(s.dirty(),Oi(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const a=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?dt:a.status==="dirty"?(s.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:r.path,parent:r})}}static create(n,s){return new dx({in:n,out:s,typeName:ut.ZodPipeline})}}class qc extends Tt{_parse(n){const s=this._def.innerType._parse(n),r=a=>(si(a)&&(a.value=Object.freeze(a.value)),a);return Tc(s)?s.then(a=>r(a)):r(s)}unwrap(){return this._def.innerType}}qc.create=(t,n)=>new qc({innerType:t,typeName:ut.ZodReadonly,...jt(n)});var ut;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ut||(ut={}));const P=vr.create,St=Ya.create;Xa.create;const Ve=Rc.create;ri.create;const gt=Am.create,Y2=ja.create,st=Nr.create,xe=Rn.create,Fd=Pc.create,ux=cx.create;Mc.create;eo.create;const mt=$c.create,ks=Dc.create,Me=to.create;Oc.create;Br.create;no.create;const X2=wa.createWithPreprocess,Oa={string:(t=>vr.create({...t,coerce:!0})),number:(t=>Ya.create({...t,coerce:!0})),boolean:(t=>Rc.create({...t,coerce:!0})),bigint:(t=>Xa.create({...t,coerce:!0})),date:(t=>ri.create({...t,coerce:!0}))},e5=xe({censorUsernameInLogs:Ve().default(!1)}).strict();e5.partial();const t5=xe({enableIsolatedWorkspaces:Ve().default(!1),autoRestartDevServerWhenIdle:Ve().default(!1)}).strict();t5.partial();xe({scopeType:Me(m2),scopeId:P().uuid(),metric:Me(p2).optional().default("billed_cents"),windowKind:Me(x2).optional().default("calendar_month_utc"),amount:St().int().nonnegative(),warnPercent:St().int().min(1).max(99).optional().default(80),hardStopEnabled:Ve().optional().default(!0),notifyEnabled:Ve().optional().default(!0),isActive:Ve().optional().default(!0)});xe({action:Me(f2),amount:St().int().nonnegative().optional(),decisionNote:P().optional().nullable()}).superRefine((t,n)=>{t.action==="raise_budget_and_resume"&&typeof t.amount!="number"&&n.addIssue({code:ve.custom,message:"amount is required when raising a budget",path:["amount"]})});const Qv=P().uuid().nullable().optional(),Gv=P().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),n5=xe({name:P().min(1),description:P().optional().nullable(),budgetMonthlyCents:St().int().nonnegative().optional().default(0)});n5.partial().extend({status:Me(JI).optional(),spentMonthlyCents:St().int().nonnegative().optional(),requireBoardApprovalForNewAgents:Ve().optional(),brandColor:Gv,logoAssetId:Qv});xe({name:P().min(1).optional(),description:P().nullable().optional(),brandColor:Gv,logoAssetId:Qv}).strict().refine(t=>t.name!==void 0||t.description!==void 0||t.brandColor!==void 0||t.logoAssetId!==void 0,"At least one branding field must be provided");const s5=Me(["local_path","github","url","catalog","skills_sh"]),r5=Me(["markdown_only","assets","scripts_executables"]),a5=Me(["compatible","unknown","invalid"]),Jv=Me(["crewspace","github","local","url","catalog","skills_sh"]),o5=xe({path:P().min(1),kind:Me(["skill","markdown","reference","script","asset","other"])}),Uc=xe({id:P().uuid(),companyId:P().uuid(),key:P().min(1),slug:P().min(1),name:P().min(1),description:P().nullable(),markdown:P(),sourceType:s5,sourceLocator:P().nullable(),sourceRef:P().nullable(),trustLevel:r5,compatibility:a5,fileInventory:st(o5).default([]),metadata:mt(gt()).nullable(),createdAt:Oa.date(),updatedAt:Oa.date()});Uc.extend({attachedAgentCount:St().int().nonnegative(),editable:Ve(),editableReason:P().nullable(),sourceLabel:P().nullable(),sourceBadge:Jv});const i5=xe({id:P().uuid(),name:P().min(1),urlKey:P().min(1),adapterType:P().min(1),desired:Ve(),actualState:P().nullable()});Uc.extend({attachedAgentCount:St().int().nonnegative(),usedByAgents:st(i5).default([]),editable:Ve(),editableReason:P().nullable(),sourceLabel:P().nullable(),sourceBadge:Jv});xe({supported:Ve(),reason:P().nullable(),trackingRef:P().nullable(),currentRef:P().nullable(),latestRef:P().nullable(),hasUpdate:Ve()});xe({source:P().min(1)});xe({projectIds:st(P().uuid()).optional(),workspaceIds:st(P().uuid()).optional()});const l5=xe({projectId:P().uuid(),projectName:P().min(1),workspaceId:P().uuid().nullable(),workspaceName:P().nullable(),path:P().nullable(),reason:P().min(1)}),c5=xe({slug:P().min(1),key:P().min(1),projectId:P().uuid(),projectName:P().min(1),workspaceId:P().uuid(),workspaceName:P().min(1),path:P().min(1),existingSkillId:P().uuid(),existingSkillKey:P().min(1),existingSourceLocator:P().nullable(),reason:P().min(1)});xe({scannedProjects:St().int().nonnegative(),scannedWorkspaces:St().int().nonnegative(),discovered:St().int().nonnegative(),imported:st(Uc),updated:st(Uc),skipped:st(l5),conflicts:st(c5),warnings:st(P())});xe({name:P().min(1),slug:P().min(1).nullable().optional(),description:P().nullable().optional(),markdown:P().nullable().optional()});xe({skillId:P().uuid(),path:P().min(1),kind:Me(["skill","markdown","reference","script","asset","other"]),content:P(),language:P().nullable(),markdown:Ve(),editable:Ve()});xe({path:P().min(1),content:P()});const d5=Me(["available","configured","installed","missing","stale","external"]),u5=Me(["company_managed","crewspace_required","user_installed","external_unknown"]),m5=Me(["unsupported","persistent","ephemeral"]),p5=xe({key:P().min(1),runtimeName:P().min(1).nullable(),desired:Ve(),managed:Ve(),required:Ve().optional(),requiredReason:P().nullable().optional(),state:d5,origin:u5.optional(),originLabel:P().nullable().optional(),locationLabel:P().nullable().optional(),readOnly:Ve().optional(),sourcePath:P().nullable().optional(),targetPath:P().nullable().optional(),detail:P().nullable().optional()});xe({adapterType:P().min(1),supported:Ve(),mode:m5,desiredSkills:st(P().min(1)),entries:st(p5),warnings:st(P())});xe({desiredSkills:st(P().min(1))});const Zv=xe({company:Ve().optional(),agents:Ve().optional(),projects:Ve().optional(),issues:Ve().optional(),skills:Ve().optional()}).partial(),x5=xe({key:P().min(1),description:P().nullable(),agentSlug:P().min(1).nullable(),kind:Me(["secret","plain"]),requirement:Me(["required","optional"]),defaultValue:P().nullable(),portability:Me(["portable","system_dependent"])}),f5=Fd([P(),xe({encoding:ks("base64"),data:P(),contentType:P().min(1).optional().nullable()})]),h5=xe({path:P().min(1),name:P().min(1),description:P().nullable(),brandColor:P().nullable(),logoPath:P().nullable(),requireBoardApprovalForNewAgents:Ve()}),Yv=xe({agents:st(P().min(1)).default([]),projects:st(P().min(1)).default([])}),g5=xe({slug:P().min(1),name:P().min(1),path:P().min(1),skills:st(P().min(1)).default([]),role:P().min(1),title:P().nullable(),icon:P().nullable(),capabilities:P().nullable(),reportsToSlug:P().min(1).nullable(),adapterType:P().min(1),adapterConfig:mt(gt()),runtimeConfig:mt(gt()),permissions:mt(gt()),budgetMonthlyCents:St().int().nonnegative(),metadata:mt(gt()).nullable()}),b5=xe({key:P().min(1),slug:P().min(1),name:P().min(1),path:P().min(1),description:P().nullable(),sourceType:P().min(1),sourceLocator:P().nullable(),sourceRef:P().nullable(),trustLevel:P().nullable(),compatibility:P().nullable(),metadata:mt(gt()).nullable(),fileInventory:st(xe({path:P().min(1),kind:P().min(1)})).default([])}),y5=xe({slug:P().min(1),name:P().min(1),path:P().min(1),description:P().nullable(),ownerAgentSlug:P().min(1).nullable(),leadAgentSlug:P().min(1).nullable(),targetDate:P().nullable(),color:P().nullable(),status:P().nullable(),executionWorkspacePolicy:mt(gt()).nullable(),workspaces:st(xe({key:P().min(1),name:P().min(1),sourceType:P().nullable(),repoUrl:P().nullable(),repoRef:P().nullable(),defaultRef:P().nullable(),visibility:P().nullable(),setupCommand:P().nullable(),cleanupCommand:P().nullable(),metadata:mt(gt()).nullable(),isPrimary:Ve()})).default([]),metadata:mt(gt()).nullable()}),v5=xe({kind:P().min(1),label:P().nullable(),enabled:Ve(),cronExpression:P().nullable(),timezone:P().nullable(),signingMode:P().nullable(),replayWindowSec:St().int().nullable()}),j5=xe({concurrencyPolicy:P().nullable(),catchUpPolicy:P().nullable(),triggers:st(v5).default([])}),w5=xe({slug:P().min(1),identifier:P().min(1).nullable(),title:P().min(1),path:P().min(1),projectSlug:P().min(1).nullable(),projectWorkspaceKey:P().min(1).nullable(),assigneeAgentSlug:P().min(1).nullable(),description:P().nullable(),recurring:Ve().default(!1),routine:j5.nullable(),legacyRecurrence:mt(gt()).nullable(),status:P().nullable(),priority:P().nullable(),labelIds:st(P().min(1)).default([]),billingCode:P().nullable(),executionWorkspaceSettings:mt(gt()).nullable(),assigneeAdapterOverrides:mt(gt()).nullable(),metadata:mt(gt()).nullable()});xe({schemaVersion:St().int().positive(),generatedAt:P().datetime(),source:xe({companyId:P().uuid(),companyName:P().min(1)}).nullable(),includes:xe({company:Ve(),agents:Ve(),projects:Ve(),issues:Ve(),skills:Ve()}),company:h5.nullable(),sidebar:Yv.nullable(),agents:st(g5),skills:st(b5).default([]),projects:st(y5).default([]),issues:st(w5).default([]),envInputs:st(x5).default([])});const N5=ux("type",[xe({type:ks("inline"),rootPath:P().min(1).optional().nullable(),files:mt(f5)}),xe({type:ks("github"),url:P().url()})]),k5=ux("mode",[xe({mode:ks("new_company"),newCompanyName:P().min(1).optional().nullable()}),xe({mode:ks("existing_company"),companyId:P().uuid()})]),C5=Fd([ks("all"),st(P().min(1))]),S5=Me(["rename","skip","replace"]);xe({include:Zv.optional(),agents:st(P().min(1)).optional(),skills:st(P().min(1)).optional(),projects:st(P().min(1)).optional(),issues:st(P().min(1)).optional(),projectIssues:st(P().min(1)).optional(),selectedFiles:st(P().min(1)).optional(),expandReferencedSkills:Ve().optional(),sidebarOrder:Yv.partial().optional()});const I5=xe({source:N5,include:Zv.optional(),target:k5,agents:C5.optional(),collisionStrategy:S5.optional(),nameOverrides:mt(P().min(1),P().min(1)).optional(),selectedFiles:st(P().min(1)).optional()}),_5=xe({adapterType:P().min(1),adapterConfig:mt(gt()).optional()});I5.extend({adapterOverrides:mt(P().min(1),_5).optional()});const A5=xe({type:ks("plain"),value:P()}),E5=xe({type:ks("secret_ref"),secretId:P().uuid(),version:Fd([ks("latest"),St().int().positive()]).optional()}),T5=Fd([P(),A5,E5]),R5=mt(T5);xe({name:P().min(1),provider:Me(qv).optional(),value:P().min(1),description:P().optional().nullable(),externalRef:P().optional().nullable()});xe({value:P().min(1),externalRef:P().optional().nullable()});xe({name:P().min(1).optional(),description:P().optional().nullable(),externalRef:P().optional().nullable()});const P5=xe({canCreateAgents:Ve().optional().default(!1)}),M5=Me(["managed","external"]);xe({mode:M5.optional(),rootPath:P().trim().min(1).nullable().optional(),entryFile:P().trim().min(1).optional(),clearLegacyPromptTemplate:Ve().optional().default(!1)});xe({path:P().trim().min(1),content:P(),clearLegacyPromptTemplate:Ve().optional().default(!1)});const Xv=mt(gt()).superRefine((t,n)=>{const s=t.env;if(s===void 0)return;R5.safeParse(s).success||n.addIssue({code:ve.custom,message:"adapterConfig.env must be a map of valid env bindings",path:["env"]})}),ej=xe({name:P().min(1),role:Me(Dv).optional().default("general"),title:P().optional().nullable(),icon:Me(ax).optional().nullable(),reportsTo:P().uuid().optional().nullable(),capabilities:P().optional().nullable(),desiredSkills:st(P().min(1)).optional(),adapterType:Me(_l).optional().default("process"),adapterConfig:Xv.optional().default({}),runtimeConfig:mt(gt()).optional().default({}),budgetMonthlyCents:St().int().nonnegative().optional().default(0),permissions:P5.optional(),metadata:mt(gt()).optional().nullable()});ej.extend({sourceIssueId:P().uuid().optional().nullable(),sourceIssueIds:st(P().uuid()).optional()});ej.omit({permissions:!0}).partial().extend({permissions:Y2().optional(),replaceAdapterConfig:Ve().optional(),status:Me(e2).optional(),spentMonthlyCents:St().int().nonnegative().optional()});xe({path:P().trim().min(1).nullable(),adapterConfigKey:P().trim().min(1).optional()});xe({name:P().min(1).default("default")});xe({userId:P().trim().min(1),status:P().trim().min(1).optional().default(km)});xe({source:Me(["timer","assignment","on_demand","automation"]).optional().default("on_demand"),triggerDetail:Me(["manual","ping","callback","system"]).optional(),reason:P().optional().nullable(),payload:mt(gt()).optional().nullable(),idempotencyKey:P().optional().nullable(),forceFreshSession:X2(t=>t===null?void 0:t,Ve().optional().default(!1))});xe({taskKey:P().min(1).optional().nullable()});xe({adapterConfig:Xv.optional().default({})});xe({canCreateAgents:Ve(),canAssignTasks:Ve()});const $5=xe({type:Me(["project_primary","git_worktree","adapter_managed","cloud_sandbox"]).optional(),baseRef:P().optional().nullable(),branchTemplate:P().optional().nullable(),worktreeParentDir:P().optional().nullable(),provisionCommand:P().optional().nullable(),teardownCommand:P().optional().nullable()}).strict(),D5=xe({enabled:Ve(),defaultMode:Me(["shared_workspace","isolated_workspace","operator_branch","adapter_default"]).optional(),allowIssueOverride:Ve().optional(),defaultProjectWorkspaceId:P().uuid().optional().nullable(),workspaceStrategy:$5.optional().nullable(),workspaceRuntime:mt(gt()).optional().nullable(),branchPolicy:mt(gt()).optional().nullable(),pullRequestPolicy:mt(gt()).optional().nullable(),runtimePolicy:mt(gt()).optional().nullable(),cleanupPolicy:mt(gt()).optional().nullable()}).strict(),O5=xe({workspaceRuntime:mt(gt()).optional().nullable(),desiredState:Me(["running","stopped"]).optional().nullable()}).strict(),L5=Me(["local_path","git_repo","remote_managed","non_git_path"]),F5=Me(["default","advanced"]),tj={name:P().min(1).optional(),sourceType:L5.optional(),cwd:P().min(1).optional().nullable(),repoUrl:P().url().optional().nullable(),repoRef:P().optional().nullable(),defaultRef:P().optional().nullable(),visibility:F5.optional(),setupCommand:P().optional().nullable(),cleanupCommand:P().optional().nullable(),remoteProvider:P().optional().nullable(),remoteWorkspaceRef:P().optional().nullable(),sharedWorkspaceKey:P().optional().nullable(),metadata:mt(gt()).optional().nullable(),runtimeConfig:O5.optional().nullable()};function q5(t,n){const s=t.sourceType??"local_path",r=typeof t.cwd=="string"&&t.cwd.trim().length>0,a=typeof t.repoUrl=="string"&&t.repoUrl.trim().length>0,o=typeof t.remoteWorkspaceRef=="string"&&t.remoteWorkspaceRef.trim().length>0;if(s==="remote_managed"){!o&&!a&&n.addIssue({code:ve.custom,message:"Remote-managed workspace requires remoteWorkspaceRef or repoUrl.",path:["remoteWorkspaceRef"]});return}!r&&!a&&n.addIssue({code:ve.custom,message:"Workspace requires at least one of cwd or repoUrl.",path:["cwd"]})}const U5=xe({...tj,isPrimary:Ve().optional().default(!1)}).superRefine(q5);xe({...tj,isPrimary:Ve().optional()}).partial();const nj={goalId:P().uuid().optional().nullable(),goalIds:st(P().uuid()).optional(),name:P().min(1),description:P().optional().nullable(),status:Me(n2).optional().default("backlog"),leadAgentId:P().uuid().optional().nullable(),targetDate:P().optional().nullable(),color:P().optional().nullable(),executionWorkspacePolicy:D5.optional().nullable(),archivedAt:P().datetime().optional().nullable()};xe({...nj,workspace:U5.optional()});xe(nj).partial();const B5=xe({type:Me(["project_primary","git_worktree","adapter_managed","cloud_sandbox"]).optional(),baseRef:P().optional().nullable(),branchTemplate:P().optional().nullable(),worktreeParentDir:P().optional().nullable(),provisionCommand:P().optional().nullable(),teardownCommand:P().optional().nullable()}).strict(),K5=xe({mode:Me(["inherit","shared_workspace","isolated_workspace","operator_branch","reuse_existing","agent_default"]).optional(),workspaceStrategy:B5.optional().nullable(),workspaceRuntime:mt(gt()).optional().nullable()}).strict(),z5=xe({adapterConfig:mt(gt()).optional(),useProjectWorkspace:Ve().optional()}).strict(),W5=xe({projectId:P().uuid().optional().nullable(),projectWorkspaceId:P().uuid().optional().nullable(),goalId:P().uuid().optional().nullable(),parentId:P().uuid().optional().nullable(),inheritExecutionWorkspaceFromIssueId:P().uuid().optional().nullable(),title:P().min(1),description:P().optional().nullable(),status:Me(Ov).optional().default("backlog"),priority:Me(Lv).optional().default("medium"),assigneeAgentId:P().uuid().optional().nullable(),assigneeUserId:P().optional().nullable(),requestDepth:St().int().nonnegative().optional().default(0),billingCode:P().optional().nullable(),assigneeAdapterOverrides:z5.optional().nullable(),executionWorkspaceId:P().uuid().optional().nullable(),executionWorkspacePreference:Me(["inherit","shared_workspace","isolated_workspace","operator_branch","reuse_existing","agent_default"]).optional().nullable(),executionWorkspaceSettings:K5.optional().nullable(),labelIds:st(P().uuid()).optional()});xe({name:P().trim().min(1).max(48),color:P().regex(/^#(?:[0-9a-fA-F]{6})$/,"Color must be a 6-digit hex value")});W5.partial().extend({comment:P().min(1).optional(),reopen:Ve().optional(),interrupt:Ve().optional(),hiddenAt:P().datetime().nullable().optional()});xe({agentId:P().uuid(),expectedStatuses:st(Me(Ov)).nonempty()});xe({body:P().min(1),reopen:Ve().optional(),interrupt:Ve().optional()});xe({approvalId:P().uuid()});xe({issueCommentId:P().uuid().optional().nullable()});const H5=["markdown"],V5=Me(H5);P().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9_-]*$/,"Document key must be lowercase letters, numbers, _ or -");xe({title:P().trim().max(200).nullable().optional(),format:V5,body:P().max(524288),changeSummary:P().trim().max(500).nullable().optional(),baseRevisionId:P().uuid().nullable().optional()});xe({});const Q5=Me(["preview_url","runtime_service","pull_request","branch","commit","artifact","document"]),G5=Me(["active","ready_for_review","approved","changes_requested","merged","closed","failed","archived","draft"]),J5=Me(["none","needs_board_review","approved","changes_requested"]),Z5=xe({projectId:P().uuid().optional().nullable(),executionWorkspaceId:P().uuid().optional().nullable(),runtimeServiceId:P().uuid().optional().nullable(),type:Q5,provider:P().min(1),externalId:P().optional().nullable(),title:P().min(1),url:P().url().optional().nullable(),status:G5.default("active"),reviewState:J5.optional().default("none"),isPrimary:Ve().optional().default(!1),healthStatus:Me(["unknown","healthy","unhealthy"]).optional().default("unknown"),summary:P().optional().nullable(),metadata:mt(gt()).optional().nullable(),createdByRunId:P().uuid().optional().nullable()});Z5.partial();const Y5=Me(["active","idle","in_review","archived","cleanup_failed"]),X5=xe({provisionCommand:P().optional().nullable(),teardownCommand:P().optional().nullable(),cleanupCommand:P().optional().nullable(),workspaceRuntime:mt(gt()).optional().nullable(),desiredState:Me(["running","stopped"]).optional().nullable()}).strict(),e_=Me(["ready","ready_with_warnings","blocked"]),t_=Me(["archive_record","stop_runtime_services","cleanup_command","teardown_command","git_worktree_remove","git_branch_delete","remove_local_directory"]),n_=xe({kind:t_,label:P(),description:P(),command:P().nullable()}).strict(),s_=xe({id:P().uuid(),identifier:P().nullable(),title:P(),status:P(),isTerminal:Ve()}).strict(),r_=xe({repoRoot:P().nullable(),workspacePath:P().nullable(),branchName:P().nullable(),baseRef:P().nullable(),hasDirtyTrackedFiles:Ve(),hasUntrackedFiles:Ve(),dirtyEntryCount:St().int().nonnegative(),untrackedEntryCount:St().int().nonnegative(),aheadCount:St().int().nonnegative().nullable(),behindCount:St().int().nonnegative().nullable(),isMergedIntoBase:Ve().nullable(),createdByRuntime:Ve()}).strict(),a_=xe({id:P(),companyId:P().uuid(),projectId:P().uuid().nullable(),projectWorkspaceId:P().uuid().nullable(),executionWorkspaceId:P().uuid().nullable(),issueId:P().uuid().nullable(),scopeType:Me(["project_workspace","execution_workspace","run","agent"]),scopeId:P().nullable(),serviceName:P(),status:Me(["starting","running","stopped","failed"]),lifecycle:Me(["shared","ephemeral"]),reuseKey:P().nullable(),command:P().nullable(),cwd:P().nullable(),port:St().int().nullable(),url:P().nullable(),provider:Me(["local_process","adapter_managed"]),providerRef:P().nullable(),ownerAgentId:P().uuid().nullable(),startedByRunId:P().uuid().nullable(),lastUsedAt:Oa.date(),startedAt:Oa.date(),stoppedAt:Oa.date().nullable(),stopPolicy:mt(gt()).nullable(),healthStatus:Me(["unknown","healthy","unhealthy"]),createdAt:Oa.date(),updatedAt:Oa.date()}).strict();xe({workspaceId:P().uuid(),state:e_,blockingReasons:st(P()),warnings:st(P()),linkedIssues:st(s_),plannedActions:st(n_),isDestructiveCloseAllowed:Ve(),isSharedWorkspace:Ve(),isProjectPrimaryWorkspace:Ve(),git:r_.nullable(),runtimeServices:st(a_)}).strict();xe({name:P().min(1).optional(),cwd:P().optional().nullable(),repoUrl:P().optional().nullable(),baseRef:P().optional().nullable(),branchName:P().optional().nullable(),providerRef:P().optional().nullable(),status:Y5.optional(),cleanupEligibleAt:P().datetime().optional().nullable(),cleanupReason:P().optional().nullable(),config:X5.optional().nullable(),metadata:mt(gt()).optional().nullable()}).strict();const o_=xe({title:P().min(1),description:P().optional().nullable(),level:Me(ox).optional().default("task"),status:Me(ix).optional().default("planned"),parentId:P().uuid().optional().nullable(),ownerAgentId:P().uuid().optional().nullable()});o_.partial();xe({type:Me(o2),requestedByAgentId:P().uuid().optional().nullable(),payload:mt(gt()),issueIds:st(P().uuid()).optional()});xe({decisionNote:P().optional().nullable(),decidedByUserId:P().optional().default("board")});xe({decisionNote:P().optional().nullable(),decidedByUserId:P().optional().default("board")});xe({payload:mt(gt()).optional()});xe({body:P().min(1)});const i_=xe({projectId:P().uuid(),goalId:P().uuid().optional().nullable(),parentIssueId:P().uuid().optional().nullable(),title:P().trim().min(1).max(200),description:P().optional().nullable(),assigneeAgentId:P().uuid(),priority:Me(Lv).optional().default("medium"),status:Me(s2).optional().default("active"),concurrencyPolicy:Me(r2).optional().default("coalesce_if_active"),catchUpPolicy:Me(a2).optional().default("skip_missed")});i_.partial();const uu=xe({label:P().trim().max(120).optional().nullable(),enabled:Ve().optional().default(!0)});ux("kind",[uu.extend({kind:ks("schedule"),cronExpression:P().trim().min(1),timezone:P().trim().min(1).default("UTC")}),uu.extend({kind:ks("webhook"),signingMode:Me(Fv).optional().default("bearer"),replayWindowSec:St().int().min(30).max(86400).optional().default(300)}),uu.extend({kind:ks("api")})]);xe({label:P().trim().max(120).optional().nullable(),enabled:Ve().optional(),cronExpression:P().trim().min(1).optional().nullable(),timezone:P().trim().min(1).optional().nullable(),signingMode:Me(Fv).optional().nullable(),replayWindowSec:St().int().min(30).max(86400).optional().nullable()});xe({triggerId:P().uuid().optional().nullable(),payload:mt(gt()).optional().nullable(),idempotencyKey:P().trim().max(255).optional().nullable(),source:Me(["manual","api"]).optional().default("manual")});xe({});xe({agentId:P().uuid(),issueId:P().uuid().optional().nullable(),projectId:P().uuid().optional().nullable(),goalId:P().uuid().optional().nullable(),heartbeatRunId:P().uuid().optional().nullable(),billingCode:P().optional().nullable(),provider:P().min(1),biller:P().min(1).optional(),billingType:Me(l2).optional().default("unknown"),model:P().min(1),inputTokens:St().int().nonnegative().optional().default(0),cachedInputTokens:St().int().nonnegative().optional().default(0),outputTokens:St().int().nonnegative().optional().default(0),costCents:St().int().nonnegative(),occurredAt:P().datetime()}).transform(t=>({...t,biller:t.biller??t.provider}));xe({budgetMonthlyCents:St().int().nonnegative()});xe({agentId:P().uuid().optional().nullable(),issueId:P().uuid().optional().nullable(),projectId:P().uuid().optional().nullable(),goalId:P().uuid().optional().nullable(),heartbeatRunId:P().uuid().optional().nullable(),costEventId:P().uuid().optional().nullable(),billingCode:P().optional().nullable(),description:P().max(500).optional().nullable(),eventKind:Me(c2),direction:Me(d2).optional().default("debit"),biller:P().min(1),provider:P().min(1).optional().nullable(),executionAdapterType:Me(_l).optional().nullable(),pricingTier:P().min(1).optional().nullable(),region:P().min(1).optional().nullable(),model:P().min(1).optional().nullable(),quantity:St().int().nonnegative().optional().nullable(),unit:Me(u2).optional().nullable(),amountCents:St().int().nonnegative(),currency:P().length(3).optional().default("USD"),estimated:Ve().optional().default(!1),externalInvoiceId:P().optional().nullable(),metadataJson:mt(P(),gt()).optional().nullable(),occurredAt:P().datetime()}).transform(t=>({...t,currency:t.currency.toUpperCase()}));xe({namespace:P().trim().min(1).max(120).regex(/^[a-zA-Z0-9/_-]+$/).optional()});xe({allowedJoinTypes:Me(h2).default("both"),defaultsPayload:mt(P(),gt()).optional().nullable(),agentMessage:P().max(4e3).optional().nullable()});xe({agentMessage:P().max(4e3).optional().nullable()});xe({requestType:Me(Uv),agentName:P().min(1).max(120).optional(),adapterType:Me(_l).optional(),capabilities:P().max(4e3).optional().nullable(),agentDefaultsPayload:mt(P(),gt()).optional().nullable(),responsesWebhookUrl:P().max(4e3).optional().nullable(),responsesWebhookMethod:P().max(32).optional().nullable(),responsesWebhookHeaders:mt(P(),gt()).optional().nullable(),crewspaceApiUrl:P().max(4e3).optional().nullable(),webhookAuthHeader:P().max(4e3).optional().nullable()});xe({status:Me(g2).optional(),requestType:Me(Uv).optional()});xe({claimSecret:P().min(16).max(256)});const l_=Me(["board","instance_admin_required"]);xe({command:P().min(1).max(240),clientName:P().max(120).optional().nullable(),requestedAccess:l_.default("board"),requestedCompanyId:P().uuid().optional().nullable()});xe({token:P().min(16).max(256)});xe({grants:st(xe({permissionKey:Me(b2),scope:mt(P(),gt()).optional().nullable()}))});xe({companyIds:st(P().uuid()).default([])});const sj=mt(gt()).refine(t=>Object.keys(t).length===0?!0:typeof t.type=="string"||t.$ref!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||t.allOf!==void 0,{message:"Must be a valid JSON Schema object (requires at least a 'type', '$ref', or composition keyword)"}),c_=/^(\*(?:\/[0-9]+)?|[0-9]+(?:-[0-9]+)?(?:\/[0-9]+)?)(?:,(\*(?:\/[0-9]+)?|[0-9]+(?:-[0-9]+)?(?:\/[0-9]+)?))*$/;function d_(t){const n=t.trim();if(!n)return!1;const s=n.split(/\s+/);return s.length!==5?!1:s.every(r=>c_.test(r))}const u_=xe({jobKey:P().min(1),displayName:P().min(1),description:P().optional(),schedule:P().refine(t=>d_(t),{message:"schedule must be a valid 5-field cron expression (e.g. '*/15 * * * *')"}).optional()}),m_=xe({endpointKey:P().min(1),displayName:P().min(1),description:P().optional()}),p_=xe({name:P().min(1),displayName:P().min(1),description:P().min(1),parametersSchema:sj}),x_=xe({type:Me(w2),id:P().min(1),displayName:P().min(1),exportName:P().min(1),entityTypes:st(Me(Kv)).optional(),routePath:P().regex(/^[a-z0-9][a-z0-9-]*$/,{message:"routePath must be a lowercase single-segment slug (letters, numbers, hyphens)"}).optional(),order:St().int().optional()}).superRefine((t,n)=>{["detailTab","taskDetailView","contextMenuItem","commentAnnotation","commentContextMenuItem","projectSidebarItem"].includes(t.type)&&(!t.entityTypes||t.entityTypes.length===0)&&n.addIssue({code:ve.custom,message:`${t.type} slots require at least one entityType`,path:["entityTypes"]}),t.type==="projectSidebarItem"&&t.entityTypes&&!t.entityTypes.includes("project")&&n.addIssue({code:ve.custom,message:'projectSidebarItem slots require entityTypes to include "project"',path:["entityTypes"]}),t.type==="commentAnnotation"&&t.entityTypes&&!t.entityTypes.includes("comment")&&n.addIssue({code:ve.custom,message:'commentAnnotation slots require entityTypes to include "comment"',path:["entityTypes"]}),t.type==="commentContextMenuItem"&&t.entityTypes&&!t.entityTypes.includes("comment")&&n.addIssue({code:ve.custom,message:'commentContextMenuItem slots require entityTypes to include "comment"',path:["entityTypes"]}),t.routePath&&t.type!=="page"&&n.addIssue({code:ve.custom,message:"routePath is only supported for page slots",path:["routePath"]}),t.routePath&&N2.includes(t.routePath)&&n.addIssue({code:ve.custom,message:`routePath "${t.routePath}" is reserved by the host`,path:["routePath"]})}),f_=["detailTab","taskDetailView","contextMenuItem","commentAnnotation","commentContextMenuItem","projectSidebarItem"],h_={hostInline:["inline","compact","default"],hostOverlay:["compact","default","wide","full"],hostRoute:["default","wide","full"],external:[],iframe:["compact","default","wide","full"]},g_=xe({type:Me(C2),target:P().min(1),params:mt(gt()).optional()}).superRefine((t,n)=>{t.type==="performAction"&&t.target.includes("/")&&n.addIssue({code:ve.custom,message:"performAction launchers must target an action key, not a route or URL",path:["target"]}),t.type==="navigate"&&/^https?:\/\//.test(t.target)&&n.addIssue({code:ve.custom,message:"navigate launchers must target a host route, not an absolute URL",path:["target"]})}),b_=xe({environment:Me(S2),bounds:Me(Bv).optional()}).superRefine((t,n)=>{if(!t.bounds)return;h_[t.environment].includes(t.bounds)||n.addIssue({code:ve.custom,message:`bounds "${t.bounds}" is not supported for render environment "${t.environment}"`,path:["bounds"]})}),Of=xe({id:P().min(1),displayName:P().min(1),description:P().optional(),placementZone:Me(k2),exportName:P().min(1).optional(),entityTypes:st(Me(Kv)).optional(),order:St().int().optional(),action:g_,render:b_.optional()}).superRefine((t,n)=>{var s,r;f_.some(a=>a===t.placementZone)&&(!t.entityTypes||t.entityTypes.length===0)&&n.addIssue({code:ve.custom,message:`${t.placementZone} launchers require at least one entityType`,path:["entityTypes"]}),t.placementZone==="projectSidebarItem"&&t.entityTypes&&!t.entityTypes.includes("project")&&n.addIssue({code:ve.custom,message:'projectSidebarItem launchers require entityTypes to include "project"',path:["entityTypes"]}),t.action.type==="performAction"&&t.render&&n.addIssue({code:ve.custom,message:"performAction launchers cannot declare render hints",path:["render"]}),["openModal","openDrawer","openPopover"].includes(t.action.type)&&!t.render&&n.addIssue({code:ve.custom,message:`${t.action.type} launchers require render metadata`,path:["render"]}),t.action.type==="openModal"&&((s=t.render)==null?void 0:s.environment)==="hostInline"&&n.addIssue({code:ve.custom,message:"openModal launchers cannot use the hostInline render environment",path:["render","environment"]}),t.action.type==="openDrawer"&&t.render&&!["hostOverlay","iframe"].includes(t.render.environment)&&n.addIssue({code:ve.custom,message:"openDrawer launchers must use hostOverlay or iframe render environments",path:["render","environment"]}),t.action.type==="openPopover"&&((r=t.render)==null?void 0:r.environment)==="hostRoute"&&n.addIssue({code:ve.custom,message:"openPopover launchers cannot use the hostRoute render environment",path:["render","environment"]})});xe({id:P().min(1).regex(/^[a-z0-9][a-z0-9._-]*$/,"Plugin id must start with a lowercase alphanumeric and contain only lowercase letters, digits, dots, hyphens, or underscores"),apiVersion:ks(1),version:P().min(1).regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/,"Version must follow semver (e.g. 1.0.0 or 1.0.0-beta.1)"),displayName:P().min(1).max(100),description:P().min(1).max(500),author:P().min(1).max(200),categories:st(Me(v2)).min(1),minimumHostVersion:P().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/,"minimumHostVersion must follow semver (e.g. 1.0.0)").optional(),minimumCrewSpaceVersion:P().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/,"minimumCrewSpaceVersion must follow semver (e.g. 1.0.0)").optional(),capabilities:st(Me(j2)).min(1),entrypoints:xe({worker:P().min(1),ui:P().min(1).optional()}),instanceConfigSchema:sj.optional(),jobs:st(u_).optional(),webhooks:st(m_).optional(),tools:st(p_).optional(),launchers:st(Of).optional(),ui:xe({slots:st(x_).min(1).optional(),launchers:st(Of).optional()}).optional()}).superRefine((t,n)=>{var o,i,l,u,d,m;const s=(((i=(o=t.ui)==null?void 0:o.slots)==null?void 0:i.length)??0)>0,r=(((u=(l=t.ui)==null?void 0:l.launchers)==null?void 0:u.length)??0)>0;if((s||r)&&!t.entrypoints.ui&&n.addIssue({code:ve.custom,message:"entrypoints.ui is required when ui.slots or ui.launchers are declared",path:["entrypoints","ui"]}),t.minimumHostVersion&&t.minimumCrewSpaceVersion&&t.minimumHostVersion!==t.minimumCrewSpaceVersion&&n.addIssue({code:ve.custom,message:"minimumHostVersion and minimumCrewSpaceVersion must match when both are declared",path:["minimumHostVersion"]}),t.tools&&t.tools.length>0&&(t.capabilities.includes("agent.tools.register")||n.addIssue({code:ve.custom,message:"Capability 'agent.tools.register' is required when tools are declared",path:["capabilities"]})),t.jobs&&t.jobs.length>0&&(t.capabilities.includes("jobs.schedule")||n.addIssue({code:ve.custom,message:"Capability 'jobs.schedule' is required when jobs are declared",path:["capabilities"]})),t.webhooks&&t.webhooks.length>0&&(t.capabilities.includes("webhooks.receive")||n.addIssue({code:ve.custom,message:"Capability 'webhooks.receive' is required when webhooks are declared",path:["capabilities"]})),t.jobs){const p=t.jobs.map(f=>f.jobKey),x=p.filter((f,h)=>p.indexOf(f)!==h);x.length>0&&n.addIssue({code:ve.custom,message:`Duplicate job keys: ${[...new Set(x)].join(", ")}`,path:["jobs"]})}if(t.webhooks){const p=t.webhooks.map(f=>f.endpointKey),x=p.filter((f,h)=>p.indexOf(f)!==h);x.length>0&&n.addIssue({code:ve.custom,message:`Duplicate webhook endpoint keys: ${[...new Set(x)].join(", ")}`,path:["webhooks"]})}if(t.tools){const p=t.tools.map(f=>f.name),x=p.filter((f,h)=>p.indexOf(f)!==h);x.length>0&&n.addIssue({code:ve.custom,message:`Duplicate tool names: ${[...new Set(x)].join(", ")}`,path:["tools"]})}if(t.ui&&t.ui.slots){const p=t.ui.slots.map(f=>f.id),x=p.filter((f,h)=>p.indexOf(f)!==h);x.length>0&&n.addIssue({code:ve.custom,message:`Duplicate UI slot ids: ${[...new Set(x)].join(", ")}`,path:["ui","slots"]})}const a=[...t.launchers??[],...((d=t.ui)==null?void 0:d.launchers)??[]];if(a.length>0){const p=a.map(f=>f.id),x=p.filter((f,h)=>p.indexOf(f)!==h);x.length>0&&n.addIssue({code:ve.custom,message:`Duplicate launcher ids: ${[...new Set(x)].join(", ")}`,path:(m=t.ui)!=null&&m.launchers?["ui","launchers"]:["launchers"]})}});xe({packageName:P().min(1),version:P().min(1).optional(),packagePath:P().min(1).optional()});xe({configJson:mt(gt())});xe({configJson:mt(gt())});xe({status:Me(y2),lastError:P().nullable().optional()});xe({removeData:Ve().optional().default(!1)});xe({scopeKind:Me(lx),scopeId:P().min(1).optional(),namespace:P().min(1).optional(),stateKey:P().min(1)});xe({scopeKind:Me(lx),scopeId:P().min(1).optional(),namespace:P().min(1).optional(),stateKey:P().min(1),value:gt()});xe({scopeKind:Me(lx).optional(),scopeId:P().min(1).optional(),namespace:P().min(1).optional()});const y_=/[^a-z0-9]+/g,v_=/^-+|-+$/g,j_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function qd(t){return typeof t!="string"?!1:j_.test(t.trim())}function dl(t){if(typeof t!="string")return null;const n=t.trim().toLowerCase().replace(y_,"-").replace(v_,"");return n.length>0?n:null}function w_(t,n){return dl(t)??dl(n)??"agent"}const N_=/[^a-z0-9]+/g,k_=/^-+|-+$/g,C_=/[^\x00-\x7F]/,S_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Pm(t){if(typeof t!="string")return null;const n=t.trim().toLowerCase().replace(N_,"-").replace(k_,"");return n.length>0?n:null}function rj(t){return typeof t!="string"?!1:C_.test(t)}function I_(t){return typeof t!="string"||!S_.test(t.trim())?null:t.trim().replace(/-/g,"").slice(0,8).toLowerCase()}function mx(t,n){const s=Pm(t);if(s&&!rj(t))return s;const r=I_(n);return s&&r?`${s}-${r}`:r||(s??Pm(n)??"project")}const Mm="project://",$m="agent://",__=/^[0-9a-f]{6}$/i,A_=/^[0-9a-f]{3}$/i,E_=/^#[0-9a-f]{6}$/i,T_=/^#[0-9a-f]{3}$/i,R_=/^[a-z0-9-]+$/i;function aj(t){if(!t)return null;const n=t.trim();if(!n)return null;if(E_.test(n))return n.toLowerCase();if(__.test(n))return`#${n.toLowerCase()}`;if(T_.test(n)){const s=n.slice(1).toLowerCase();return`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}`}if(A_.test(n)){const s=n.toLowerCase();return`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}`}return null}function oj(t,n){const s=t.trim(),r=aj(n??null);return r?`${Mm}${s}?c=${encodeURIComponent(r.slice(1))}`:`${Mm}${s}`}function P_(t){if(!t.startsWith(Mm))return null;let n;try{n=new URL(t)}catch{return null}if(n.protocol!=="project:")return null;const s=`${n.hostname}${n.pathname}`.replace(/^\/+/,"").trim();if(!s)return null;const r=aj(n.searchParams.get("c")??n.searchParams.get("color"));return{projectId:s,color:r}}function ij(t,n){const s=t.trim(),r=lj(n??null);return r?`${$m}${s}?i=${encodeURIComponent(r)}`:`${$m}${s}`}function M_(t){if(!t.startsWith($m))return null;let n;try{n=new URL(t)}catch{return null}if(n.protocol!=="agent:")return null;const s=`${n.hostname}${n.pathname}`.replace(/^\/+/,"").trim();return s?{agentId:s,icon:lj(n.searchParams.get("i")??n.searchParams.get("icon"))}:null}function lj(t){if(!t)return null;const n=t.trim().toLowerCase();return!n||!R_.test(n)?null:n}const $_=xe({version:ks(1),updatedAt:P(),source:Me(["onboard","configure","doctor"])}),D_=xe({provider:Me(["claude","openai"]),apiKey:P().optional()}),O_=xe({enabled:Ve().default(!0),intervalMinutes:St().int().min(1).max(10080).default(60),retentionDays:St().int().min(1).max(3650).default(30),dir:P().default("~/.crewspace/instances/default/data/backups")}),L_=xe({mode:Me(["embedded-postgres","postgres"]).default("embedded-postgres"),connectionString:P().optional(),embeddedPostgresDataDir:P().default("~/.crewspace/instances/default/db"),embeddedPostgresPort:St().int().min(1).max(65535).default(54329),backup:O_.default({enabled:!0,intervalMinutes:60,retentionDays:30,dir:"~/.crewspace/instances/default/data/backups"})}),F_=xe({mode:Me(["file","cloud"]),logDir:P().default("~/.crewspace/instances/default/logs")}),q_=xe({deploymentMode:Me(ZI).default("local_trusted"),exposure:Me(YI).default("private"),host:P().default("127.0.0.1"),port:St().int().min(1).max(65535).default(3100),allowedHostnames:st(P().min(1)).default([]),serveUi:Ve().default(!0)}),U_=xe({baseUrlMode:Me(XI).default("auto"),publicBaseUrl:P().url().optional(),disableSignUp:Ve().default(!1)}),B_=xe({baseDir:P().default("~/.crewspace/instances/default/data/storage")}),K_=xe({bucket:P().min(1).default("crewspace"),region:P().min(1).default("us-east-1"),endpoint:P().optional(),prefix:P().default(""),forcePathStyle:Ve().default(!1)}),z_=xe({provider:Me(i2).default("local_disk"),localDisk:B_.default({baseDir:"~/.crewspace/instances/default/data/storage"}),s3:K_.default({bucket:"crewspace",region:"us-east-1",prefix:"",forcePathStyle:!1})}),W_=xe({keyFilePath:P().default("~/.crewspace/instances/default/secrets/master.key")}),H_=xe({provider:Me(qv).default("local_encrypted"),strictMode:Ve().default(!1),localEncrypted:W_.default({keyFilePath:"~/.crewspace/instances/default/secrets/master.key"})});xe({$meta:$_,llm:D_.optional(),database:L_,logging:F_,server:q_,auth:U_.default({baseUrlMode:"auto",disableSignUp:!1}),storage:z_.default({provider:"local_disk",localDisk:{baseDir:"~/.crewspace/instances/default/data/storage"},s3:{bucket:"crewspace",region:"us-east-1",prefix:"",forcePathStyle:!1}}),secrets:H_.default({provider:"local_encrypted",strictMode:!1,localEncrypted:{keyFilePath:"~/.crewspace/instances/default/secrets/master.key"}})}).superRefine((t,n)=>{if(t.server.deploymentMode==="local_trusted"){t.server.exposure!=="private"&&n.addIssue({code:ve.custom,message:"server.exposure must be private when deploymentMode is local_trusted",path:["server","exposure"]});return}t.auth.baseUrlMode==="explicit"&&!t.auth.publicBaseUrl&&n.addIssue({code:ve.custom,message:"auth.publicBaseUrl is required when auth.baseUrlMode is explicit",path:["auth","publicBaseUrl"]}),t.server.exposure==="public"&&t.auth.baseUrlMode!=="explicit"&&n.addIssue({code:ve.custom,message:"auth.baseUrlMode must be explicit when deploymentMode=authenticated and exposure=public",path:["auth","baseUrlMode"]}),t.server.exposure==="public"&&!t.auth.publicBaseUrl&&n.addIssue({code:ve.custom,message:"auth.publicBaseUrl is required when deploymentMode=authenticated and exposure=public",path:["auth","publicBaseUrl"]})});function O(...t){return HC(VC(t))}function ot(t){return`$${(t/100).toFixed(2)}`}function xs(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function js(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function os(t){const n=Date.now(),s=new Date(t).getTime(),r=Math.round((n-s)/1e3);if(r<60)return"just now";const a=Math.round(r/60);if(a<60)return`${a}m ago`;const o=Math.round(a/60);if(o<24)return`${o}h ago`;const i=Math.round(o/24);return i<30?`${i}d ago`:xs(t)}function Et(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function lr(t){return{anthropic:"Anthropic",openai:"OpenAI",openrouter:"OpenRouter",chatgpt:"ChatGPT",google:"Google",cursor:"Cursor",jetbrains:"JetBrains AI"}[t.toLowerCase()]??t}function px(t){return{metered_api:"Metered API",subscription_included:"Subscription",subscription_overage:"Subscription overage",credits:"Credits",fixed:"Fixed",unknown:"Unknown"}[t]}function xx(t){return{"anthropic-oauth":"Anthropic OAuth","claude-cli":"Claude CLI","codex-rpc":"Codex app server","codex-wham":"ChatGPT WHAM"}[t]??t}function Lf(t){return t==="metered_api"||t==="subscription_included"||t==="subscription_overage"||t==="credits"||t==="fixed"||t==="unknown"?t:null}function Ff(t){if(!t)return 0;for(const n of["costUsd","cost_usd","total_cost_usd"]){const s=t[n];if(typeof s=="number"&&Number.isFinite(s))return s}return 0}function cj(t,n=null){return(Lf(t==null?void 0:t.billingType)??Lf(n==null?void 0:n.billingType))==="subscription_included"?0:Ff(t)||Ff(n)}function dj(t){return{inference_charge:"Inference charge",platform_fee:"Platform fee",credit_purchase:"Credit purchase",credit_refund:"Credit refund",credit_expiry:"Credit expiry",byok_fee:"BYOK fee",gateway_overhead:"Gateway overhead",log_storage_charge:"Log storage",logpush_charge:"Logpush",provisioned_capacity_charge:"Provisioned capacity",training_charge:"Training",custom_model_import_charge:"Custom model import",custom_model_storage_charge:"Custom model storage",manual_adjustment:"Manual adjustment"}[t]}function V_(t){return t==="credit"?"Credit":"Debit"}function Bc(t){return`/issues/${t.identifier??t.id}`}function so(t){return t.urlKey??w_(t.name,t.id)}function Na(t){return`/agents/${so(t)}`}function Al(t){const n=t.urlKey??mx(t.name,t.id);return n===Pm(t.name)&&rj(t.name)?t.id:n}function El(t){return`/projects/${Al(t)}`}function Ud(t,n){return`${El(t)}/workspaces/${n}`}const Q_=Cp("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[color,background-color,border-color,box-shadow,opacity] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-9 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-10","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-9","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function G({className:t,variant:n="default",size:s="default",asChild:r=!1,...a}){const o=r?gp:"button";return e.jsx(o,{"data-slot":"button","data-variant":n,"data-size":s,className:O(Q_({variant:n,size:s,className:t})),...a})}function ai(t){return c.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",...t,children:c.createElement("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}function G_(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return c.useMemo(()=>r=>{n.forEach(a=>a(r))},n)}const Bd=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function hi(t){const n=Object.prototype.toString.call(t);return n==="[object Window]"||n==="[object global]"}function fx(t){return"nodeType"in t}function gs(t){var n,s;return t?hi(t)?t:fx(t)&&(n=(s=t.ownerDocument)==null?void 0:s.defaultView)!=null?n:window:window}function hx(t){const{Document:n}=gs(t);return t instanceof n}function Tl(t){return hi(t)?!1:t instanceof gs(t).HTMLElement}function uj(t){return t instanceof gs(t).SVGElement}function gi(t){return t?hi(t)?t.document:fx(t)?hx(t)?t:Tl(t)||uj(t)?t.ownerDocument:document:document:document}const cr=Bd?c.useLayoutEffect:c.useEffect;function Kd(t){const n=c.useRef(t);return cr(()=>{n.current=t}),c.useCallback(function(){for(var s=arguments.length,r=new Array(s),a=0;a<s;a++)r[a]=arguments[a];return n.current==null?void 0:n.current(...r)},[])}function J_(){const t=c.useRef(null),n=c.useCallback((r,a)=>{t.current=setInterval(r,a)},[]),s=c.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[n,s]}function ul(t,n){n===void 0&&(n=[t]);const s=c.useRef(t);return cr(()=>{s.current!==t&&(s.current=t)},n),s}function Rl(t,n){const s=c.useRef();return c.useMemo(()=>{const r=t(s.current);return s.current=r,r},[...n])}function Kc(t){const n=Kd(t),s=c.useRef(null),r=c.useCallback(a=>{a!==s.current&&(n==null||n(a,s.current)),s.current=a},[]);return[s,r]}function zc(t){const n=c.useRef();return c.useEffect(()=>{n.current=t},[t]),n.current}let mu={};function Pl(t,n){return c.useMemo(()=>{if(n)return n;const s=mu[t]==null?0:mu[t]+1;return mu[t]=s,t+"-"+s},[t,n])}function mj(t){return function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),a=1;a<s;a++)r[a-1]=arguments[a];return r.reduce((o,i)=>{const l=Object.entries(i);for(const[u,d]of l){const m=o[u];m!=null&&(o[u]=m+t*d)}return o},{...n})}}const Wo=mj(1),Wc=mj(-1);function Z_(t){return"clientX"in t&&"clientY"in t}function zd(t){if(!t)return!1;const{KeyboardEvent:n}=gs(t.target);return n&&t instanceof n}function Y_(t){if(!t)return!1;const{TouchEvent:n}=gs(t.target);return n&&t instanceof n}function Hc(t){if(Y_(t)){if(t.touches&&t.touches.length){const{clientX:n,clientY:s}=t.touches[0];return{x:n,y:s}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:n,clientY:s}=t.changedTouches[0];return{x:n,y:s}}}return Z_(t)?{x:t.clientX,y:t.clientY}:null}const Er=Object.freeze({Translate:{toString(t){if(!t)return;const{x:n,y:s}=t;return"translate3d("+(n?Math.round(n):0)+"px, "+(s?Math.round(s):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:n,scaleY:s}=t;return"scaleX("+n+") scaleY("+s+")"}},Transform:{toString(t){if(t)return[Er.Translate.toString(t),Er.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:n,duration:s,easing:r}=t;return n+" "+s+"ms "+r}}}),qf="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function X_(t){return t.matches(qf)?t:t.querySelector(qf)}const eA={display:"none"};function tA(t){let{id:n,value:s}=t;return Bt.createElement("div",{id:n,style:eA},s)}function nA(t){let{id:n,announcement:s,ariaLiveType:r="assertive"}=t;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Bt.createElement("div",{id:n,style:a,role:"status","aria-live":r,"aria-atomic":!0},s)}function sA(){const[t,n]=c.useState("");return{announce:c.useCallback(r=>{r!=null&&n(r)},[]),announcement:t}}const pj=c.createContext(null);function rA(t){const n=c.useContext(pj);c.useEffect(()=>{if(!n)throw new Error("useDndMonitor must be used within a children of <DndContext>");return n(t)},[t,n])}function aA(){const[t]=c.useState(()=>new Set),n=c.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[c.useCallback(r=>{let{type:a,event:o}=r;t.forEach(i=>{var l;return(l=i[a])==null?void 0:l.call(i,o)})},[t]),n]}const oA={draggable:`
|
|
3
|
+
To pick up a draggable item, press the space bar.
|
|
4
|
+
While dragging, use the arrow keys to move the item.
|
|
5
|
+
Press space again to drop the item in its new position, or press escape to cancel.
|
|
6
|
+
`},iA={onDragStart(t){let{active:n}=t;return"Picked up draggable item "+n.id+"."},onDragOver(t){let{active:n,over:s}=t;return s?"Draggable item "+n.id+" was moved over droppable area "+s.id+".":"Draggable item "+n.id+" is no longer over a droppable area."},onDragEnd(t){let{active:n,over:s}=t;return s?"Draggable item "+n.id+" was dropped over droppable area "+s.id:"Draggable item "+n.id+" was dropped."},onDragCancel(t){let{active:n}=t;return"Dragging was cancelled. Draggable item "+n.id+" was dropped."}};function lA(t){let{announcements:n=iA,container:s,hiddenTextDescribedById:r,screenReaderInstructions:a=oA}=t;const{announce:o,announcement:i}=sA(),l=Pl("DndLiveRegion"),[u,d]=c.useState(!1);if(c.useEffect(()=>{d(!0)},[]),rA(c.useMemo(()=>({onDragStart(p){let{active:x}=p;o(n.onDragStart({active:x}))},onDragMove(p){let{active:x,over:f}=p;n.onDragMove&&o(n.onDragMove({active:x,over:f}))},onDragOver(p){let{active:x,over:f}=p;o(n.onDragOver({active:x,over:f}))},onDragEnd(p){let{active:x,over:f}=p;o(n.onDragEnd({active:x,over:f}))},onDragCancel(p){let{active:x,over:f}=p;o(n.onDragCancel({active:x,over:f}))}}),[o,n])),!u)return null;const m=Bt.createElement(Bt.Fragment,null,Bt.createElement(tA,{id:r,value:a.draggable}),Bt.createElement(nA,{id:l,announcement:i}));return s?Lo.createPortal(m,s):m}var Fn;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Fn||(Fn={}));function Vc(){}function gx(t,n){return c.useMemo(()=>({sensor:t,options:n??{}}),[t,n])}function bx(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return c.useMemo(()=>[...n].filter(r=>r!=null),[...n])}const dr=Object.freeze({x:0,y:0});function cA(t,n){return Math.sqrt(Math.pow(t.x-n.x,2)+Math.pow(t.y-n.y,2))}function dA(t,n){const s=Hc(t);if(!s)return"0 0";const r={x:(s.x-n.left)/n.width*100,y:(s.y-n.top)/n.height*100};return r.x+"% "+r.y+"%"}function uA(t,n){let{data:{value:s}}=t,{data:{value:r}}=n;return s-r}function mA(t,n){let{data:{value:s}}=t,{data:{value:r}}=n;return r-s}function pA(t,n){if(!t||t.length===0)return null;const[s]=t;return s[n]}function Uf(t,n,s){return n===void 0&&(n=t.left),s===void 0&&(s=t.top),{x:n+t.width*.5,y:s+t.height*.5}}const xj=t=>{let{collisionRect:n,droppableRects:s,droppableContainers:r}=t;const a=Uf(n,n.left,n.top),o=[];for(const i of r){const{id:l}=i,u=s.get(l);if(u){const d=cA(Uf(u),a);o.push({id:l,data:{droppableContainer:i,value:d}})}}return o.sort(uA)};function xA(t,n){const s=Math.max(n.top,t.top),r=Math.max(n.left,t.left),a=Math.min(n.left+n.width,t.left+t.width),o=Math.min(n.top+n.height,t.top+t.height),i=a-r,l=o-s;if(r<a&&s<o){const u=n.width*n.height,d=t.width*t.height,m=i*l,p=m/(u+d-m);return Number(p.toFixed(4))}return 0}const fA=t=>{let{collisionRect:n,droppableRects:s,droppableContainers:r}=t;const a=[];for(const o of r){const{id:i}=o,l=s.get(i);if(l){const u=xA(l,n);u>0&&a.push({id:i,data:{droppableContainer:o,value:u}})}}return a.sort(mA)};function hA(t,n,s){return{...t,scaleX:n&&s?n.width/s.width:1,scaleY:n&&s?n.height/s.height:1}}function fj(t,n){return t&&n?{x:t.left-n.left,y:t.top-n.top}:dr}function gA(t){return function(s){for(var r=arguments.length,a=new Array(r>1?r-1:0),o=1;o<r;o++)a[o-1]=arguments[o];return a.reduce((i,l)=>({...i,top:i.top+t*l.y,bottom:i.bottom+t*l.y,left:i.left+t*l.x,right:i.right+t*l.x}),{...s})}}const bA=gA(1);function hj(t){if(t.startsWith("matrix3d(")){const n=t.slice(9,-1).split(/, /);return{x:+n[12],y:+n[13],scaleX:+n[0],scaleY:+n[5]}}else if(t.startsWith("matrix(")){const n=t.slice(7,-1).split(/, /);return{x:+n[4],y:+n[5],scaleX:+n[0],scaleY:+n[3]}}return null}function yA(t,n,s){const r=hj(n);if(!r)return t;const{scaleX:a,scaleY:o,x:i,y:l}=r,u=t.left-i-(1-a)*parseFloat(s),d=t.top-l-(1-o)*parseFloat(s.slice(s.indexOf(" ")+1)),m=a?t.width/a:t.width,p=o?t.height/o:t.height;return{width:m,height:p,top:d,right:u+m,bottom:d+p,left:u}}const vA={ignoreTransform:!1};function bi(t,n){n===void 0&&(n=vA);let s=t.getBoundingClientRect();if(n.ignoreTransform){const{transform:d,transformOrigin:m}=gs(t).getComputedStyle(t);d&&(s=yA(s,d,m))}const{top:r,left:a,width:o,height:i,bottom:l,right:u}=s;return{top:r,left:a,width:o,height:i,bottom:l,right:u}}function Bf(t){return bi(t,{ignoreTransform:!0})}function jA(t){const n=t.innerWidth,s=t.innerHeight;return{top:0,left:0,right:n,bottom:s,width:n,height:s}}function wA(t,n){return n===void 0&&(n=gs(t).getComputedStyle(t)),n.position==="fixed"}function NA(t,n){n===void 0&&(n=gs(t).getComputedStyle(t));const s=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const o=n[a];return typeof o=="string"?s.test(o):!1})}function yx(t,n){const s=[];function r(a){if(n!=null&&s.length>=n||!a)return s;if(hx(a)&&a.scrollingElement!=null&&!s.includes(a.scrollingElement))return s.push(a.scrollingElement),s;if(!Tl(a)||uj(a)||s.includes(a))return s;const o=gs(t).getComputedStyle(a);return a!==t&&NA(a,o)&&s.push(a),wA(a,o)?s:r(a.parentNode)}return t?r(t):s}function gj(t){const[n]=yx(t,1);return n??null}function pu(t){return!Bd||!t?null:hi(t)?t:fx(t)?hx(t)||t===gi(t).scrollingElement?window:Tl(t)?t:null:null}function bj(t){return hi(t)?t.scrollX:t.scrollLeft}function yj(t){return hi(t)?t.scrollY:t.scrollTop}function Dm(t){return{x:bj(t),y:yj(t)}}var zn;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(zn||(zn={}));function vj(t){return!Bd||!t?!1:t===document.scrollingElement}function jj(t){const n={x:0,y:0},s=vj(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-s.width,y:t.scrollHeight-s.height},a=t.scrollTop<=n.y,o=t.scrollLeft<=n.x,i=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:a,isLeft:o,isBottom:i,isRight:l,maxScroll:r,minScroll:n}}const kA={x:.2,y:.2};function CA(t,n,s,r,a){let{top:o,left:i,right:l,bottom:u}=s;r===void 0&&(r=10),a===void 0&&(a=kA);const{isTop:d,isBottom:m,isLeft:p,isRight:x}=jj(t),f={x:0,y:0},h={x:0,y:0},j={height:n.height*a.y,width:n.width*a.x};return!d&&o<=n.top+j.height?(f.y=zn.Backward,h.y=r*Math.abs((n.top+j.height-o)/j.height)):!m&&u>=n.bottom-j.height&&(f.y=zn.Forward,h.y=r*Math.abs((n.bottom-j.height-u)/j.height)),!x&&l>=n.right-j.width?(f.x=zn.Forward,h.x=r*Math.abs((n.right-j.width-l)/j.width)):!p&&i<=n.left+j.width&&(f.x=zn.Backward,h.x=r*Math.abs((n.left+j.width-i)/j.width)),{direction:f,speed:h}}function SA(t){if(t===document.scrollingElement){const{innerWidth:o,innerHeight:i}=window;return{top:0,left:0,right:o,bottom:i,width:o,height:i}}const{top:n,left:s,right:r,bottom:a}=t.getBoundingClientRect();return{top:n,left:s,right:r,bottom:a,width:t.clientWidth,height:t.clientHeight}}function wj(t){return t.reduce((n,s)=>Wo(n,Dm(s)),dr)}function IA(t){return t.reduce((n,s)=>n+bj(s),0)}function _A(t){return t.reduce((n,s)=>n+yj(s),0)}function Nj(t,n){if(n===void 0&&(n=bi),!t)return;const{top:s,left:r,bottom:a,right:o}=n(t);gj(t)&&(a<=0||o<=0||s>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const AA=[["x",["left","right"],IA],["y",["top","bottom"],_A]];class vx{constructor(n,s){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=yx(s),a=wj(r);this.rect={...n},this.width=n.width,this.height=n.height;for(const[o,i,l]of AA)for(const u of i)Object.defineProperty(this,u,{get:()=>{const d=l(r),m=a[o]-d;return this.rect[u]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class zi{constructor(n){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(s=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...s)})},this.target=n}add(n,s,r){var a;(a=this.target)==null||a.addEventListener(n,s,r),this.listeners.push([n,s,r])}}function EA(t){const{EventTarget:n}=gs(t);return t instanceof n?t:gi(t)}function xu(t,n){const s=Math.abs(t.x),r=Math.abs(t.y);return typeof n=="number"?Math.sqrt(s**2+r**2)>n:"x"in n&&"y"in n?s>n.x&&r>n.y:"x"in n?s>n.x:"y"in n?r>n.y:!1}var Qs;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Qs||(Qs={}));function Kf(t){t.preventDefault()}function TA(t){t.stopPropagation()}var Kt;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(Kt||(Kt={}));const kj={start:[Kt.Space,Kt.Enter],cancel:[Kt.Esc],end:[Kt.Space,Kt.Enter,Kt.Tab]},RA=(t,n)=>{let{currentCoordinates:s}=n;switch(t.code){case Kt.Right:return{...s,x:s.x+25};case Kt.Left:return{...s,x:s.x-25};case Kt.Down:return{...s,y:s.y+25};case Kt.Up:return{...s,y:s.y-25}}};class Cj{constructor(n){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=n;const{event:{target:s}}=n;this.props=n,this.listeners=new zi(gi(s)),this.windowListeners=new zi(gs(s)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Qs.Resize,this.handleCancel),this.windowListeners.add(Qs.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Qs.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:n,onStart:s}=this.props,r=n.node.current;r&&Nj(r),s(dr)}handleKeyDown(n){if(zd(n)){const{active:s,context:r,options:a}=this.props,{keyboardCodes:o=kj,coordinateGetter:i=RA,scrollBehavior:l="smooth"}=a,{code:u}=n;if(o.end.includes(u)){this.handleEnd(n);return}if(o.cancel.includes(u)){this.handleCancel(n);return}const{collisionRect:d}=r.current,m=d?{x:d.left,y:d.top}:dr;this.referenceCoordinates||(this.referenceCoordinates=m);const p=i(n,{active:s,context:r.current,currentCoordinates:m});if(p){const x=Wc(p,m),f={x:0,y:0},{scrollableAncestors:h}=r.current;for(const j of h){const b=n.code,{isTop:g,isRight:y,isLeft:v,isBottom:_,maxScroll:E,minScroll:S}=jj(j),M=SA(j),B={x:Math.min(b===Kt.Right?M.right-M.width/2:M.right,Math.max(b===Kt.Right?M.left:M.left+M.width/2,p.x)),y:Math.min(b===Kt.Down?M.bottom-M.height/2:M.bottom,Math.max(b===Kt.Down?M.top:M.top+M.height/2,p.y))},k=b===Kt.Right&&!y||b===Kt.Left&&!v,L=b===Kt.Down&&!_||b===Kt.Up&&!g;if(k&&B.x!==p.x){const $=j.scrollLeft+x.x,C=b===Kt.Right&&$<=E.x||b===Kt.Left&&$>=S.x;if(C&&!x.y){j.scrollTo({left:$,behavior:l});return}C?f.x=j.scrollLeft-$:f.x=b===Kt.Right?j.scrollLeft-E.x:j.scrollLeft-S.x,f.x&&j.scrollBy({left:-f.x,behavior:l});break}else if(L&&B.y!==p.y){const $=j.scrollTop+x.y,C=b===Kt.Down&&$<=E.y||b===Kt.Up&&$>=S.y;if(C&&!x.x){j.scrollTo({top:$,behavior:l});return}C?f.y=j.scrollTop-$:f.y=b===Kt.Down?j.scrollTop-E.y:j.scrollTop-S.y,f.y&&j.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(n,Wo(Wc(p,this.referenceCoordinates),f))}}}handleMove(n,s){const{onMove:r}=this.props;n.preventDefault(),r(s)}handleEnd(n){const{onEnd:s}=this.props;n.preventDefault(),this.detach(),s()}handleCancel(n){const{onCancel:s}=this.props;n.preventDefault(),this.detach(),s()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Cj.activators=[{eventName:"onKeyDown",handler:(t,n,s)=>{let{keyboardCodes:r=kj,onActivation:a}=n,{active:o}=s;const{code:i}=t.nativeEvent;if(r.start.includes(i)){const l=o.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),a==null||a({event:t.nativeEvent}),!0)}return!1}}];function zf(t){return!!(t&&"distance"in t)}function Wf(t){return!!(t&&"delay"in t)}class jx{constructor(n,s,r){var a;r===void 0&&(r=EA(n.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=n,this.events=s;const{event:o}=n,{target:i}=o;this.props=n,this.events=s,this.document=gi(i),this.documentListeners=new zi(this.document),this.listeners=new zi(r),this.windowListeners=new zi(gs(i)),this.initialCoordinates=(a=Hc(o))!=null?a:dr,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:n,props:{options:{activationConstraint:s,bypassActivationConstraint:r}}}=this;if(this.listeners.add(n.move.name,this.handleMove,{passive:!1}),this.listeners.add(n.end.name,this.handleEnd),n.cancel&&this.listeners.add(n.cancel.name,this.handleCancel),this.windowListeners.add(Qs.Resize,this.handleCancel),this.windowListeners.add(Qs.DragStart,Kf),this.windowListeners.add(Qs.VisibilityChange,this.handleCancel),this.windowListeners.add(Qs.ContextMenu,Kf),this.documentListeners.add(Qs.Keydown,this.handleKeydown),s){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Wf(s)){this.timeoutId=setTimeout(this.handleStart,s.delay),this.handlePending(s);return}if(zf(s)){this.handlePending(s);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(n,s){const{active:r,onPending:a}=this.props;a(r,n,this.initialCoordinates,s)}handleStart(){const{initialCoordinates:n}=this,{onStart:s}=this.props;n&&(this.activated=!0,this.documentListeners.add(Qs.Click,TA,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Qs.SelectionChange,this.removeTextSelection),s(n))}handleMove(n){var s;const{activated:r,initialCoordinates:a,props:o}=this,{onMove:i,options:{activationConstraint:l}}=o;if(!a)return;const u=(s=Hc(n))!=null?s:dr,d=Wc(a,u);if(!r&&l){if(zf(l)){if(l.tolerance!=null&&xu(d,l.tolerance))return this.handleCancel();if(xu(d,l.distance))return this.handleStart()}if(Wf(l)&&xu(d,l.tolerance))return this.handleCancel();this.handlePending(l,d);return}n.cancelable&&n.preventDefault(),i(u)}handleEnd(){const{onAbort:n,onEnd:s}=this.props;this.detach(),this.activated||n(this.props.active),s()}handleCancel(){const{onAbort:n,onCancel:s}=this.props;this.detach(),this.activated||n(this.props.active),s()}handleKeydown(n){n.code===Kt.Esc&&this.handleCancel()}removeTextSelection(){var n;(n=this.document.getSelection())==null||n.removeAllRanges()}}const PA={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class wx extends jx{constructor(n){const{event:s}=n,r=gi(s.target);super(n,PA,r)}}wx.activators=[{eventName:"onPointerDown",handler:(t,n)=>{let{nativeEvent:s}=t,{onActivation:r}=n;return!s.isPrimary||s.button!==0?!1:(r==null||r({event:s}),!0)}}];const MA={move:{name:"mousemove"},end:{name:"mouseup"}};var Om;(function(t){t[t.RightClick=2]="RightClick"})(Om||(Om={}));class Nx extends jx{constructor(n){super(n,MA,gi(n.event.target))}}Nx.activators=[{eventName:"onMouseDown",handler:(t,n)=>{let{nativeEvent:s}=t,{onActivation:r}=n;return s.button===Om.RightClick?!1:(r==null||r({event:s}),!0)}}];const fu={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class $A extends jx{constructor(n){super(n,fu)}static setup(){return window.addEventListener(fu.move.name,n,{capture:!1,passive:!1}),function(){window.removeEventListener(fu.move.name,n)};function n(){}}}$A.activators=[{eventName:"onTouchStart",handler:(t,n)=>{let{nativeEvent:s}=t,{onActivation:r}=n;const{touches:a}=s;return a.length>1?!1:(r==null||r({event:s}),!0)}}];var Wi;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(Wi||(Wi={}));var Qc;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(Qc||(Qc={}));function DA(t){let{acceleration:n,activator:s=Wi.Pointer,canScroll:r,draggingRect:a,enabled:o,interval:i=5,order:l=Qc.TreeOrder,pointerCoordinates:u,scrollableAncestors:d,scrollableAncestorRects:m,delta:p,threshold:x}=t;const f=LA({delta:p,disabled:!o}),[h,j]=J_(),b=c.useRef({x:0,y:0}),g=c.useRef({x:0,y:0}),y=c.useMemo(()=>{switch(s){case Wi.Pointer:return u?{top:u.y,bottom:u.y,left:u.x,right:u.x}:null;case Wi.DraggableRect:return a}},[s,a,u]),v=c.useRef(null),_=c.useCallback(()=>{const S=v.current;if(!S)return;const M=b.current.x*g.current.x,B=b.current.y*g.current.y;S.scrollBy(M,B)},[]),E=c.useMemo(()=>l===Qc.TreeOrder?[...d].reverse():d,[l,d]);c.useEffect(()=>{if(!o||!d.length||!y){j();return}for(const S of E){if((r==null?void 0:r(S))===!1)continue;const M=d.indexOf(S),B=m[M];if(!B)continue;const{direction:k,speed:L}=CA(S,B,y,n,x);for(const $ of["x","y"])f[$][k[$]]||(L[$]=0,k[$]=0);if(L.x>0||L.y>0){j(),v.current=S,h(_,i),b.current=L,g.current=k;return}}b.current={x:0,y:0},g.current={x:0,y:0},j()},[n,_,r,j,o,i,JSON.stringify(y),JSON.stringify(f),h,d,E,m,JSON.stringify(x)])}const OA={x:{[zn.Backward]:!1,[zn.Forward]:!1},y:{[zn.Backward]:!1,[zn.Forward]:!1}};function LA(t){let{delta:n,disabled:s}=t;const r=zc(n);return Rl(a=>{if(s||!r||!a)return OA;const o={x:Math.sign(n.x-r.x),y:Math.sign(n.y-r.y)};return{x:{[zn.Backward]:a.x[zn.Backward]||o.x===-1,[zn.Forward]:a.x[zn.Forward]||o.x===1},y:{[zn.Backward]:a.y[zn.Backward]||o.y===-1,[zn.Forward]:a.y[zn.Forward]||o.y===1}}},[s,n,r])}function FA(t,n){const s=n!=null?t.get(n):void 0,r=s?s.node.current:null;return Rl(a=>{var o;return n==null?null:(o=r??a)!=null?o:null},[r,n])}function qA(t,n){return c.useMemo(()=>t.reduce((s,r)=>{const{sensor:a}=r,o=a.activators.map(i=>({eventName:i.eventName,handler:n(i.handler,r)}));return[...s,...o]},[]),[t,n])}var ml;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(ml||(ml={}));var Lm;(function(t){t.Optimized="optimized"})(Lm||(Lm={}));const Hf=new Map;function UA(t,n){let{dragging:s,dependencies:r,config:a}=n;const[o,i]=c.useState(null),{frequency:l,measure:u,strategy:d}=a,m=c.useRef(t),p=b(),x=ul(p),f=c.useCallback(function(g){g===void 0&&(g=[]),!x.current&&i(y=>y===null?g:y.concat(g.filter(v=>!y.includes(v))))},[x]),h=c.useRef(null),j=Rl(g=>{if(p&&!s)return Hf;if(!g||g===Hf||m.current!==t||o!=null){const y=new Map;for(let v of t){if(!v)continue;if(o&&o.length>0&&!o.includes(v.id)&&v.rect.current){y.set(v.id,v.rect.current);continue}const _=v.node.current,E=_?new vx(u(_),_):null;v.rect.current=E,E&&y.set(v.id,E)}return y}return g},[t,o,s,p,u]);return c.useEffect(()=>{m.current=t},[t]),c.useEffect(()=>{p||f()},[s,p]),c.useEffect(()=>{o&&o.length>0&&i(null)},[JSON.stringify(o)]),c.useEffect(()=>{p||typeof l!="number"||h.current!==null||(h.current=setTimeout(()=>{f(),h.current=null},l))},[l,p,f,...r]),{droppableRects:j,measureDroppableContainers:f,measuringScheduled:o!=null};function b(){switch(d){case ml.Always:return!1;case ml.BeforeDragging:return s;default:return!s}}}function kx(t,n){return Rl(s=>t?s||(typeof n=="function"?n(t):t):null,[n,t])}function BA(t,n){return kx(t,n)}function KA(t){let{callback:n,disabled:s}=t;const r=Kd(n),a=c.useMemo(()=>{if(s||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(r)},[r,s]);return c.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function Wd(t){let{callback:n,disabled:s}=t;const r=Kd(n),a=c.useMemo(()=>{if(s||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(r)},[s]);return c.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function zA(t){return new vx(bi(t),t)}function Vf(t,n,s){n===void 0&&(n=zA);const[r,a]=c.useState(null);function o(){a(u=>{if(!t)return null;if(t.isConnected===!1){var d;return(d=u??s)!=null?d:null}const m=n(t);return JSON.stringify(u)===JSON.stringify(m)?u:m})}const i=KA({callback(u){if(t)for(const d of u){const{type:m,target:p}=d;if(m==="childList"&&p instanceof HTMLElement&&p.contains(t)){o();break}}}}),l=Wd({callback:o});return cr(()=>{o(),t?(l==null||l.observe(t),i==null||i.observe(document.body,{childList:!0,subtree:!0})):(l==null||l.disconnect(),i==null||i.disconnect())},[t]),r}function WA(t){const n=kx(t);return fj(t,n)}const Qf=[];function HA(t){const n=c.useRef(t),s=Rl(r=>t?r&&r!==Qf&&t&&n.current&&t.parentNode===n.current.parentNode?r:yx(t):Qf,[t]);return c.useEffect(()=>{n.current=t},[t]),s}function VA(t){const[n,s]=c.useState(null),r=c.useRef(t),a=c.useCallback(o=>{const i=pu(o.target);i&&s(l=>l?(l.set(i,Dm(i)),new Map(l)):null)},[]);return c.useEffect(()=>{const o=r.current;if(t!==o){i(o);const l=t.map(u=>{const d=pu(u);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,Dm(d)]):null}).filter(u=>u!=null);s(l.length?new Map(l):null),r.current=t}return()=>{i(t),i(o)};function i(l){l.forEach(u=>{const d=pu(u);d==null||d.removeEventListener("scroll",a)})}},[a,t]),c.useMemo(()=>t.length?n?Array.from(n.values()).reduce((o,i)=>Wo(o,i),dr):wj(t):dr,[t,n])}function Gf(t,n){n===void 0&&(n=[]);const s=c.useRef(null);return c.useEffect(()=>{s.current=null},n),c.useEffect(()=>{const r=t!==dr;r&&!s.current&&(s.current=t),!r&&s.current&&(s.current=null)},[t]),s.current?Wc(t,s.current):dr}function QA(t){c.useEffect(()=>{if(!Bd)return;const n=t.map(s=>{let{sensor:r}=s;return r.setup==null?void 0:r.setup()});return()=>{for(const s of n)s==null||s()}},t.map(n=>{let{sensor:s}=n;return s}))}function GA(t,n){return c.useMemo(()=>t.reduce((s,r)=>{let{eventName:a,handler:o}=r;return s[a]=i=>{o(i,n)},s},{}),[t,n])}function Sj(t){return c.useMemo(()=>t?jA(t):null,[t])}const Jf=[];function JA(t,n){n===void 0&&(n=bi);const[s]=t,r=Sj(s?gs(s):null),[a,o]=c.useState(Jf);function i(){o(()=>t.length?t.map(u=>vj(u)?r:new vx(n(u),u)):Jf)}const l=Wd({callback:i});return cr(()=>{l==null||l.disconnect(),i(),t.forEach(u=>l==null?void 0:l.observe(u))},[t]),a}function Ij(t){if(!t)return null;if(t.children.length>1)return t;const n=t.children[0];return Tl(n)?n:t}function ZA(t){let{measure:n}=t;const[s,r]=c.useState(null),a=c.useCallback(d=>{for(const{target:m}of d)if(Tl(m)){r(p=>{const x=n(m);return p?{...p,width:x.width,height:x.height}:x});break}},[n]),o=Wd({callback:a}),i=c.useCallback(d=>{const m=Ij(d);o==null||o.disconnect(),m&&(o==null||o.observe(m)),r(m?n(m):null)},[n,o]),[l,u]=Kc(i);return c.useMemo(()=>({nodeRef:l,rect:s,setRef:u}),[s,l,u])}const YA=[{sensor:wx,options:{}},{sensor:Cj,options:{}}],XA={current:{}},fc={draggable:{measure:Bf},droppable:{measure:Bf,strategy:ml.WhileDragging,frequency:Lm.Optimized},dragOverlay:{measure:bi}};class Hi extends Map{get(n){var s;return n!=null&&(s=super.get(n))!=null?s:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(n=>{let{disabled:s}=n;return!s})}getNodeFor(n){var s,r;return(s=(r=this.get(n))==null?void 0:r.node.current)!=null?s:void 0}}const eE={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Hi,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Vc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:fc,measureDroppableContainers:Vc,windowRect:null,measuringScheduled:!1},_j={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Vc,draggableNodes:new Map,over:null,measureDroppableContainers:Vc},Ml=c.createContext(_j),Aj=c.createContext(eE);function tE(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Hi}}}function nE(t,n){switch(n.type){case Fn.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:n.initialCoordinates,active:n.active}};case Fn.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:n.coordinates.x-t.draggable.initialCoordinates.x,y:n.coordinates.y-t.draggable.initialCoordinates.y}}};case Fn.DragEnd:case Fn.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Fn.RegisterDroppable:{const{element:s}=n,{id:r}=s,a=new Hi(t.droppable.containers);return a.set(r,s),{...t,droppable:{...t.droppable,containers:a}}}case Fn.SetDroppableDisabled:{const{id:s,key:r,disabled:a}=n,o=t.droppable.containers.get(s);if(!o||r!==o.key)return t;const i=new Hi(t.droppable.containers);return i.set(s,{...o,disabled:a}),{...t,droppable:{...t.droppable,containers:i}}}case Fn.UnregisterDroppable:{const{id:s,key:r}=n,a=t.droppable.containers.get(s);if(!a||r!==a.key)return t;const o=new Hi(t.droppable.containers);return o.delete(s),{...t,droppable:{...t.droppable,containers:o}}}default:return t}}function sE(t){let{disabled:n}=t;const{active:s,activatorEvent:r,draggableNodes:a}=c.useContext(Ml),o=zc(r),i=zc(s==null?void 0:s.id);return c.useEffect(()=>{if(!n&&!r&&o&&i!=null){if(!zd(o)||document.activeElement===o.target)return;const l=a.get(i);if(!l)return;const{activatorNode:u,node:d}=l;if(!u.current&&!d.current)return;requestAnimationFrame(()=>{for(const m of[u.current,d.current]){if(!m)continue;const p=X_(m);if(p){p.focus();break}}})}},[r,n,a,i,o]),null}function Ej(t,n){let{transform:s,...r}=n;return t!=null&&t.length?t.reduce((a,o)=>o({transform:a,...r}),s):s}function rE(t){return c.useMemo(()=>({draggable:{...fc.draggable,...t==null?void 0:t.draggable},droppable:{...fc.droppable,...t==null?void 0:t.droppable},dragOverlay:{...fc.dragOverlay,...t==null?void 0:t.dragOverlay}}),[t==null?void 0:t.draggable,t==null?void 0:t.droppable,t==null?void 0:t.dragOverlay])}function aE(t){let{activeNode:n,measure:s,initialRect:r,config:a=!0}=t;const o=c.useRef(!1),{x:i,y:l}=typeof a=="boolean"?{x:a,y:a}:a;cr(()=>{if(!i&&!l||!n){o.current=!1;return}if(o.current||!r)return;const d=n==null?void 0:n.node.current;if(!d||d.isConnected===!1)return;const m=s(d),p=fj(m,r);if(i||(p.x=0),l||(p.y=0),o.current=!0,Math.abs(p.x)>0||Math.abs(p.y)>0){const x=gj(d);x&&x.scrollBy({top:p.y,left:p.x})}},[n,i,l,r,s])}const Hd=c.createContext({...dr,scaleX:1,scaleY:1});var la;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(la||(la={}));const Cx=c.memo(function(n){var s,r,a,o;let{id:i,accessibility:l,autoScroll:u=!0,children:d,sensors:m=YA,collisionDetection:p=fA,measuring:x,modifiers:f,...h}=n;const j=c.useReducer(nE,void 0,tE),[b,g]=j,[y,v]=aA(),[_,E]=c.useState(la.Uninitialized),S=_===la.Initialized,{draggable:{active:M,nodes:B,translate:k},droppable:{containers:L}}=b,$=M!=null?B.get(M):null,C=c.useRef({initial:null,translated:null}),I=c.useMemo(()=>{var Ue;return M!=null?{id:M,data:(Ue=$==null?void 0:$.data)!=null?Ue:XA,rect:C}:null},[M,$]),K=c.useRef(null),[T,z]=c.useState(null),[w,F]=c.useState(null),A=ul(h,Object.values(h)),R=Pl("DndDescribedBy",i),Q=c.useMemo(()=>L.getEnabled(),[L]),H=rE(x),{droppableRects:U,measureDroppableContainers:Z,measuringScheduled:V}=UA(Q,{dragging:S,dependencies:[k.x,k.y],config:H.droppable}),W=FA(B,M),J=c.useMemo(()=>w?Hc(w):null,[w]),Y=It(),de=BA(W,H.draggable.measure);aE({activeNode:M!=null?B.get(M):null,config:Y.layoutShiftCompensation,initialRect:de,measure:H.draggable.measure});const fe=Vf(W,H.draggable.measure,de),Ce=Vf(W?W.parentElement:null),le=c.useRef({activatorEvent:null,active:null,activeNode:W,collisionRect:null,collisions:null,droppableRects:U,draggableNodes:B,draggingNode:null,draggingNodeRect:null,droppableContainers:L,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Re=L.getNodeFor((s=le.current.over)==null?void 0:s.id),Pe=ZA({measure:H.dragOverlay.measure}),Fe=(r=Pe.nodeRef.current)!=null?r:W,pe=S?(a=Pe.rect)!=null?a:fe:null,Le=!!(Pe.nodeRef.current&&Pe.rect),q=WA(Le?null:fe),D=Sj(Fe?gs(Fe):null),ie=HA(S?Re??W:null),Ie=JA(ie),ue=Ej(f,{transform:{x:k.x-q.x,y:k.y-q.y,scaleX:1,scaleY:1},activatorEvent:w,active:I,activeNodeRect:fe,containerNodeRect:Ce,draggingNodeRect:pe,over:le.current.over,overlayNodeRect:Pe.rect,scrollableAncestors:ie,scrollableAncestorRects:Ie,windowRect:D}),Be=J?Wo(J,k):null,be=VA(ie),he=Gf(be),Se=Gf(be,[fe]),we=Wo(ue,he),ee=pe?bA(pe,ue):null,me=I&&ee?p({active:I,collisionRect:ee,droppableRects:U,droppableContainers:Q,pointerCoordinates:Be}):null,ye=pA(me,"id"),[Ke,qe]=c.useState(null),se=Le?ue:Wo(ue,Se),ce=hA(se,(o=Ke==null?void 0:Ke.rect)!=null?o:null,fe),Te=c.useRef(null),ae=c.useCallback((Ue,pt)=>{let{sensor:ht,options:ln}=pt;if(K.current==null)return;const yt=B.get(K.current);if(!yt)return;const hn=Ue.nativeEvent,pn=new ht({active:K.current,activeNode:yt,event:hn,options:ln,context:le,onAbort($e){if(!B.get($e))return;const{onDragAbort:He}=A.current,rt={id:$e};He==null||He(rt),y({type:"onDragAbort",event:rt})},onPending($e,Ee,He,rt){if(!B.get($e))return;const{onDragPending:Pt}=A.current,gn={id:$e,constraint:Ee,initialCoordinates:He,offset:rt};Pt==null||Pt(gn),y({type:"onDragPending",event:gn})},onStart($e){const Ee=K.current;if(Ee==null)return;const He=B.get(Ee);if(!He)return;const{onDragStart:rt}=A.current,xt={activatorEvent:hn,active:{id:Ee,data:He.data,rect:C}};Lo.unstable_batchedUpdates(()=>{rt==null||rt(xt),E(la.Initializing),g({type:Fn.DragStart,initialCoordinates:$e,active:Ee}),y({type:"onDragStart",event:xt}),z(Te.current),F(hn)})},onMove($e){g({type:Fn.DragMove,coordinates:$e})},onEnd:re(Fn.DragEnd),onCancel:re(Fn.DragCancel)});Te.current=pn;function re($e){return async function(){const{active:He,collisions:rt,over:xt,scrollAdjustedTranslate:Pt}=le.current;let gn=null;if(He&&Pt){const{cancelDrop:$n}=A.current;gn={activatorEvent:hn,active:He,collisions:rt,delta:Pt,over:xt},$e===Fn.DragEnd&&typeof $n=="function"&&await Promise.resolve($n(gn))&&($e=Fn.DragCancel)}K.current=null,Lo.unstable_batchedUpdates(()=>{g({type:$e}),E(la.Uninitialized),qe(null),z(null),F(null),Te.current=null;const $n=$e===Fn.DragEnd?"onDragEnd":"onDragCancel";if(gn){const Ne=A.current[$n];Ne==null||Ne(gn),y({type:$n,event:gn})}})}}},[B]),je=c.useCallback((Ue,pt)=>(ht,ln)=>{const yt=ht.nativeEvent,hn=B.get(ln);if(K.current!==null||!hn||yt.dndKit||yt.defaultPrevented)return;const pn={active:hn};Ue(ht,pt.options,pn)===!0&&(yt.dndKit={capturedBy:pt.sensor},K.current=ln,ae(ht,pt))},[B,ae]),ke=qA(m,je);QA(m),cr(()=>{fe&&_===la.Initializing&&E(la.Initialized)},[fe,_]),c.useEffect(()=>{const{onDragMove:Ue}=A.current,{active:pt,activatorEvent:ht,collisions:ln,over:yt}=le.current;if(!pt||!ht)return;const hn={active:pt,activatorEvent:ht,collisions:ln,delta:{x:we.x,y:we.y},over:yt};Lo.unstable_batchedUpdates(()=>{Ue==null||Ue(hn),y({type:"onDragMove",event:hn})})},[we.x,we.y]),c.useEffect(()=>{const{active:Ue,activatorEvent:pt,collisions:ht,droppableContainers:ln,scrollAdjustedTranslate:yt}=le.current;if(!Ue||K.current==null||!pt||!yt)return;const{onDragOver:hn}=A.current,pn=ln.get(ye),re=pn&&pn.rect.current?{id:pn.id,rect:pn.rect.current,data:pn.data,disabled:pn.disabled}:null,$e={active:Ue,activatorEvent:pt,collisions:ht,delta:{x:yt.x,y:yt.y},over:re};Lo.unstable_batchedUpdates(()=>{qe(re),hn==null||hn($e),y({type:"onDragOver",event:$e})})},[ye]),cr(()=>{le.current={activatorEvent:w,active:I,activeNode:W,collisionRect:ee,collisions:me,droppableRects:U,draggableNodes:B,draggingNode:Fe,draggingNodeRect:pe,droppableContainers:L,over:Ke,scrollableAncestors:ie,scrollAdjustedTranslate:we},C.current={initial:pe,translated:ee}},[I,W,me,ee,B,Fe,pe,U,L,Ke,ie,we]),DA({...Y,delta:k,draggingRect:ee,pointerCoordinates:Be,scrollableAncestors:ie,scrollableAncestorRects:Ie});const Xe=c.useMemo(()=>({active:I,activeNode:W,activeNodeRect:fe,activatorEvent:w,collisions:me,containerNodeRect:Ce,dragOverlay:Pe,draggableNodes:B,droppableContainers:L,droppableRects:U,over:Ke,measureDroppableContainers:Z,scrollableAncestors:ie,scrollableAncestorRects:Ie,measuringConfiguration:H,measuringScheduled:V,windowRect:D}),[I,W,fe,w,me,Ce,Pe,B,L,U,Ke,Z,ie,Ie,H,V,D]),lt=c.useMemo(()=>({activatorEvent:w,activators:ke,active:I,activeNodeRect:fe,ariaDescribedById:{draggable:R},dispatch:g,draggableNodes:B,over:Ke,measureDroppableContainers:Z}),[w,ke,I,fe,g,R,B,Ke,Z]);return Bt.createElement(pj.Provider,{value:v},Bt.createElement(Ml.Provider,{value:lt},Bt.createElement(Aj.Provider,{value:Xe},Bt.createElement(Hd.Provider,{value:ce},d)),Bt.createElement(sE,{disabled:(l==null?void 0:l.restoreFocus)===!1})),Bt.createElement(lA,{...l,hiddenTextDescribedById:R}));function It(){const Ue=(T==null?void 0:T.autoScrollEnabled)===!1,pt=typeof u=="object"?u.enabled===!1:u===!1,ht=S&&!Ue&&!pt;return typeof u=="object"?{...u,enabled:ht}:{enabled:ht}}}),oE=c.createContext(null),Zf="button",iE="Draggable";function lE(t){let{id:n,data:s,disabled:r=!1,attributes:a}=t;const o=Pl(iE),{activators:i,activatorEvent:l,active:u,activeNodeRect:d,ariaDescribedById:m,draggableNodes:p,over:x}=c.useContext(Ml),{role:f=Zf,roleDescription:h="draggable",tabIndex:j=0}=a??{},b=(u==null?void 0:u.id)===n,g=c.useContext(b?Hd:oE),[y,v]=Kc(),[_,E]=Kc(),S=GA(i,n),M=ul(s);cr(()=>(p.set(n,{id:n,key:o,node:y,activatorNode:_,data:M}),()=>{const k=p.get(n);k&&k.key===o&&p.delete(n)}),[p,n]);const B=c.useMemo(()=>({role:f,tabIndex:j,"aria-disabled":r,"aria-pressed":b&&f===Zf?!0:void 0,"aria-roledescription":h,"aria-describedby":m.draggable}),[r,f,j,b,h,m.draggable]);return{active:u,activatorEvent:l,activeNodeRect:d,attributes:B,isDragging:b,listeners:r?void 0:S,node:y,over:x,setNodeRef:v,setActivatorNodeRef:E,transform:g}}function Tj(){return c.useContext(Aj)}const cE="Droppable",dE={timeout:25};function Rj(t){let{data:n,disabled:s=!1,id:r,resizeObserverConfig:a}=t;const o=Pl(cE),{active:i,dispatch:l,over:u,measureDroppableContainers:d}=c.useContext(Ml),m=c.useRef({disabled:s}),p=c.useRef(!1),x=c.useRef(null),f=c.useRef(null),{disabled:h,updateMeasurementsFor:j,timeout:b}={...dE,...a},g=ul(j??r),y=c.useCallback(()=>{if(!p.current){p.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(g.current)?g.current:[g.current]),f.current=null},b)},[b]),v=Wd({callback:y,disabled:h||!i}),_=c.useCallback((B,k)=>{v&&(k&&(v.unobserve(k),p.current=!1),B&&v.observe(B))},[v]),[E,S]=Kc(_),M=ul(n);return c.useEffect(()=>{!v||!E.current||(v.disconnect(),p.current=!1,v.observe(E.current))},[E,v]),c.useEffect(()=>(l({type:Fn.RegisterDroppable,element:{id:r,key:o,disabled:s,node:E,rect:x,data:M}}),()=>l({type:Fn.UnregisterDroppable,key:o,id:r})),[r]),c.useEffect(()=>{s!==m.current.disabled&&(l({type:Fn.SetDroppableDisabled,id:r,key:o,disabled:s}),m.current.disabled=s)},[r,o,s,l]),{active:i,rect:x,isOver:(u==null?void 0:u.id)===r,node:E,over:u,setNodeRef:S}}function uE(t){let{animation:n,children:s}=t;const[r,a]=c.useState(null),[o,i]=c.useState(null),l=zc(s);return!s&&!r&&l&&a(l),cr(()=>{if(!o)return;const u=r==null?void 0:r.key,d=r==null?void 0:r.props.id;if(u==null||d==null){a(null);return}Promise.resolve(n(d,o)).then(()=>{a(null)})},[n,r,o]),Bt.createElement(Bt.Fragment,null,s,r?c.cloneElement(r,{ref:i}):null)}const mE={x:0,y:0,scaleX:1,scaleY:1};function pE(t){let{children:n}=t;return Bt.createElement(Ml.Provider,{value:_j},Bt.createElement(Hd.Provider,{value:mE},n))}const xE={position:"fixed",touchAction:"none"},fE=t=>zd(t)?"transform 250ms ease":void 0,hE=c.forwardRef((t,n)=>{let{as:s,activatorEvent:r,adjustScale:a,children:o,className:i,rect:l,style:u,transform:d,transition:m=fE}=t;if(!l)return null;const p=a?d:{...d,scaleX:1,scaleY:1},x={...xE,width:l.width,height:l.height,top:l.top,left:l.left,transform:Er.Transform.toString(p),transformOrigin:a&&r?dA(r,l):void 0,transition:typeof m=="function"?m(r):m,...u};return Bt.createElement(s,{className:i,style:x,ref:n},o)}),gE=t=>n=>{let{active:s,dragOverlay:r}=n;const a={},{styles:o,className:i}=t;if(o!=null&&o.active)for(const[l,u]of Object.entries(o.active))u!==void 0&&(a[l]=s.node.style.getPropertyValue(l),s.node.style.setProperty(l,u));if(o!=null&&o.dragOverlay)for(const[l,u]of Object.entries(o.dragOverlay))u!==void 0&&r.node.style.setProperty(l,u);return i!=null&&i.active&&s.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[u,d]of Object.entries(a))s.node.style.setProperty(u,d);i!=null&&i.active&&s.node.classList.remove(i.active)}},bE=t=>{let{transform:{initial:n,final:s}}=t;return[{transform:Er.Transform.toString(n)},{transform:Er.Transform.toString(s)}]},yE={duration:250,easing:"ease",keyframes:bE,sideEffects:gE({styles:{active:{opacity:"0"}}})};function vE(t){let{config:n,draggableNodes:s,droppableContainers:r,measuringConfiguration:a}=t;return Kd((o,i)=>{if(n===null)return;const l=s.get(o);if(!l)return;const u=l.node.current;if(!u)return;const d=Ij(i);if(!d)return;const{transform:m}=gs(i).getComputedStyle(i),p=hj(m);if(!p)return;const x=typeof n=="function"?n:jE(n);return Nj(u,a.draggable.measure),x({active:{id:o,data:l.data,node:u,rect:a.draggable.measure(u)},draggableNodes:s,dragOverlay:{node:i,rect:a.dragOverlay.measure(d)},droppableContainers:r,measuringConfiguration:a,transform:p})})}function jE(t){const{duration:n,easing:s,sideEffects:r,keyframes:a}={...yE,...t};return o=>{let{active:i,dragOverlay:l,transform:u,...d}=o;if(!n)return;const m={x:l.rect.left-i.rect.left,y:l.rect.top-i.rect.top},p={scaleX:u.scaleX!==1?i.rect.width*u.scaleX/l.rect.width:1,scaleY:u.scaleY!==1?i.rect.height*u.scaleY/l.rect.height:1},x={x:u.x-m.x,y:u.y-m.y,...p},f=a({...d,active:i,dragOverlay:l,transform:{initial:u,final:x}}),[h]=f,j=f[f.length-1];if(JSON.stringify(h)===JSON.stringify(j))return;const b=r==null?void 0:r({active:i,dragOverlay:l,...d}),g=l.node.animate(f,{duration:n,easing:s,fill:"forwards"});return new Promise(y=>{g.onfinish=()=>{b==null||b(),y()}})}}let Yf=0;function wE(t){return c.useMemo(()=>{if(t!=null)return Yf++,Yf},[t])}const NE=Bt.memo(t=>{let{adjustScale:n=!1,children:s,dropAnimation:r,style:a,transition:o,modifiers:i,wrapperElement:l="div",className:u,zIndex:d=999}=t;const{activatorEvent:m,active:p,activeNodeRect:x,containerNodeRect:f,draggableNodes:h,droppableContainers:j,dragOverlay:b,over:g,measuringConfiguration:y,scrollableAncestors:v,scrollableAncestorRects:_,windowRect:E}=Tj(),S=c.useContext(Hd),M=wE(p==null?void 0:p.id),B=Ej(i,{activatorEvent:m,active:p,activeNodeRect:x,containerNodeRect:f,draggingNodeRect:b.rect,over:g,overlayNodeRect:b.rect,scrollableAncestors:v,scrollableAncestorRects:_,transform:S,windowRect:E}),k=kx(x),L=vE({config:r,draggableNodes:h,droppableContainers:j,measuringConfiguration:y}),$=k?b.setRef:void 0;return Bt.createElement(pE,null,Bt.createElement(uE,{animation:L},p&&M?Bt.createElement(hE,{key:M,id:p.id,ref:$,as:l,activatorEvent:m,adjustScale:n,className:u,transition:o,rect:k,style:{zIndex:d,...a},transform:B},s):null))});function Vd(t,n,s){const r=t.slice();return r.splice(s<0?r.length+s:s,0,r.splice(n,1)[0]),r}function kE(t,n){return t.reduce((s,r,a)=>{const o=n.get(r);return o&&(s[a]=o),s},Array(t.length))}function zl(t){return t!==null&&t>=0}function CE(t,n){if(t===n)return!0;if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(t[s]!==n[s])return!1;return!0}function SE(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const Pj=t=>{let{rects:n,activeIndex:s,overIndex:r,index:a}=t;const o=Vd(n,r,s),i=n[a],l=o[a];return!l||!i?null:{x:l.left-i.left,y:l.top-i.top,scaleX:l.width/i.width,scaleY:l.height/i.height}},Wl={scaleX:1,scaleY:1},Sx=t=>{var n;let{activeIndex:s,activeNodeRect:r,index:a,rects:o,overIndex:i}=t;const l=(n=o[s])!=null?n:r;if(!l)return null;if(a===s){const d=o[i];return d?{x:0,y:s<i?d.top+d.height-(l.top+l.height):d.top-l.top,...Wl}:null}const u=IE(o,a,s);return a>s&&a<=i?{x:0,y:-l.height-u,...Wl}:a<s&&a>=i?{x:0,y:l.height+u,...Wl}:{x:0,y:0,...Wl}};function IE(t,n,s){const r=t[n],a=t[n-1],o=t[n+1];return r?s<n?a?r.top-(a.top+a.height):o?o.top-(r.top+r.height):0:o?o.top-(r.top+r.height):a?r.top-(a.top+a.height):0:0}const Mj="Sortable",$j=Bt.createContext({activeIndex:-1,containerId:Mj,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Pj,disabled:{draggable:!1,droppable:!1}});function Ix(t){let{children:n,id:s,items:r,strategy:a=Pj,disabled:o=!1}=t;const{active:i,dragOverlay:l,droppableRects:u,over:d,measureDroppableContainers:m}=Tj(),p=Pl(Mj,s),x=l.rect!==null,f=c.useMemo(()=>r.map(S=>typeof S=="object"&&"id"in S?S.id:S),[r]),h=i!=null,j=i?f.indexOf(i.id):-1,b=d?f.indexOf(d.id):-1,g=c.useRef(f),y=!CE(f,g.current),v=b!==-1&&j===-1||y,_=SE(o);cr(()=>{y&&h&&m(f)},[y,f,h,m]),c.useEffect(()=>{g.current=f},[f]);const E=c.useMemo(()=>({activeIndex:j,containerId:p,disabled:_,disableTransforms:v,items:f,overIndex:b,useDragOverlay:x,sortedRects:kE(f,u),strategy:a}),[j,p,_.draggable,_.droppable,v,f,b,u,x,a]);return Bt.createElement($j.Provider,{value:E},n)}const _E=t=>{let{id:n,items:s,activeIndex:r,overIndex:a}=t;return Vd(s,r,a).indexOf(n)},AE=t=>{let{containerId:n,isSorting:s,wasDragging:r,index:a,items:o,newIndex:i,previousItems:l,previousContainerId:u,transition:d}=t;return!d||!r||l!==o&&a===i?!1:s?!0:i!==a&&n===u},EE={duration:200,easing:"ease"},Dj="transform",TE=Er.Transition.toString({property:Dj,duration:0,easing:"linear"}),RE={roleDescription:"sortable"};function PE(t){let{disabled:n,index:s,node:r,rect:a}=t;const[o,i]=c.useState(null),l=c.useRef(s);return cr(()=>{if(!n&&s!==l.current&&r.current){const u=a.current;if(u){const d=bi(r.current,{ignoreTransform:!0}),m={x:u.left-d.left,y:u.top-d.top,scaleX:u.width/d.width,scaleY:u.height/d.height};(m.x||m.y)&&i(m)}}s!==l.current&&(l.current=s)},[n,s,r,a]),c.useEffect(()=>{o&&i(null)},[o]),o}function _x(t){let{animateLayoutChanges:n=AE,attributes:s,disabled:r,data:a,getNewIndex:o=_E,id:i,strategy:l,resizeObserverConfig:u,transition:d=EE}=t;const{items:m,containerId:p,activeIndex:x,disabled:f,disableTransforms:h,sortedRects:j,overIndex:b,useDragOverlay:g,strategy:y}=c.useContext($j),v=ME(r,f),_=m.indexOf(i),E=c.useMemo(()=>({sortable:{containerId:p,index:_,items:m},...a}),[p,a,_,m]),S=c.useMemo(()=>m.slice(m.indexOf(i)),[m,i]),{rect:M,node:B,isOver:k,setNodeRef:L}=Rj({id:i,data:E,disabled:v.droppable,resizeObserverConfig:{updateMeasurementsFor:S,...u}}),{active:$,activatorEvent:C,activeNodeRect:I,attributes:K,setNodeRef:T,listeners:z,isDragging:w,over:F,setActivatorNodeRef:A,transform:R}=lE({id:i,data:E,attributes:{...RE,...s},disabled:v.draggable}),Q=G_(L,T),H=!!$,U=H&&!h&&zl(x)&&zl(b),Z=!g&&w,V=Z&&U?R:null,J=U?V??(l??y)({rects:j,activeNodeRect:I,activeIndex:x,overIndex:b,index:_}):null,Y=zl(x)&&zl(b)?o({id:i,items:m,activeIndex:x,overIndex:b}):_,de=$==null?void 0:$.id,fe=c.useRef({activeId:de,items:m,newIndex:Y,containerId:p}),Ce=m!==fe.current.items,le=n({active:$,containerId:p,isDragging:w,isSorting:H,id:i,index:_,items:m,newIndex:fe.current.newIndex,previousItems:fe.current.items,previousContainerId:fe.current.containerId,transition:d,wasDragging:fe.current.activeId!=null}),Re=PE({disabled:!le,index:_,node:B,rect:M});return c.useEffect(()=>{H&&fe.current.newIndex!==Y&&(fe.current.newIndex=Y),p!==fe.current.containerId&&(fe.current.containerId=p),m!==fe.current.items&&(fe.current.items=m)},[H,Y,p,m]),c.useEffect(()=>{if(de===fe.current.activeId)return;if(de!=null&&fe.current.activeId==null){fe.current.activeId=de;return}const Fe=setTimeout(()=>{fe.current.activeId=de},50);return()=>clearTimeout(Fe)},[de]),{active:$,activeIndex:x,attributes:K,data:E,rect:M,index:_,newIndex:Y,items:m,isOver:k,isSorting:H,isDragging:w,listeners:z,node:B,overIndex:b,over:F,setNodeRef:Q,setActivatorNodeRef:A,setDroppableNodeRef:L,setDraggableNodeRef:T,transform:Re??J,transition:Pe()};function Pe(){if(Re||Ce&&fe.current.newIndex===_)return TE;if(!(Z&&!zd(C)||!d)&&(H||le))return Er.Transition.toString({...d,property:Dj})}}function ME(t,n){var s,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(s=t==null?void 0:t.draggable)!=null?s:n.draggable,droppable:(r=t==null?void 0:t.droppable)!=null?r:n.droppable}}Kt.Down,Kt.Right,Kt.Up,Kt.Left;const Oj=c.createContext(null);function $E({children:t}){const[n,s]=c.useState(!1),[r,a]=c.useState({}),[o,i]=c.useState(!1),[l,u]=c.useState(!1),[d,m]=c.useState({}),[p,x]=c.useState(!1),[f,h]=c.useState(!1),[j,b]=c.useState({}),g=c.useCallback(($={})=>{a($),s(!0)},[]),y=c.useCallback(()=>{s(!1),a({})},[]),v=c.useCallback(()=>{i(!0)},[]),_=c.useCallback(()=>{i(!1)},[]),E=c.useCallback(($={})=>{m($),u(!0)},[]),S=c.useCallback(()=>{u(!1),m({})},[]),M=c.useCallback(()=>{x(!0)},[]),B=c.useCallback(()=>{x(!1)},[]),k=c.useCallback(($={})=>{b($),h(!0)},[]),L=c.useCallback(()=>{h(!1),b({})},[]);return e.jsx(Oj.Provider,{value:{newIssueOpen:n,newIssueDefaults:r,openNewIssue:g,closeNewIssue:y,newProjectOpen:o,openNewProject:v,closeNewProject:_,newGoalOpen:l,newGoalDefaults:d,openNewGoal:E,closeNewGoal:S,newAgentOpen:p,openNewAgent:M,closeNewAgent:B,onboardingOpen:f,onboardingOptions:j,openOnboarding:k,closeOnboarding:L},children:t})}function In(){const t=c.useContext(Oj);if(!t)throw new Error("useDialog must be used within DialogProvider");return t}const DE={get:t=>ne.get(`/companies/${t}/sidebar-badges`)},Yt={list:(t,n,s)=>{const r=new URLSearchParams;n&&r.set("agentId",n),s&&r.set("limit",String(s));const a=r.toString();return ne.get(`/companies/${t}/heartbeat-runs${a?`?${a}`:""}`)},get:t=>ne.get(`/heartbeat-runs/${t}`),events:(t,n=0,s=200)=>ne.get(`/heartbeat-runs/${t}/events?afterSeq=${encodeURIComponent(String(n))}&limit=${encodeURIComponent(String(s))}`),log:(t,n=0,s=256e3)=>ne.get(`/heartbeat-runs/${t}/log?offset=${encodeURIComponent(String(n))}&limitBytes=${encodeURIComponent(String(s))}`),workspaceOperations:t=>ne.get(`/heartbeat-runs/${t}/workspace-operations`),workspaceOperationLog:(t,n=0,s=256e3)=>ne.get(`/workspace-operations/${t}/log?offset=${encodeURIComponent(String(n))}&limitBytes=${encodeURIComponent(String(s))}`),cancel:t=>ne.post(`/heartbeat-runs/${t}/cancel`,{}),liveRunsForIssue:t=>ne.get(`/issues/${t}/live-runs`),activeRunForIssue:t=>ne.get(`/issues/${t}/active-run`),liveRunsForCompany:(t,n)=>ne.get(`/companies/${t}/live-runs${n?`?minCount=${n}`:""}`),listInstanceSchedulerAgents:()=>ne.get("/instance/scheduler-heartbeats")};function Lj({delayDuration:t=0,...n}){return e.jsx(Bk,{"data-slot":"tooltip-provider",delayDuration:t,...n})}function Jn({...t}){return e.jsx(Ok,{"data-slot":"tooltip",...t})}function Zn({...t}){return e.jsx(Lk,{"data-slot":"tooltip-trigger",...t})}function Yn({className:t,sideOffset:n=0,children:s,...r}){return e.jsx(Fk,{children:e.jsxs(qk,{"data-slot":"tooltip-content",sideOffset:n,className:O("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[s,e.jsx(Uk,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}const OE=[[0,8,2,10],[12,4,14,6],[3,11,1,9],[15,7,13,5]];function LE(t){let n=2166136261;for(let s=0;s<t.length;s++)n^=t.charCodeAt(s),n=Math.imul(n,16777619);return n>>>0}function FE(t){let n=t>>>0;return()=>{n=n+1831565813>>>0;let s=Math.imul(n^n>>>15,1|n);return s^=s+Math.imul(s^s>>>7,61|s),((s^s>>>14)>>>0)/4294967296}}function Xf(t,n,s){const r=(t%360+360)%360,a=Math.max(0,Math.min(100,n))/100,o=Math.max(0,Math.min(100,s))/100,i=(1-Math.abs(2*o-1))*a,l=i*(1-Math.abs(r/60%2-1)),u=o-i/2;let d=0,m=0,p=0;return r<60?(d=i,m=l):r<120?(d=l,m=i):r<180?(m=i,p=l):r<240?(m=l,p=i):r<300?(d=l,p=i):(d=i,p=l),[Math.round((d+u)*255),Math.round((m+u)*255),Math.round((p+u)*255)]}function qE(t){const n=parseInt(t.slice(1,3),16)/255,s=parseInt(t.slice(3,5),16)/255,r=parseInt(t.slice(5,7),16)/255,a=Math.max(n,s,r),o=Math.min(n,s,r),i=a-o;if(i===0)return 0;let l=0;return a===n?l=(s-r)/i%6:a===s?l=(r-n)/i+2:l=(n-s)/i+4,(l*60+360)%360}function UE(t,n,s=22,r=2){if(typeof document>"u")return"";const a=document.createElement("canvas");a.width=s*r,a.height=s*r;const o=a.getContext("2d");if(!o)return"";const i=FE(LE(t)),l=n?qE(n):Math.floor(i()*360),[u,d,m]=Xf(l,54+Math.floor(i()*14),36+Math.floor(i()*12)),[p,x,f]=Xf(l+(i()>.5?10:-10),86+Math.floor(i()*10),82+Math.floor(i()*10)),h=(s-1)/2,j=Math.max(h,1),b=i()*Math.PI*2,g=Math.cos(b),y=Math.sin(b),v=Math.abs(g*j)+Math.abs(y*j),_=.34+i()*.12,E=.33+i()*.12,S=i()*Math.PI*2,M=i()*Math.PI*2;o.fillStyle=`rgb(${u} ${d} ${m})`,o.fillRect(0,0,a.width,a.height),o.fillStyle=`rgb(${p} ${x} ${f})`;const B=r*.46;for(let k=0;k<s;k++){const L=k-h;for(let $=0;$<s;$++){const C=$-h,K=((C*g+L*y)/v+1)*.5,T=Math.sin((C+L)*_+S)*.5+.5,z=Math.sin((C-L)*E+M)*.5+.5,w=T*.5+z*.5,F=Math.max(0,Math.min(1,K+(w-.5)*.22)),A=Math.max(0,Math.min(15,Math.floor(F*16))),R=OE[k&3][$&3];if(A<=R)continue;const Q=$*r+r/2,H=k*r+r/2;o.beginPath(),o.arc(Q,H,B,0,Math.PI*2),o.fill()}}return a.toDataURL("image/png")}function Fj({companyName:t,logoUrl:n,brandColor:s,className:r}){const a=t.trim().charAt(0).toUpperCase()||"?",[o,i]=c.useState(!1),l=!o&&typeof n=="string"&&n.trim().length>0?n:null;c.useEffect(()=>{i(!1)},[n]);const u=c.useMemo(()=>UE(t.trim().toLowerCase(),s),[t,s]);return e.jsxs("div",{className:O("relative flex items-center justify-center w-11 h-11 text-base font-semibold text-white overflow-hidden",r),children:[l?e.jsx("img",{src:l,alt:`${t} logo`,onError:()=>i(!0),className:"absolute inset-0 h-full w-full object-cover"}):u?e.jsx("img",{src:u,alt:"","aria-hidden":"true",className:"absolute inset-0 h-full w-full",style:{imageRendering:"pixelated"}}):e.jsx("div",{className:"absolute inset-0 bg-muted"}),!l&&e.jsx("span",{className:"relative z-10 drop-shadow-[0_1px_2px_rgba(0,0,0,0.65)]",children:a})]})}const Ax="crewspace.companyOrder";function BE(){try{const t=localStorage.getItem(Ax);if(t)return JSON.parse(t)}catch{}return[]}function KE(t){localStorage.setItem(Ax,JSON.stringify(t))}function eh(t){const n=BE();if(n.length===0)return t;const s=new Map(t.map(a=>[a.id,a])),r=[];for(const a of n){const o=s.get(a);o&&(r.push(o),s.delete(a))}for(const a of s.values())r.push(a);return r}function zE({company:t,isSelected:n,hasLiveAgents:s,hasUnreadInbox:r,onSelect:a}){const{attributes:o,listeners:i,setNodeRef:l,transform:u,transition:d,isDragging:m}=_x({id:t.id}),p={transform:Er.Transform.toString(u),transition:d,zIndex:m?10:void 0,opacity:m?.8:1};return e.jsx("div",{ref:l,style:p,...o,...i,className:"overflow-visible",children:e.jsxs(Jn,{delayDuration:300,children:[e.jsx(Zn,{asChild:!0,children:e.jsxs("a",{href:`/${t.issuePrefix}/dashboard`,onClick:x=>{x.preventDefault(),a()},className:"relative flex items-center justify-center group overflow-visible",children:[e.jsx("div",{className:O("absolute left-[-14px] w-1 rounded-r-full bg-foreground transition-[height] duration-150",n?"h-5":"h-0 group-hover:h-2")}),e.jsxs("div",{className:O("relative overflow-visible transition-transform duration-150",m&&"scale-105"),children:[e.jsx(Fj,{companyName:t.name,logoUrl:t.logoUrl,brandColor:t.brandColor,className:O(n?"rounded-[14px]":"rounded-[22px] group-hover:rounded-[14px]",m&&"shadow-lg")}),s&&e.jsx("span",{className:"pointer-events-none absolute -right-0.5 -top-0.5 z-10",children:e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-blue-400 opacity-80"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-blue-500 ring-2 ring-background"})]})}),r&&e.jsx("span",{className:"pointer-events-none absolute -bottom-0.5 -right-0.5 z-10 h-2.5 w-2.5 rounded-full bg-red-500 ring-2 ring-background"})]})]})}),e.jsx(Yn,{side:"right",sideOffset:8,children:e.jsx("p",{children:t.name})})]})})}function th(){const{companies:t,selectedCompanyId:n,setSelectedCompanyId:s}=et(),{openOnboarding:r}=In(),a=Sn(),i=fn().pathname.startsWith("/instance/"),l=i?null:n,u=c.useMemo(()=>t.filter(v=>v.status!=="archived"),[t]),d=c.useMemo(()=>u.map(v=>v.id),[u]),m=gf({queries:d.map(v=>({queryKey:N.liveRuns(v),queryFn:()=>Yt.liveRunsForCompany(v),refetchInterval:1e4}))}),p=gf({queries:d.map(v=>({queryKey:N.sidebarBadges(v),queryFn:()=>DE.get(v),refetchInterval:15e3}))}),x=c.useMemo(()=>{const v=new Map;return d.forEach((_,E)=>{var S,M;v.set(_,(((M=(S=m[E])==null?void 0:S.data)==null?void 0:M.length)??0)>0)}),v},[d,m]),f=c.useMemo(()=>{const v=new Map;return d.forEach((_,E)=>{var S,M;v.set(_,(((M=(S=p[E])==null?void 0:S.data)==null?void 0:M.inbox)??0)>0)}),v},[d,p]),[h,j]=c.useState(()=>eh(u).map(v=>v.id));c.useEffect(()=>{if(u.length===0){j([]);return}j(eh(u).map(v=>v.id))},[u]),c.useEffect(()=>{const v=_=>{if(_.key===Ax)try{const E=_.newValue?JSON.parse(_.newValue):[];j(E)}catch{}};return window.addEventListener("storage",v),()=>window.removeEventListener("storage",v)},[]);const b=c.useMemo(()=>{const v=new Map(u.map(E=>[E.id,E])),_=[];for(const E of h){const S=v.get(E);S&&(_.push(S),v.delete(E))}for(const E of v.values())_.push(E);return _},[u,h]),g=bx(gx(Nx,{activationConstraint:{distance:8}})),y=c.useCallback(v=>{const{active:_,over:E}=v;if(!E||_.id===E.id)return;const S=b.map(L=>L.id),M=S.indexOf(_.id),B=S.indexOf(E.id);if(M===-1||B===-1)return;const k=Vd(S,M,B);j(k),KE(k)},[b]);return e.jsxs("div",{className:"flex flex-col items-center w-[72px] shrink-0 h-full bg-background border-r border-border",children:[e.jsx("div",{className:"flex items-center justify-center h-12 w-full shrink-0",children:e.jsx(ai,{className:"h-5 w-5 text-foreground"})}),e.jsx("div",{className:"flex-1 flex flex-col items-center gap-2 py-3 w-full overflow-y-auto overflow-x-hidden scrollbar-none",children:e.jsx(Cx,{sensors:g,collisionDetection:xj,onDragEnd:y,children:e.jsx(Ix,{items:b.map(v=>v.id),strategy:Sx,children:b.map(v=>e.jsx(zE,{company:v,isSelected:v.id===l,hasLiveAgents:x.get(v.id)??!1,hasUnreadInbox:f.get(v.id)??!1,onSelect:()=>{s(v.id),i&&a(`/${v.issuePrefix}/dashboard`)}},v.id))})})}),e.jsx("div",{className:"w-8 h-px bg-border mx-auto shrink-0"}),e.jsx("div",{className:"flex items-center justify-center py-2 shrink-0",children:e.jsxs(Jn,{delayDuration:300,children:[e.jsx(Zn,{asChild:!0,children:e.jsx("button",{onClick:()=>r(),className:"flex items-center justify-center w-11 h-11 rounded-[22px] hover:rounded-[14px] border-2 border-dashed border-border text-muted-foreground hover:border-foreground/30 hover:text-foreground transition-[border-color,color,border-radius] duration-150","aria-label":"Add company",children:e.jsx(Ot,{className:"h-5 w-5"})})}),e.jsx(Yn,{side:"right",sideOffset:8,children:e.jsx("p",{children:"Add company"})})]})})]})}function hu({label:t,children:n}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/50",children:t}),e.jsx("div",{className:"flex-1 h-px bg-border/50"})]}),e.jsx("div",{className:"flex flex-col gap-0.5",children:n})]})}const qj=c.createContext(null),gu=768;function WE({children:t}){const[n,s]=c.useState(()=>window.innerWidth<gu),[r,a]=c.useState(()=>window.innerWidth>=gu);c.useEffect(()=>{const i=window.matchMedia(`(max-width: ${gu-1}px)`),l=u=>{s(u.matches),a(!u.matches)};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[]);const o=c.useCallback(()=>a(i=>!i),[]);return e.jsx(qj.Provider,{value:{sidebarOpen:r,setSidebarOpen:a,toggleSidebar:o,isMobile:n},children:t})}function mr(){const t=c.useContext(qj);if(!t)throw new Error("useSidebar must be used within SidebarProvider");return t}function Ln({to:t,label:n,icon:s,end:r,className:a,badge:o,badgeTone:i="default",textBadge:l,textBadgeTone:u="default",alert:d=!1,liveCount:m}){const{isMobile:p,setSidebarOpen:x}=mr();return e.jsxs(Cl,{to:t,end:r,onClick:()=>{p&&x(!1)},className:({isActive:f})=>O("flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium transition-colors rounded-sm",f?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground",a),children:[e.jsxs("span",{className:"relative shrink-0",children:[e.jsx(s,{className:"h-4 w-4"}),d&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-[0_0_0_2px_hsl(var(--background))]"})]}),e.jsx("span",{className:"flex-1 truncate",children:n}),l&&e.jsx("span",{className:O("ml-auto rounded-full px-1.5 py-0.5 text-[10px] font-medium leading-none",u==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:l}),m!=null&&m>0&&e.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}),e.jsxs("span",{className:"text-[11px] font-medium text-blue-600 dark:text-blue-400",children:[m," live"]})]}),o!=null&&o>0&&e.jsx("span",{className:O("ml-auto rounded-full px-1.5 py-0.5 text-xs leading-none",i==="danger"?"bg-red-600/90 text-red-50":"bg-primary text-primary-foreground"),children:o})]})}function nh(t){if(!t||typeof t!="object")return null;const n=t,s=n.session,r=n.user;if(!s||typeof s!="object"||!r||typeof r!="object")return null;const a=s,o=r;return typeof a.id!="string"||typeof a.userId!="string"||typeof o.id!="string"?null:{session:{id:a.id,userId:a.userId},user:{id:o.id,email:typeof o.email=="string"?o.email:null,name:typeof o.name=="string"?o.name:null}}}async function bu(t,n){var a;const s=await fetch(`/api/auth${t}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),r=await s.json().catch(()=>null);if(!s.ok){const o=r!=null&&r.error&&typeof r.error=="object"?((a=r.error)==null?void 0:a.message)??`Request failed: ${s.status}`:(r==null?void 0:r.error)??`Request failed: ${s.status}`;throw new Error(o)}return r}const Bn={getSession:async()=>{const t=await fetch("/api/auth/get-session",{credentials:"include",headers:{Accept:"application/json"}});if(t.status===401)return null;const n=await t.json().catch(()=>null);if(!t.ok)throw new Error(`Failed to load session (${t.status})`);const s=nh(n);return s||(n&&typeof n=="object"?nh(n.data):null)},signInEmail:async t=>{await bu("/sign-in/email",t)},signUpEmail:async t=>{await bu("/sign-up/email",t)},signOut:async()=>{await bu("/sign-out",{})}};function HE(t,n){if(!n)return t;const s=t.includes("?")?"&":"?";return`${t}${s}companyId=${encodeURIComponent(n)}`}function Zr(t,n,s=""){return HE(`/projects/${encodeURIComponent(t)}${s}`,n)}const en={list:t=>ne.get(`/companies/${t}/projects`),get:(t,n)=>ne.get(Zr(t,n)),create:(t,n)=>ne.post(`/companies/${t}/projects`,n),update:(t,n,s)=>ne.patch(Zr(t,s),n),listWorkspaces:(t,n)=>ne.get(Zr(t,n,"/workspaces")),createWorkspace:(t,n,s)=>ne.post(Zr(t,s,"/workspaces"),n),updateWorkspace:(t,n,s,r)=>ne.patch(Zr(t,r,`/workspaces/${encodeURIComponent(n)}`),s),controlWorkspaceRuntimeServices:(t,n,s,r)=>ne.post(Zr(t,r,`/workspaces/${encodeURIComponent(n)}/runtime-services/${s}`),{}),removeWorkspace:(t,n,s)=>ne.delete(Zr(t,s,`/workspaces/${encodeURIComponent(n)}`)),remove:(t,n)=>ne.delete(Zr(t,n))},Fm="crewspace:project-order-updated",VE="crewspace.projectOrder",sh="anonymous";function Uj(t){return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function QE(t){if(!t)return sh;const n=t.trim();return n.length>0?n:sh}function Bj(t,n){return`${VE}:${t}:${QE(n)}`}function yu(t){try{const n=localStorage.getItem(t);return n?Uj(JSON.parse(n)):[]}catch{return[]}}function Kj(t,n){const s=Uj(n);try{localStorage.setItem(t,JSON.stringify(s))}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fm,{detail:{storageKey:t,orderedIds:s}}))}function zj(t,n){if(t.length===0)return[];if(n.length===0)return t;const s=new Map(t.map(a=>[a.id,a])),r=[];for(const a of n){const o=s.get(a);o&&(r.push(o),s.delete(a))}for(const a of s.values())r.push(a);return r}function vu(t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s+=1)if(t[s]!==n[s])return!1;return!0}function ju(t,n){return zj(t,n).map(s=>s.id)}function $l({projects:t,companyId:n,userId:s}){const r=c.useMemo(()=>n?Bj(n,s):null,[n,s]),[a,o]=c.useState(()=>r?ju(t,yu(r)):t.map(u=>u.id));c.useEffect(()=>{const u=r?ju(t,yu(r)):t.map(d=>d.id);o(d=>vu(d,u)?d:u)},[t,r]),c.useEffect(()=>{if(!r)return;const u=p=>{const x=ju(t,p);o(f=>vu(f,x)?f:x)},d=p=>{p.key===r&&u(yu(r))},m=p=>{const x=p.detail;!x||x.storageKey!==r||u(x.orderedIds)};return window.addEventListener("storage",d),window.addEventListener(Fm,m),()=>{window.removeEventListener("storage",d),window.removeEventListener(Fm,m)}},[t,r]);const i=c.useMemo(()=>zj(t,a),[t,a]),l=c.useCallback(u=>{const d=new Set(t.map(p=>p.id)),m=u.filter(p=>d.has(p));for(const p of t)m.includes(p.id)||m.push(p.id);o(p=>vu(p,m)?p:m),r&&Kj(r,m)},[t,r]);return{orderedProjects:i,orderedIds:a,persistOrder:l}}function Wj({title:t="Paused by budget"}){return e.jsx("span",{title:t,"aria-label":t,className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500/90 text-white shadow-[0_0_0_1px_rgba(255,255,255,0.08)]",children:e.jsx(wr,{className:"h-3 w-3"})})}function Sa({...t}){return e.jsx(Z1,{"data-slot":"collapsible",...t})}function Ia({...t}){return e.jsx(my,{"data-slot":"collapsible-trigger",...t})}function _a({...t}){return e.jsx(py,{"data-slot":"collapsible-content",...t})}const Mn={list:t=>ne.get(`/plugins${t?`?status=${t}`:""}`),listExamples:()=>ne.get("/plugins/examples"),get:t=>ne.get(`/plugins/${t}`),install:t=>ne.post("/plugins/install",t),uninstall:(t,n)=>ne.delete(`/plugins/${t}${n?"?purge=true":""}`),enable:t=>ne.post(`/plugins/${t}/enable`,{}),disable:(t,n)=>ne.post(`/plugins/${t}/disable`,n?{reason:n}:{}),health:t=>ne.get(`/plugins/${t}/health`),dashboard:t=>ne.get(`/plugins/${t}/dashboard`),logs:(t,n)=>{const s=new URLSearchParams;n!=null&&n.limit&&s.set("limit",String(n.limit)),n!=null&&n.level&&s.set("level",n.level),n!=null&&n.since&&s.set("since",n.since);const r=s.toString();return ne.get(`/plugins/${t}/logs${r?`?${r}`:""}`)},upgrade:(t,n)=>ne.post(`/plugins/${t}/upgrade`,n?{version:n}:{}),listUiContributions:()=>ne.get("/plugins/ui-contributions"),getConfig:t=>ne.get(`/plugins/${t}/config`),saveConfig:(t,n)=>ne.post(`/plugins/${t}/config`,{configJson:n}),testConfig:(t,n)=>ne.post(`/plugins/${t}/config/test`,{configJson:n}),bridgeGetData:(t,n,s,r,a)=>ne.post(`/plugins/${t}/data/${encodeURIComponent(n)}`,{companyId:r??void 0,params:s,renderEnvironment:a??void 0}),bridgePerformAction:(t,n,s,r,a)=>ne.post(`/plugins/${t}/actions/${encodeURIComponent(n)}`,{companyId:r??void 0,params:s,renderEnvironment:a??void 0})},GE={info:4e3,success:3500,warn:8e3,error:1e4},JE=1500,ZE=15e3,YE=5,XE=3500,eT=2e4,Hj=c.createContext(null);function tT(t,n){const s=GE[n];return typeof t!="number"||!Number.isFinite(t)?s:Math.max(JE,Math.min(ZE,Math.floor(t)))}function nT(){return`toast_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function sT({children:t}){const[n,s]=c.useState([]),r=c.useRef(new Map),a=c.useRef(new Map),o=c.useCallback(m=>{const p=r.current.get(m);p!==void 0&&(window.clearTimeout(p),r.current.delete(m))},[]),i=c.useCallback(m=>{o(m),s(p=>p.filter(x=>x.id!==m))},[o]),l=c.useCallback(()=>{for(const m of r.current.values())window.clearTimeout(m);r.current.clear(),s([])},[]),u=c.useCallback(m=>{var y;const p=Date.now(),x=m.tone??"info",f=tT(m.ttlMs,x),h=m.dedupeKey??m.id??`${x}|${m.title}|${m.body??""}|${((y=m.action)==null?void 0:y.href)??""}`;for(const[v,_]of a.current.entries())p-_>eT&&a.current.delete(v);const j=a.current.get(h);if(j&&p-j<XE)return null;a.current.set(h,p);const b=m.id??nT();o(b),s(v=>{const _={id:b,title:m.title,body:m.body,tone:x,ttlMs:f,action:m.action,createdAt:p},E=v.filter(S=>S.id!==b);return[_,...E].slice(0,YE)});const g=window.setTimeout(()=>{i(b)},f);return r.current.set(b,g),b},[o,i]);c.useEffect(()=>()=>{for(const m of r.current.values())window.clearTimeout(m);r.current.clear()},[]);const d=c.useMemo(()=>({toasts:n,pushToast:u,dismissToast:i,clearToasts:l}),[n,u,i,l]);return e.jsx(Hj.Provider,{value:d,children:t})}function ds(){const t=c.useContext(Hj);if(!t)throw new Error("useToast must be used within a ToastProvider");return t}const Ex=c.createContext(null);function Qd(){const t=c.useContext(Ex);if(!t)throw new Error("Plugin bridge hook called outside of a <PluginBridgeContext.Provider>. Ensure the plugin component is rendered within a PluginBridgeScope.");return t}function Vj(t){if(t instanceof Qr&&t.body&&typeof t.body=="object"){const n=t.body;if(typeof n.code=="string"&&typeof n.message=="string")return{code:n.code,message:n.message,details:n.details};if(typeof n.error=="string")return{code:"UNKNOWN",message:n.error}}return{code:"UNKNOWN",message:t instanceof Error?t.message:String(t)}}function rT(t){if(!t)return"";try{return JSON.stringify(t,Object.keys(t).sort())}catch{return""}}function Qj(t){return t?{environment:t.environment,launcherId:t.launcherId,bounds:t.bounds}:null}function aT(t){return t?JSON.stringify(t):""}function oT(t,n){const{pluginId:s,hostContext:r}=Qd(),a=r.companyId,o=Qj(r.renderEnvironment),i=aT(o),[l,u]=c.useState(null),[d,m]=c.useState(!0),[p,x]=c.useState(null),[f,h]=c.useState(0),j=rT(n);c.useEffect(()=>{let g=!1,y=null,v=0;const _=2,E=["WORKER_UNAVAILABLE","TIMEOUT"];m(!0);const S=()=>{Mn.bridgeGetData(s,t,n,a,o).then(M=>{g||(u(M.data),x(null),m(!1))}).catch(M=>{if(g)return;const B=Vj(M);if(E.includes(B.code)&&v<_){v+=1,y=setTimeout(()=>{y=null,g||S()},150*v);return}x(B),u(null),m(!1)})};return S(),()=>{g=!0,y&&clearTimeout(y)}},[s,t,j,f,a,i]);const b=c.useCallback(()=>{h(g=>g+1)},[]);return{data:l,loading:d,error:p,refresh:b}}function iT(t){const n=Qd(),s=c.useRef(n);return s.current=n,c.useCallback(async r=>{const{pluginId:a,hostContext:o}=s.current,i=o.companyId,l=Qj(o.renderEnvironment);try{return(await Mn.bridgePerformAction(a,t,r,i,l)).data}catch(u){throw Vj(u)}},[t])}function lT(){const{hostContext:t}=Qd();return t}function cT(){const{pushToast:t}=ds();return c.useCallback(n=>t(n),[t])}function dT(t,n){const{pluginId:s,hostContext:r}=Qd(),a=(n==null?void 0:n.companyId)??r.companyId??void 0,[o,i]=c.useState([]),[l,u]=c.useState(null),[d,m]=c.useState(!!a),[p,x]=c.useState(!1),[f,h]=c.useState(null),j=c.useRef(null),b=c.useCallback(()=>{var g;(g=j.current)==null||g.close(),j.current=null,m(!1),x(!1)},[]);return c.useEffect(()=>{if(i([]),u(null),h(null),!a){b();return}const g=new URLSearchParams({companyId:a}),y=new EventSource(`/api/plugins/${encodeURIComponent(s)}/bridge/stream/${encodeURIComponent(t)}?${g.toString()}`,{withCredentials:!0});return j.current=y,m(!0),x(!1),y.onopen=()=>{m(!1),x(!0),h(null)},y.onmessage=v=>{try{const _=JSON.parse(v.data);i(E=>[...E,_]),u(_)}catch(_){h(_ instanceof Error?_:new Error(String(_)))}},y.addEventListener("close",()=>{y.close(),j.current===y&&(j.current=null),m(!1),x(!1)}),y.onerror=()=>{m(!1),x(!1),h(new Error(`Failed to connect to plugin stream "${t}"`)),y.close(),j.current===y&&(j.current=null)},()=>{y.close(),j.current===y&&(j.current=null)}},[t,b,a,s]),{events:o,lastEvent:l,connecting:d,connected:p,error:f,close:b}}const Gd=new Map;function Jd(t,n){return`${t}:${n}`}function uT(t){return t==="detailTab"||t==="taskDetailView"||t==="contextMenuItem"||t==="commentAnnotation"||t==="commentContextMenuItem"||t==="projectSidebarItem"||t==="toolbarButton"}function mT(t){return t instanceof Error&&t.message?t.message:"Unknown error"}function pT(t,n,s){Gd.set(Jd(t,n),{kind:"react",component:s})}function xT(t,n,s){Gd.set(Jd(t,n),{kind:"web-component",tagName:s})}function fT(t){return Gd.get(Jd(t.pluginKey,t.exportName))??null}function rh(t,n){return Gd.get(Jd(t,n))??null}const La=new Map,Li=new Map;function Tx(t){const n=t.updatedAt??t.version??"0";return`${t.pluginId}:${n}`}function hT(t){const n=encodeURIComponent(t.updatedAt??t.version??"0");return`/_plugins/${encodeURIComponent(t.pluginId)}/ui/${t.uiEntryFile}?v=${n}`}const wu={};function gT(t,n){return n===void 0?t??{}:{...t??{},key:n}}function Us(t){if(wu[t])return wu[t];let n;switch(t){case"react":n=`
|
|
7
|
+
const R = globalThis.__crewspacePluginBridge__?.react;
|
|
8
|
+
export default R;
|
|
9
|
+
const { useState, useEffect, useCallback, useMemo, useRef, useContext,
|
|
10
|
+
createContext, createElement, Fragment, Component, forwardRef,
|
|
11
|
+
memo, lazy, Suspense, StrictMode, cloneElement, Children,
|
|
12
|
+
isValidElement, createRef } = R;
|
|
13
|
+
export { useState, useEffect, useCallback, useMemo, useRef, useContext,
|
|
14
|
+
createContext, createElement, Fragment, Component, forwardRef,
|
|
15
|
+
memo, lazy, Suspense, StrictMode, cloneElement, Children,
|
|
16
|
+
isValidElement, createRef };
|
|
17
|
+
`;break;case"react/jsx-runtime":n=`
|
|
18
|
+
const R = globalThis.__crewspacePluginBridge__?.react;
|
|
19
|
+
const withKey = ${gT.toString()};
|
|
20
|
+
export const jsx = (type, props, key) => R.createElement(type, withKey(props, key));
|
|
21
|
+
export const jsxs = (type, props, key) => R.createElement(type, withKey(props, key));
|
|
22
|
+
export const Fragment = R.Fragment;
|
|
23
|
+
`;break;case"react-dom":case"react-dom/client":n=`
|
|
24
|
+
const RD = globalThis.__crewspacePluginBridge__?.reactDom;
|
|
25
|
+
export default RD;
|
|
26
|
+
const { createRoot, hydrateRoot, createPortal, flushSync } = RD ?? {};
|
|
27
|
+
export { createRoot, hydrateRoot, createPortal, flushSync };
|
|
28
|
+
`;break;case"sdk-ui":n=`
|
|
29
|
+
const SDK = globalThis.__crewspacePluginBridge__?.sdkUi ?? {};
|
|
30
|
+
const { usePluginData, usePluginAction, useHostContext, usePluginStream, usePluginToast } = SDK;
|
|
31
|
+
export { usePluginData, usePluginAction, useHostContext, usePluginStream, usePluginToast };
|
|
32
|
+
`;break}const s=new Blob([n],{type:"application/javascript"}),r=URL.createObjectURL(s);return wu[t]=r,r}function bT(t){const n={'"@crewspaceai/plugin-sdk/ui"':`"${Us("sdk-ui")}"`,"'@crewspaceai/plugin-sdk/ui'":`'${Us("sdk-ui")}'`,'"@crewspaceai/plugin-sdk/ui/hooks"':`"${Us("sdk-ui")}"`,"'@crewspaceai/plugin-sdk/ui/hooks'":`'${Us("sdk-ui")}'`,'"react/jsx-runtime"':`"${Us("react/jsx-runtime")}"`,"'react/jsx-runtime'":`'${Us("react/jsx-runtime")}'`,'"react-dom/client"':`"${Us("react-dom/client")}"`,"'react-dom/client'":`'${Us("react-dom/client")}'`,'"react-dom"':`"${Us("react-dom")}"`,"'react-dom'":`'${Us("react-dom")}'`,'"react"':`"${Us("react")}"`,"'react'":`'${Us("react")}'`};let s=t;for(const[r,a]of Object.entries(n))s=s.replaceAll(` from ${r}`,` from ${a}`),s=s.replaceAll(`import ${r}`,`import ${a}`);return s}async function yT(t){if(!globalThis.__crewspacePluginBridge__)return console.warn("[plugin-loader] Bridge registry not initialized, falling back to direct import"),import(t);const n=await fetch(t);if(!n.ok)throw new Error(`Failed to fetch plugin module: ${n.status} ${n.statusText}`);const s=await n.text(),r=bT(s),a=new Blob([r],{type:"application/javascript"}),o=URL.createObjectURL(a);try{return await import(o)}finally{URL.revokeObjectURL(o)}}async function Gj(t){const{pluginId:n,pluginKey:s,slots:r,launchers:a}=t,o=Tx(t),i=La.get(o);if(i==="loaded"||i==="loading"){const m=Li.get(n);m&&await m;return}const l=Li.get(n);if(l&&(await l,La.get(o)==="loaded"))return;La.set(o,"loading");const u=hT(t),d=(async()=>{try{const m=await yT(u),p=new Set;for(const x of r)p.add(x.exportName);for(const x of a)x.exportName&&p.add(x.exportName),vT(x)&&p.add(x.action.target);for(const x of p){const f=m[x];if(f===void 0){console.warn(`Plugin "${s}" declares slot export "${x}" but the module does not export it.`);continue}typeof f=="function"?pT(s,x,f):typeof f=="string"?xT(s,x,f):console.warn(`Plugin "${s}" export "${x}" is neither a function nor a string tag name — skipping.`)}La.set(o,"loaded")}catch(m){La.set(o,"error"),console.error(`Failed to load UI module for plugin "${s}"`,m)}finally{Li.delete(n)}})();Li.set(n,d),await d}function vT(t){return t.action.type==="openModal"||t.action.type==="openDrawer"||t.action.type==="openPopover"}async function jT(t){await Promise.all(t.map(n=>Gj(n)))}async function wT(t){await Gj(t)}function NT(t){for(const n of t){const s=La.get(Tx(n));if(s==="loading"||s==="idle"||s===void 0)return"loading"}return"loaded"}function kT(t){const[,n]=c.useState(0);c.useEffect(()=>{if(!t||t.length===0)return;const s=t.filter(a=>{const o=La.get(Tx(a));return o!=="loaded"&&o!=="loading"});if(s.length===0)return;let r=!1;return jT(s).then(()=>{r||n(a=>a+1)}),()=>{r=!0}},[t])}function yi(t){const n=t.enabled??!0,{data:s,isLoading:r,error:a}=oe({queryKey:N.plugins.uiContributions,queryFn:()=>Mn.listUiContributions(),enabled:n});kT(s);const o=c.useMemo(()=>[...t.slotTypes].sort().join("|"),[t.slotTypes]),i=c.useMemo(()=>{var p;const d=new Set(o.split("|").filter(Boolean)),m=[];for(const x of s??[])for(const f of x.slots)d.has(f.type)&&(uT(f.type)&&(!t.entityType||!((p=f.entityTypes)!=null&&p.includes(t.entityType)))||m.push({...f,pluginId:x.pluginId,pluginKey:x.pluginKey,pluginDisplayName:x.displayName,pluginVersion:x.version}));return m.sort((x,f)=>{const h=x.order??Number.MAX_SAFE_INTEGER,j=f.order??Number.MAX_SAFE_INTEGER;if(h!==j)return h-j;const b=x.pluginDisplayName.localeCompare(f.pluginDisplayName);return b!==0?b:x.displayName.localeCompare(f.displayName)}),m},[s,t.entityType,o]),l=s?NT(s)==="loaded":!0;return{slots:i,isLoading:n&&(r||!l),errorMessage:a?mT(a):null}}class ah extends c.Component{constructor(){super(...arguments);Ci(this,"state",{hasError:!1})}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(s,r){console.error("Plugin slot render failed",{pluginKey:this.props.slot.pluginKey,slotId:this.props.slot.id,error:s,info:r.componentStack})}render(){return this.state.hasError?e.jsxs("div",{className:O("rounded-md border border-destructive/30 bg-destructive/5 px-2 py-1 text-xs text-destructive",this.props.className),children:[this.props.slot.pluginDisplayName,": failed to render"]}):this.props.children}}function CT({tagName:t,slot:n,context:s,className:r}){const a=c.useRef(null);return c.useEffect(()=>{if(!a.current)return;const o=a.current;o.pluginSlot=n,o.pluginContext=s},[s,n]),c.createElement(t,{ref:a,className:r})}function ST(t,n){return{companyId:t.companyId??null,companyPrefix:t.companyPrefix??null,projectId:t.projectId??(t.entityType==="project"?t.entityId??null:null),entityId:t.entityId??null,entityType:t.entityType??null,parentEntityId:t.parentEntityId??null,userId:n,renderEnvironment:null}}function IT({pluginId:t,context:n,children:s}){var l,u;const{data:r}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),a=((l=r==null?void 0:r.user)==null?void 0:l.id)??((u=r==null?void 0:r.session)==null?void 0:u.userId)??null,o=c.useMemo(()=>ST(n,a),[n,a]),i=c.useMemo(()=>({pluginId:t,hostContext:o}),[t,o]);return e.jsx(Ex.Provider,{value:i,children:s})}function vi({slot:t,context:n,className:s,missingBehavior:r="hidden"}){const[,a]=c.useState(0),o=fT(t);if(c.useEffect(()=>{if(o)return;const i=Li.get(t.pluginId);if(!i)return;let l=!1;return i.finally(()=>{l||a(u=>u+1)}),()=>{l=!0}},[o,t.pluginId]),!o)return r==="hidden"?null:e.jsxs("div",{className:O("rounded-md border border-dashed border-border px-2 py-1 text-xs text-muted-foreground",s),children:[t.pluginDisplayName,": ",t.displayName]});if(o.kind==="react"){const i=c.createElement(o.component,{slot:t,context:n});return e.jsx(ah,{slot:t,className:s,children:e.jsx(IT,{pluginId:t.pluginId,context:n,children:s?e.jsx("div",{className:s,children:i}):i})})}return e.jsx(ah,{slot:t,className:s,children:e.jsx(CT,{tagName:o.tagName,slot:t,context:n,className:s})})}function Vr({slotTypes:t,context:n,entityType:s,className:r,itemClassName:a,errorClassName:o,missingBehavior:i="hidden"}){const{slots:l,errorMessage:u}=yi({slotTypes:t,entityType:s,companyId:n.companyId});return u?e.jsxs("div",{className:O("rounded-md border border-destructive/30 bg-destructive/5 px-2 py-1 text-xs text-destructive",o),children:["Plugin extensions unavailable: ",u]}):l.length===0?null:e.jsx("div",{className:r,children:l.map(d=>e.jsx(vi,{slot:d,context:n,className:a,missingBehavior:i},`${d.pluginKey}:${d.id}`))})}function _T({activeProjectRef:t,companyId:n,companyPrefix:s,isMobile:r,project:a,projectSidebarSlots:o,setSidebarOpen:i}){const{attributes:l,listeners:u,setNodeRef:d,transform:m,transition:p,isDragging:x}=_x({id:a.id}),f=Al(a);return e.jsx("div",{ref:d,style:{transform:Er.Transform.toString(m),transition:p,zIndex:x?10:void 0},className:O(x&&"opacity-80"),...l,...u,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs(Cl,{to:`/projects/${f}/issues`,onClick:()=>{r&&i(!1)},className:O("flex items-center gap-2.5 px-3 py-1.5 text-[13px] font-medium transition-colors",t===f||t===a.id?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[e.jsx("span",{className:"shrink-0 h-3.5 w-3.5 rounded-sm",style:{backgroundColor:a.color??"#6366f1"}}),e.jsx("span",{className:"flex-1 truncate",children:a.name}),a.pauseReason==="budget"?e.jsx(Wj,{title:"Project paused by budget"}):null]}),o.length>0&&e.jsx("div",{className:"ml-5 flex flex-col gap-0.5",children:o.map(h=>e.jsx(vi,{slot:h,context:{companyId:n,companyPrefix:s,projectId:a.id,projectRef:f,entityId:a.id,entityType:"project"},missingBehavior:"placeholder"},`${a.id}:${h.pluginKey}:${h.id}`))})]})})}function AT(){var v,_;const[t,n]=c.useState(!0),{selectedCompany:s,selectedCompanyId:r}=et(),{openNewProject:a}=In(),{isMobile:o,setSidebarOpen:i}=mr(),l=fn(),{data:u}=oe({queryKey:N.projects.list(r),queryFn:()=>en.list(r),enabled:!!r}),{data:d}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),{slots:m}=yi({slotTypes:["projectSidebarItem"],entityType:"project",enabled:!!r}),p=((v=d==null?void 0:d.user)==null?void 0:v.id)??((_=d==null?void 0:d.session)==null?void 0:_.userId)??null,x=c.useMemo(()=>(u??[]).filter(E=>!E.archivedAt),[u]),{orderedProjects:f,persistOrder:h}=$l({projects:x,companyId:r,userId:p}),j=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/),b=(j==null?void 0:j[1])??null,g=bx(gx(Nx,{activationConstraint:{distance:8}})),y=c.useCallback(E=>{const{active:S,over:M}=E;if(!M||S.id===M.id)return;const B=f.map($=>$.id),k=B.indexOf(S.id),L=B.indexOf(M.id);k===-1||L===-1||h(Vd(B,k,L))},[f,h]);return e.jsxs(Sa,{open:t,onOpenChange:n,children:[e.jsx("div",{className:"group",children:e.jsxs("div",{className:"flex items-center px-3 py-1.5",children:[e.jsxs(Ia,{className:"flex items-center gap-1 flex-1 min-w-0",children:[e.jsx(sn,{className:O("h-3 w-3 text-muted-foreground/60 transition-transform opacity-0 group-hover:opacity-100",t&&"rotate-90")}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-widest font-mono text-muted-foreground/60",children:"Projects"})]}),e.jsx("button",{onClick:E=>{E.stopPropagation(),a()},className:"flex items-center justify-center h-4 w-4 rounded text-muted-foreground/60 hover:text-foreground hover:bg-accent/50 transition-colors","aria-label":"New project",children:e.jsx(Ot,{className:"h-3 w-3"})})]})}),e.jsx(_a,{children:e.jsx(Cx,{sensors:g,collisionDetection:xj,onDragEnd:y,children:e.jsx(Ix,{items:f.map(E=>E.id),strategy:Sx,children:e.jsx("div",{className:"flex flex-col gap-0.5 mt-0.5",children:f.map(E=>e.jsx(_T,{activeProjectRef:b,companyId:r,companyPrefix:(s==null?void 0:s.issuePrefix)??null,isMobile:o,project:E,projectSidebarSlots:m,setSidebarOpen:i},E.id))})})})})]})}function ET(t,n){if(!n)return t;const s=t.includes("?")?"&":"?";return`${t}${s}companyId=${encodeURIComponent(n)}`}function Jt(t,n,s=""){return ET(`/agents/${encodeURIComponent(t)}${s}`,n)}const We={list:t=>ne.get(`/companies/${t}/agents`),org:t=>ne.get(`/companies/${t}/org`),listConfigurations:t=>ne.get(`/companies/${t}/agent-configurations`),get:async(t,n)=>{try{return await ne.get(Jt(t,n))}catch(s){if(!(s instanceof Qr)||s.status!==409||!n||qd(t))throw s;const r=dl(t);if(!r)throw s;const o=(await ne.get(`/companies/${n}/agents`)).filter(i=>i.status!=="terminated"&&dl(i.urlKey)===r);if(o.length!==1)throw s;return ne.get(Jt(o[0].id,n))}},getConfiguration:(t,n)=>ne.get(Jt(t,n,"/configuration")),listConfigRevisions:(t,n)=>ne.get(Jt(t,n,"/config-revisions")),getConfigRevision:(t,n,s)=>ne.get(Jt(t,s,`/config-revisions/${n}`)),rollbackConfigRevision:(t,n,s)=>ne.post(Jt(t,s,`/config-revisions/${n}/rollback`),{}),create:(t,n)=>ne.post(`/companies/${t}/agents`,n),hire:(t,n)=>ne.post(`/companies/${t}/agent-hires`,n),update:(t,n,s)=>ne.patch(Jt(t,s),n),updatePermissions:(t,n,s)=>ne.patch(Jt(t,s,"/permissions"),n),instructionsBundle:(t,n)=>ne.get(Jt(t,n,"/instructions-bundle")),updateInstructionsBundle:(t,n,s)=>ne.patch(Jt(t,s,"/instructions-bundle"),n),instructionsFile:(t,n,s)=>ne.get(Jt(t,s,`/instructions-bundle/file?path=${encodeURIComponent(n)}`)),saveInstructionsFile:(t,n,s)=>ne.put(Jt(t,s,"/instructions-bundle/file"),n),deleteInstructionsFile:(t,n,s)=>ne.delete(Jt(t,s,`/instructions-bundle/file?path=${encodeURIComponent(n)}`)),pause:(t,n)=>ne.post(Jt(t,n,"/pause"),{}),resume:(t,n)=>ne.post(Jt(t,n,"/resume"),{}),terminate:(t,n)=>ne.post(Jt(t,n,"/terminate"),{}),remove:(t,n)=>ne.delete(Jt(t,n)),listKeys:(t,n)=>ne.get(Jt(t,n,"/keys")),skills:(t,n)=>ne.get(Jt(t,n,"/skills")),syncSkills:(t,n,s)=>ne.post(Jt(t,s,"/skills/sync"),{desiredSkills:n}),createKey:(t,n,s)=>ne.post(Jt(t,s,"/keys"),{name:n}),revokeKey:(t,n,s)=>ne.delete(Jt(t,s,`/keys/${encodeURIComponent(n)}`)),runtimeState:(t,n)=>ne.get(Jt(t,n,"/runtime-state")),taskSessions:(t,n)=>ne.get(Jt(t,n,"/task-sessions")),resetSession:(t,n,s)=>ne.post(Jt(t,s,"/runtime-state/reset-session"),{taskKey:n??null}),adapterModels:(t,n)=>ne.get(`/companies/${encodeURIComponent(t)}/adapters/${encodeURIComponent(n)}/models`),detectModel:(t,n)=>ne.get(`/companies/${encodeURIComponent(t)}/adapters/${encodeURIComponent(n)}/detect-model`),testEnvironment:(t,n,s)=>ne.post(`/companies/${t}/adapters/${n}/test-environment`,s),invoke:(t,n)=>ne.post(Jt(t,n,"/heartbeat/invoke"),{}),wakeup:(t,n,s)=>ne.post(Jt(t,s,"/wakeup"),n),loginWithClaude:(t,n)=>ne.post(Jt(t,n,"/claude-login"),{}),availableSkills:()=>ne.get("/skills/available"),heartbeatRun:t=>ne.get(`/heartbeat-runs/${t}`),heartbeatRunEvents:(t,n=0)=>ne.get(`/heartbeat-runs/${t}/events?afterSeq=${n}`),chatStream:async function*(t,n,s,r){const a=await fetch(`/api${Jt(t,s,"/chat")}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({messages:n}),signal:r});if(!a.ok||!a.body){const u=await a.json().catch(()=>({error:`HTTP ${a.status}`}));throw new Error(u.error??`HTTP ${a.status}`)}const o=a.body.getReader(),i=new TextDecoder;let l="";for(;;){const{done:u,value:d}=await o.read();if(u)break;l+=i.decode(d,{stream:!0});const m=l.split(`
|
|
33
|
+
`);l=m.pop()??"";for(const p of m){if(!p.startsWith("data: "))continue;const x=p.slice(6).trim();if(x==="[DONE]")return;try{const f=JSON.parse(x);if(f.err)throw new Error(f.err);f.t&&(yield f.t)}catch{}}}}},qm="crewspace:agent-order-updated",TT="crewspace.agentOrder",oh="anonymous";function Jj(t){return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function RT(t){if(!t)return oh;const n=t.trim();return n.length>0?n:oh}function Zj(t,n){return`${TT}:${t}:${RT(n)}`}function Nu(t){try{const n=localStorage.getItem(t);return n?Jj(JSON.parse(n)):[]}catch{return[]}}function Yj(t,n){const s=Jj(n);try{localStorage.setItem(t,JSON.stringify(s))}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(qm,{detail:{storageKey:t,orderedIds:s}}))}function PT(t){if(t.length===0)return[];const n=new Map(t.map(o=>[o.id,o])),s=new Map;for(const o of t){const i=o.reportsTo&&n.has(o.reportsTo)?o.reportsTo:null,l=s.get(i)??[];l.push(o),s.set(i,l)}for(const o of s.values())o.sort((i,l)=>i.name.localeCompare(l.name));const r=[],a=[...s.get(null)??[]];for(;a.length>0;){const o=a.shift();if(!o)continue;r.push(o);const i=s.get(o.id);i&&a.push(...i)}return r}function Um(t,n){if(t.length===0)return[];const s=PT(t);if(n.length===0)return s;const r=new Map(s.map(o=>[o.id,o])),a=[];for(const o of n){const i=r.get(o);i&&(a.push(i),r.delete(o))}for(const o of s)r.has(o.id)&&(a.push(o),r.delete(o.id));return a}function ku(t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s+=1)if(t[s]!==n[s])return!1;return!0}function Cu(t,n){return Um(t,n).map(s=>s.id)}function Xj({agents:t,companyId:n,userId:s}){const r=c.useMemo(()=>n?Zj(n,s):null,[n,s]),[a,o]=c.useState(()=>r?Cu(t,Nu(r)):t.map(u=>u.id));c.useEffect(()=>{const u=r?Cu(t,Nu(r)):t.map(d=>d.id);o(d=>ku(d,u)?d:u)},[t,r]),c.useEffect(()=>{if(!r)return;const u=p=>{const x=Cu(t,p);o(f=>ku(f,x)?f:x)},d=p=>{p.key===r&&u(Nu(r))},m=p=>{const x=p.detail;!x||x.storageKey!==r||u(x.orderedIds)};return window.addEventListener("storage",d),window.addEventListener(qm,m),()=>{window.removeEventListener("storage",d),window.removeEventListener(qm,m)}},[t,r]);const i=c.useMemo(()=>Um(t,a),[t,a]),l=c.useCallback(u=>{const d=new Set(t.map(p=>p.id)),m=u.filter(p=>d.has(p));for(const p of Um(t,[]))m.includes(p.id)||m.push(p.id);o(p=>ku(p,m)?p:m),r&&Yj(r,m)},[t,r]);return{orderedAgents:i,orderedIds:a,persistOrder:l}}function Ht({...t}){return e.jsx(Kk,{"data-slot":"popover",...t})}function Vt({...t}){return e.jsx(zk,{"data-slot":"popover-trigger",...t})}function Qt({className:t,align:n="center",sideOffset:s=4,disablePortal:r=!1,...a}){const o=e.jsx(Wk,{"data-slot":"popover-content",align:n,sideOffset:s,className:O("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...a});return r?o:e.jsx(Hk,{children:o})}function Xt({className:t,type:n,...s}){return e.jsx("input",{type:n,"data-slot":"input",className:O("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",t),...s})}const Bm={bot:ss,cpu:gm,brain:Ko,zap:Xo,rocket:hm,code:_p,terminal:kd,shield:Ip,eye:pi,search:ws,wrench:tl,hammer:u1,lightbulb:Vb,sparkles:xo,star:d1,heart:$i,flame:c1,bug:l1,cog:i1,database:o1,globe:Hb,lock:a1,mail:Wb,"message-square":zb,"file-code":r1,"git-branch":Yo,package:el,puzzle:Bo,target:Ir,wand:s1,atom:n1,"circuit-board":t1,radar:e1,swords:XC,telescope:YC,microscope:ZC,crown:JC,gem:Sp,hexagon:Sr,pentagon:GC,fingerprint:QC},MT="bot";function e0(t){return t&&ax.includes(t)?Bm[t]:Bm[MT]}const $T="bot";function Cn({icon:t,className:n}){const s=e0(t);return e.jsx(s,{className:n})}function DT({value:t,onChange:n,children:s}){const[r,a]=c.useState(!1),[o,i]=c.useState(""),l=c.useMemo(()=>{const u=ax.map(m=>[m,Bm[m]]);if(!o)return u;const d=o.toLowerCase();return u.filter(([m])=>m.includes(d))},[o]);return e.jsxs(Ht,{open:r,onOpenChange:a,children:[e.jsx(Vt,{asChild:!0,children:s}),e.jsxs(Qt,{className:"w-72 p-3",align:"start",children:[e.jsx(Xt,{placeholder:"Search icons...",value:o,onChange:u=>i(u.target.value),className:"mb-2 h-8 text-sm",autoFocus:!0}),e.jsxs("div",{className:"grid grid-cols-7 gap-1 max-h-48 overflow-y-auto",children:[l.map(([u,d])=>e.jsx("button",{onClick:()=>{n(u),a(!1),i("")},className:O("flex items-center justify-center h-8 w-8 rounded hover:bg-accent transition-colors",(t??$T)===u&&"bg-accent ring-1 ring-primary"),title:u,children:e.jsx(d,{className:"h-4 w-4"})},u)),l.length===0&&e.jsx("p",{className:"col-span-7 text-xs text-muted-foreground text-center py-2",children:"No icons match"})]})]})]})}function OT(){var g,y;const[t,n]=c.useState(!0),{selectedCompanyId:s}=et(),{openNewAgent:r}=In(),{isMobile:a,setSidebarOpen:o}=mr(),i=fn(),{data:l}=oe({queryKey:N.agents.list(s),queryFn:()=>We.list(s),enabled:!!s}),{data:u}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),{data:d}=oe({queryKey:N.liveRuns(s),queryFn:()=>Yt.liveRunsForCompany(s),enabled:!!s,refetchInterval:1e4}),m=c.useMemo(()=>{const v=new Map;for(const _ of d??[])v.set(_.agentId,(v.get(_.agentId)??0)+1);return v},[d]),p=c.useMemo(()=>(l??[]).filter(_=>_.status!=="terminated"),[l]),x=((g=u==null?void 0:u.user)==null?void 0:g.id)??((y=u==null?void 0:u.session)==null?void 0:y.userId)??null,{orderedAgents:f}=Xj({agents:p,companyId:s,userId:x}),h=i.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),j=(h==null?void 0:h[1])??null,b=(h==null?void 0:h[2])??null;return e.jsxs(Sa,{open:t,onOpenChange:n,children:[e.jsx("div",{className:"group",children:e.jsxs("div",{className:"flex items-center px-3 py-1.5",children:[e.jsxs(Ia,{className:"flex items-center gap-1 flex-1 min-w-0",children:[e.jsx(sn,{className:O("h-3 w-3 text-muted-foreground/60 transition-transform opacity-0 group-hover:opacity-100",t&&"rotate-90")}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-widest font-mono text-muted-foreground/60",children:"Agents"})]}),e.jsx("button",{onClick:v=>{v.stopPropagation(),r()},className:"flex items-center justify-center h-4 w-4 rounded text-muted-foreground/60 hover:text-foreground hover:bg-accent/50 transition-colors","aria-label":"New agent",children:e.jsx(Ot,{className:"h-3 w-3"})})]})}),e.jsx(_a,{children:e.jsx("div",{className:"flex flex-col gap-0.5 mt-0.5",children:f.map(v=>{const _=m.get(v.id)??0;return e.jsxs(Cl,{to:b?`${Na(v)}/${b}`:Na(v),onClick:()=>{a&&o(!1)},className:O("flex items-center gap-2.5 px-3 py-1.5 text-[13px] font-medium transition-colors",j===so(v)?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[e.jsx(Cn,{icon:v.icon,className:"shrink-0 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:v.name}),(v.pauseReason==="budget"||_>0)&&e.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[v.pauseReason==="budget"?e.jsx(Wj,{title:"Agent paused by budget"}):null,_>0?e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}):null,_>0?e.jsxs("span",{className:"text-[11px] font-medium text-blue-600 dark:text-blue-400",children:[_," live"]}):null]})]},v.id)})})})]})}const Hl=50,t0=c.createContext(null);function LT({children:t}){const[n,s]=c.useState([]),[r,a]=c.useState(null),[o,i]=c.useState(!1),l=c.useCallback(p=>{i(!0),s(x=>{const f=x.find(b=>b.primaryAgentId===p.id&&b.participants.length===1);if(f)return a(f.id),x;const h={id:`session-${Date.now()}`,primaryAgentId:p.id,participants:[p],messages:[],updatedAt:new Date};a(h.id);const j=[...x,h];return j.length>Hl?j.sort((b,g)=>g.updatedAt.getTime()-b.updatedAt.getTime()).slice(0,Hl):j})},[]),u=c.useCallback(p=>{if(p.length!==0){if(p.length===1){l(p[0]);return}i(!0),s(x=>{const f={id:`session-${Date.now()}`,primaryAgentId:p[0].id,participants:p,messages:[],updatedAt:new Date};a(f.id);const h=[...x,f];return h.length>Hl?h.sort((j,b)=>b.updatedAt.getTime()-j.updatedAt.getTime()).slice(0,Hl):h})}},[l]),d=c.useCallback((p,x,f)=>{s(h=>h.map(j=>j.id===p?{...j,messages:x,participants:f,updatedAt:new Date}:j))},[]),m=c.useCallback(p=>{s(x=>x.length>0?x:p.map((f,h)=>({id:`session-init-${f.id}`,primaryAgentId:f.id,participants:[f],messages:[],updatedAt:new Date(Date.now()-h*1e3)})))},[]);return e.jsx(t0.Provider,{value:{sessions:n,activeSessionId:r,setActiveSessionId:a,openChatWithAgent:l,openChatWithAgents:u,updateSession:d,bulkInitSessions:m,isChatOpen:o,setIsChatOpen:i},children:t})}function Rx(){const t=c.useContext(t0);if(!t)throw new Error("useChat must be used within ChatProvider");return t}const ms={createCompanyInvite:(t,n={})=>ne.post(`/companies/${t}/invites`,n),createOpenClawInvitePrompt:(t,n={})=>ne.post(`/companies/${t}/openclaw/invite-prompt`,n),getInvite:t=>ne.get(`/invites/${t}`),getInviteOnboarding:t=>ne.get(`/invites/${t}/onboarding`),acceptInvite:(t,n)=>ne.post(`/invites/${t}/accept`,n),listJoinRequests:(t,n="pending_approval")=>ne.get(`/companies/${t}/join-requests?status=${n}`),approveJoinRequest:(t,n)=>ne.post(`/companies/${t}/join-requests/${n}/approve`,{}),rejectJoinRequest:(t,n)=>ne.post(`/companies/${t}/join-requests/${n}/reject`,{}),claimJoinRequestApiKey:(t,n)=>ne.post(`/join-requests/${t}/claim-api-key`,{claimSecret:n}),getBoardClaimStatus:(t,n)=>ne.get(`/board-claim/${t}?code=${encodeURIComponent(n)}`),claimBoard:(t,n)=>ne.post(`/board-claim/${t}/claim`,{code:n}),getCliAuthChallenge:(t,n)=>ne.get(`/cli-auth/challenges/${t}?token=${encodeURIComponent(n)}`),approveCliAuthChallenge:(t,n)=>ne.post(`/cli-auth/challenges/${t}/approve`,{token:n}),cancelCliAuthChallenge:(t,n)=>ne.post(`/cli-auth/challenges/${t}/cancel`,{token:n})},Wn={list:(t,n)=>ne.get(`/companies/${t}/approvals${n?`?status=${encodeURIComponent(n)}`:""}`),create:(t,n)=>ne.post(`/companies/${t}/approvals`,n),get:t=>ne.get(`/approvals/${t}`),approve:(t,n)=>ne.post(`/approvals/${t}/approve`,{decisionNote:n}),reject:(t,n)=>ne.post(`/approvals/${t}/reject`,{decisionNote:n}),requestRevision:(t,n)=>ne.post(`/approvals/${t}/request-revision`,{decisionNote:n}),resubmit:(t,n)=>ne.post(`/approvals/${t}/resubmit`,{payload:n}),listComments:t=>ne.get(`/approvals/${t}/comments`),addComment:(t,n)=>ne.post(`/approvals/${t}/comments`,{body:n}),listIssues:t=>ne.get(`/approvals/${t}/issues`)},Px={summary:t=>ne.get(`/companies/${t}/dashboard`)},nt={list:(t,n)=>{const s=new URLSearchParams;n!=null&&n.status&&s.set("status",n.status),n!=null&&n.projectId&&s.set("projectId",n.projectId),n!=null&&n.assigneeAgentId&&s.set("assigneeAgentId",n.assigneeAgentId),n!=null&&n.participantAgentId&&s.set("participantAgentId",n.participantAgentId),n!=null&&n.assigneeUserId&&s.set("assigneeUserId",n.assigneeUserId),n!=null&&n.touchedByUserId&&s.set("touchedByUserId",n.touchedByUserId),n!=null&&n.inboxArchivedByUserId&&s.set("inboxArchivedByUserId",n.inboxArchivedByUserId),n!=null&&n.unreadForUserId&&s.set("unreadForUserId",n.unreadForUserId),n!=null&&n.labelId&&s.set("labelId",n.labelId),n!=null&&n.executionWorkspaceId&&s.set("executionWorkspaceId",n.executionWorkspaceId),n!=null&&n.originKind&&s.set("originKind",n.originKind),n!=null&&n.originId&&s.set("originId",n.originId),n!=null&&n.includeRoutineExecutions&&s.set("includeRoutineExecutions","true"),n!=null&&n.q&&s.set("q",n.q);const r=s.toString();return ne.get(`/companies/${t}/issues${r?`?${r}`:""}`)},listLabels:t=>ne.get(`/companies/${t}/labels`),createLabel:(t,n)=>ne.post(`/companies/${t}/labels`,n),deleteLabel:t=>ne.delete(`/labels/${t}`),get:t=>ne.get(`/issues/${t}`),markRead:t=>ne.post(`/issues/${t}/read`,{}),markUnread:t=>ne.delete(`/issues/${t}/read`),archiveFromInbox:t=>ne.post(`/issues/${t}/inbox-archive`,{}),unarchiveFromInbox:t=>ne.delete(`/issues/${t}/inbox-archive`),create:(t,n)=>ne.post(`/companies/${t}/issues`,n),update:(t,n)=>ne.patch(`/issues/${t}`,n),remove:t=>ne.delete(`/issues/${t}`),checkout:(t,n)=>ne.post(`/issues/${t}/checkout`,{agentId:n,expectedStatuses:["todo","backlog","blocked"]}),release:t=>ne.post(`/issues/${t}/release`,{}),listComments:t=>ne.get(`/issues/${t}/comments`),addComment:(t,n,s,r)=>ne.post(`/issues/${t}/comments`,{body:n,...s===void 0?{}:{reopen:s},...r===void 0?{}:{interrupt:r}}),listDocuments:t=>ne.get(`/issues/${t}/documents`),getDocument:(t,n)=>ne.get(`/issues/${t}/documents/${encodeURIComponent(n)}`),upsertDocument:(t,n,s)=>ne.put(`/issues/${t}/documents/${encodeURIComponent(n)}`,s),listDocumentRevisions:(t,n)=>ne.get(`/issues/${t}/documents/${encodeURIComponent(n)}/revisions`),restoreDocumentRevision:(t,n,s)=>ne.post(`/issues/${t}/documents/${encodeURIComponent(n)}/revisions/${s}/restore`,{}),deleteDocument:(t,n)=>ne.delete(`/issues/${t}/documents/${encodeURIComponent(n)}`),listAttachments:t=>ne.get(`/issues/${t}/attachments`),uploadAttachment:(t,n,s,r)=>{const a=new FormData;return a.append("file",s),r&&a.append("issueCommentId",r),ne.postForm(`/companies/${t}/issues/${n}/attachments`,a)},deleteAttachment:t=>ne.delete(`/attachments/${t}`),listApprovals:t=>ne.get(`/issues/${t}/approvals`),linkApproval:(t,n)=>ne.post(`/issues/${t}/approvals`,{approvalId:n}),unlinkApproval:(t,n)=>ne.delete(`/issues/${t}/approvals/${n}`),listWorkProducts:t=>ne.get(`/issues/${t}/work-products`),createWorkProduct:(t,n)=>ne.post(`/issues/${t}/work-products`,n),updateWorkProduct:(t,n)=>ne.patch(`/work-products/${t}`,n),deleteWorkProduct:t=>ne.delete(`/work-products/${t}`)},FT=100,qT=new Set(["failed","timed_out"]),Gc=new Set(["pending","revision_requested"]),n0="crewspace:inbox:dismissed",Mx="crewspace:inbox:read-items",s0="crewspace:inbox:last-tab";function ih(){try{const t=localStorage.getItem(n0);return t?new Set(JSON.parse(t)):new Set}catch{return new Set}}function UT(t){try{localStorage.setItem(n0,JSON.stringify([...t]))}catch{}}function lh(){try{const t=localStorage.getItem(Mx);return t?new Set(JSON.parse(t)):new Set}catch{return new Set}}function ch(t){try{localStorage.setItem(Mx,JSON.stringify([...t]))}catch{}}function BT(){try{const t=localStorage.getItem(s0);return t==="all"||t==="unread"||t==="recent"||t==="mine"?t:"mine"}catch{return"mine"}}function KT(t){try{localStorage.setItem(s0,t)}catch{}}function zT(t){return t==="mine"}function WT(t,n){return n===0||t<0?-1:Math.min(t,n-1)}function dh(t,n,s){return n===0?-1:t<0?0:s==="next"?Math.min(t+1,n-1):Math.max(t-1,0)}function r0(t){const n=[...t].sort((r,a)=>new Date(a.createdAt).getTime()-new Date(r.createdAt).getTime()),s=new Map;for(const r of n)s.has(r.agentId)||s.set(r.agentId,r);return Array.from(s.values()).filter(r=>qT.has(r.status))}function Tr(t){if(!t)return 0;const n=new Date(t).getTime();return Number.isFinite(n)?n:0}function Km(t){const n=Tr(t.lastExternalCommentAt);return n>0?n:Tr(t.updatedAt)}function a0(t,n){const s=Km(n)-Km(t);return s!==0?s:Tr(n.updatedAt)-Tr(t.updatedAt)}function zm(t){return[...t].sort(a0).slice(0,FT)}function HT(t,n,s){const r=[...t].sort((a,o)=>Tr(o.updatedAt)-Tr(a.updatedAt));return n==="mine"||n==="recent"?r:n==="unread"?r.filter(a=>Gc.has(a.status)):s==="all"?r:r.filter(a=>{const o=Gc.has(a.status);return s==="actionable"?o:!o})}function Su(t){const n=Tr(t.updatedAt);return n>0?n:Tr(t.createdAt)}function VT({issues:t,approvals:n,failedRuns:s=[],joinRequests:r=[]}){return[...t.map(a=>({kind:"issue",timestamp:Km(a),issue:a})),...n.map(a=>({kind:"approval",timestamp:Su(a),approval:a})),...s.map(a=>({kind:"failed_run",timestamp:Tr(a.createdAt),run:a})),...r.map(a=>({kind:"join_request",timestamp:Tr(a.createdAt),joinRequest:a}))].sort((a,o)=>{const i=o.timestamp-a.timestamp;return i!==0?i:a.kind==="issue"&&o.kind==="issue"?a0(a.issue,o.issue):a.kind==="approval"&&o.kind==="approval"?Su(o.approval)-Su(a.approval):a.kind==="approval"?-1:1})}function QT({tab:t,hasItems:n,showOnMine:s,showOnRecent:r,showOnUnread:a,showOnAll:o}){return n?t==="mine"?s:t==="recent"?r:t==="unread"?a:o:!1}function GT({approvals:t,joinRequests:n,dashboard:s,heartbeatRuns:r,mineIssues:a,dismissed:o}){const i=t.filter(b=>Gc.has(b.status)&&!o.has(`approval:${b.id}`)).length,l=r0(r).filter(b=>!o.has(`run:${b.id}`)).length,u=n.filter(b=>!o.has(`join:${b.id}`)).length,d=a.length,m=(s==null?void 0:s.agents.error)??0,p=(s==null?void 0:s.costs.monthBudgetCents)??0,x=(s==null?void 0:s.costs.monthUtilizationPercent)??0,f=m>0&&l===0&&!o.has("alert:agent-errors"),h=p>0&&x>=80&&!o.has("alert:budget"),j=Number(f)+Number(h);return{inbox:i+u+l+d+j,approvals:i,failedRuns:l,joinRequests:u,mineIssues:d,alerts:j}}const JT="backlog,todo,in_progress,in_review,blocked,done";function o0(){const[t,n]=c.useState(ih);return c.useEffect(()=>{const r=a=>{a.key==="crewspace:inbox:dismissed"&&n(ih())};return window.addEventListener("storage",r),()=>window.removeEventListener("storage",r)},[]),{dismissed:t,dismiss:r=>{n(a=>{const o=new Set(a);return o.add(r),UT(o),o})}}}function ZT(){const[t,n]=c.useState(lh);return c.useEffect(()=>{const a=o=>{o.key===Mx&&n(lh())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),{readItems:t,markRead:a=>{n(o=>{const i=new Set(o);return i.add(a),ch(i),i})},markUnread:a=>{n(o=>{const i=new Set(o);return i.delete(a),ch(i),i})}}}function i0(t){const{dismissed:n}=o0(),{data:s=[]}=oe({queryKey:N.approvals.list(t),queryFn:()=>Wn.list(t),enabled:!!t}),{data:r=[]}=oe({queryKey:N.access.joinRequests(t),queryFn:async()=>{try{return await ms.listJoinRequests(t,"pending_approval")}catch(u){if(u instanceof Qr&&(u.status===401||u.status===403))return[];throw u}},enabled:!!t,retry:!1}),{data:a}=oe({queryKey:N.dashboard(t),queryFn:()=>Px.summary(t),enabled:!!t}),{data:o=[]}=oe({queryKey:N.issues.listMineByMe(t),queryFn:()=>nt.list(t,{touchedByUserId:"me",inboxArchivedByUserId:"me",status:JT}),enabled:!!t}),i=c.useMemo(()=>zm(o),[o]),{data:l=[]}=oe({queryKey:N.heartbeats(t),queryFn:()=>Yt.list(t),enabled:!!t});return c.useMemo(()=>GT({approvals:s,joinRequests:r,dashboard:a,heartbeatRuns:l,mineIssues:i,dismissed:n}),[s,r,a,l,i,n])}function uh(){const{openNewIssue:t}=In(),{selectedCompanyId:n,selectedCompany:s}=et(),{sessions:r}=Rx(),a=i0(n),{data:o}=oe({queryKey:N.liveRuns(n),queryFn:()=>Yt.liveRunsForCompany(n),enabled:!!n,refetchInterval:1e4}),i=(o==null?void 0:o.length)??0;function l(){document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0}))}const u={companyId:n,companyPrefix:(s==null?void 0:s.issuePrefix)??null};return e.jsxs("aside",{className:"w-60 h-full min-h-0 border-r border-border bg-background flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 h-13 shrink-0 border-b border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("div",{className:"w-6 h-6 rounded-md bg-primary flex items-center justify-center shrink-0",children:e.jsx(Xo,{className:"h-3.5 w-3.5 text-primary-foreground",fill:"currentColor"})}),e.jsx("span",{className:"text-sm font-bold text-foreground tracking-tight",children:"CrewSpace"}),(s==null?void 0:s.brandColor)&&e.jsx("div",{className:"w-1.5 h-1.5 rounded-full shrink-0 ml-0.5",style:{backgroundColor:s.brandColor}}),s&&e.jsx("span",{className:"text-xs text-muted-foreground truncate font-normal",children:s.name})]}),e.jsx(G,{variant:"ghost",size:"icon-sm",className:"text-muted-foreground shrink-0",onClick:l,children:e.jsx(ws,{className:"h-3.5 w-3.5"})})]}),e.jsxs("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-3 px-3 py-3",children:[e.jsx("div",{className:"flex flex-col gap-0.5",children:e.jsxs("button",{onClick:()=>t(),className:"flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium rounded-md bg-primary/10 text-primary hover:bg-primary/15 transition-colors",children:[e.jsx(Ap,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"New Task"})]})}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx(Ln,{to:"/dashboard",label:"Dashboard",icon:Ka,liveCount:i}),e.jsx(Ln,{to:"/inbox",label:"Inbox",icon:Ga,badge:a.inbox,badgeTone:a.failedRuns>0?"danger":"default",alert:a.failedRuns>0}),e.jsx(Vr,{slotTypes:["sidebar"],context:u,className:"flex flex-col gap-0.5",itemClassName:"text-[13px] font-medium",missingBehavior:"placeholder"})]}),e.jsxs(hu,{label:"Work",children:[e.jsx(Ln,{to:"/issues",label:"Issues",icon:rs}),e.jsx(Ln,{to:"/taskboard",label:"Board",icon:m1}),e.jsx(Ln,{to:"/blockers",label:"Alerts",icon:Ja}),e.jsx(Ln,{to:"/routines",label:"Routines",icon:nl,textBadge:"Beta",textBadgeTone:"amber"}),e.jsx(Ln,{to:"/goals",label:"Goals",icon:Ir})]}),e.jsx(AT,{}),e.jsx(OT,{}),e.jsxs(hu,{label:"Intelligence",children:[e.jsx(Ln,{to:"/org",label:"Org Chart",icon:bm}),e.jsx(Ln,{to:"/memory",label:"Memory Graph",icon:Ko}),e.jsx(Ln,{to:"/agent-chat",label:"Agent Chat",icon:wc,badge:r.length>0?r.length:void 0}),e.jsx(Ln,{to:"/office",label:"3D Office",icon:xc})]}),e.jsxs(hu,{label:"System",children:[e.jsx(Ln,{to:"/skills",label:"Skills",icon:Cd}),e.jsx(Ln,{to:"/costs",label:"Costs",icon:wr}),e.jsx(Ln,{to:"/activity",label:"Activity",icon:sl}),e.jsx(Ln,{to:"/company/settings",label:"Settings",icon:zr})]}),e.jsx(Vr,{slotTypes:["sidebarPanel"],context:u,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}function mh(){const{data:t}=oe({queryKey:N.plugins.all,queryFn:()=>Mn.list()});return e.jsxs("aside",{className:"w-60 h-full min-h-0 border-r border-border bg-background flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0",children:[e.jsx(zr,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-1"}),e.jsx("span",{className:"flex-1 text-sm font-bold text-foreground truncate",children:"Instance Settings"})]}),e.jsx("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 px-3 py-2",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx(Ln,{to:"/instance/settings/general",label:"General",icon:rl,end:!0}),e.jsx(Ln,{to:"/instance/settings/heartbeats",label:"Heartbeats",icon:Nl,end:!0}),e.jsx(Ln,{to:"/instance/settings/experimental",label:"Experimental",icon:Sd}),e.jsx(Ln,{to:"/instance/settings/plugins",label:"Plugins",icon:Bo}),(t??[]).length>0?e.jsx("div",{className:"ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3",children:(t??[]).map(n=>e.jsx(Cl,{to:`/instance/settings/plugins/${n.id}`,className:({isActive:s})=>["rounded-md px-2 py-1.5 text-xs transition-colors",s?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),children:n.manifestJson.displayName??n.packageName},n.id))}):null]})})]})}const l0=c.createContext(null);function YT({children:t}){const[n,s]=c.useState([]),r=c.useCallback(a=>{s(a)},[]);return c.useEffect(()=>{if(n.length===0)document.title="CrewSpace";else{const a=[...n].reverse().map(o=>o.label);document.title=`${a.join(" · ")} · CrewSpace`}},[n]),e.jsx(l0.Provider,{value:{breadcrumbs:n,setBreadcrumbs:r},children:t})}function Ft(){const t=c.useContext(l0);if(!t)throw new Error("useBreadcrumbs must be used within BreadcrumbProvider");return t}function c0({...t}){return e.jsx("nav",{"aria-label":"breadcrumb","data-slot":"breadcrumb",...t})}function d0({className:t,...n}){return e.jsx("ol",{"data-slot":"breadcrumb-list",className:O("text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",t),...n})}function hc({className:t,...n}){return e.jsx("li",{"data-slot":"breadcrumb-item",className:O("inline-flex items-center gap-1.5",t),...n})}function Wm({asChild:t,className:n,...s}){const r=t?gp:"a";return e.jsx(r,{"data-slot":"breadcrumb-link",className:O("hover:text-foreground transition-colors",n),...s})}function u0({className:t,...n}){return e.jsx("span",{"data-slot":"breadcrumb-page",role:"link","aria-disabled":"true","aria-current":"page",className:O("text-foreground font-normal",t),...n})}function Hm({children:t,className:n,...s}){return e.jsx("li",{"data-slot":"breadcrumb-separator",role:"presentation","aria-hidden":"true",className:O("[&>svg]:size-3.5",n),...s,children:t??e.jsx(sn,{})})}const XT=new Set(["detailTab","taskDetailView","contextMenuItem","commentAnnotation","commentContextMenuItem","projectSidebarItem","toolbarButton"]),m0=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),eR=1e3,tR=new Set(Bv),p0=c.createContext(null);function nR(t){return t instanceof Error&&t.message?t.message:"Unknown error"}function sR(t,n,s){return{companyId:t.companyId??null,companyPrefix:t.companyPrefix??null,projectId:t.projectId??(t.entityType==="project"?t.entityId??null:null),entityId:t.entityId??null,entityType:t.entityType??null,userId:s,renderEnvironment:n}}function rR(t){if(!t)return;const n=t.querySelector(m0);if(n){n.focus();return}t.focus()}function aR(t,n){if(n.key!=="Tab")return;const s=Array.from(t.querySelectorAll(m0)).filter(i=>!i.hasAttribute("disabled")&&i.tabIndex!==-1);if(s.length===0){n.preventDefault(),t.focus();return}const r=s[0],a=s[s.length-1],o=document.activeElement;if(n.shiftKey&&o===r){n.preventDefault(),a.focus();return}!n.shiftKey&&o===a&&(n.preventDefault(),r.focus())}function oR(t){switch(t){case"projectSidebarItem":return"justify-start h-auto px-3 py-1 text-[12px] font-normal text-muted-foreground hover:text-foreground";case"contextMenuItem":case"commentContextMenuItem":return"justify-start h-7 w-full px-2 text-xs font-normal";case"sidebar":case"sidebarPanel":return"justify-start h-8 w-full";case"toolbarButton":case"globalToolbarButton":return"h-8";default:return"h-8"}}function x0(t){switch(t){case"compact":return{width:"min(28rem, calc(100vw - 2rem))"};case"wide":return{width:"min(64rem, calc(100vw - 2rem))"};case"full":return{width:"calc(100vw - 2rem)",height:"calc(100vh - 2rem)"};case"inline":return{width:"min(24rem, calc(100vw - 2rem))"};case"default":default:return{width:"min(40rem, calc(100vw - 2rem))"}}}function iR(t){const n=t.sourceRect,s=x0(t.bounds).width??"min(24rem, calc(100vw - 2rem))";if(!n)return{width:s,maxHeight:"min(70vh, 36rem)",top:"4rem",left:"50%",transform:"translateX(-50%)"};const r=Math.min(n.bottom+8,window.innerHeight-32),a=Math.min(Math.max(n.left,16),Math.max(16,window.innerWidth-360));return{width:s,maxHeight:"min(70vh, 36rem)",top:r,left:a}}function lR(t){return typeof t=="string"&&tR.has(t)}function f0(t){const n=t.enabled??!0,{data:s,isLoading:r,error:a}=oe({queryKey:N.plugins.uiContributions,queryFn:()=>Mn.listUiContributions(),enabled:n}),o=c.useMemo(()=>[...t.placementZones].sort().join("|"),[t.placementZones]),i=c.useMemo(()=>{const u=new Map;for(const d of s??[])u.set(d.pluginId,d);return u},[s]);return{launchers:c.useMemo(()=>{var m;const u=new Set(o.split("|").filter(Boolean)),d=[];for(const p of s??[])for(const x of p.launchers)u.has(x.placementZone)&&(XT.has(x.placementZone)&&(!t.entityType||!((m=x.entityTypes)!=null&&m.includes(t.entityType)))||d.push({...x,pluginId:p.pluginId,pluginKey:p.pluginKey,pluginDisplayName:p.displayName,pluginVersion:p.version,uiEntryFile:p.uiEntryFile}));return d.sort((p,x)=>{const f=p.order??Number.MAX_SAFE_INTEGER,h=x.order??Number.MAX_SAFE_INTEGER;if(f!==h)return f-h;const j=p.pluginDisplayName.localeCompare(x.pluginDisplayName);return j!==0?j:p.displayName.localeCompare(x.displayName)}),d},[s,t.entityType,o]),contributionsByPluginId:i,isLoading:n&&r,errorMessage:a?nR(a):null}}async function cR(t,n){const s=n.action.target,r=rh(n.pluginKey,s);return r||(await wT(t),rh(n.pluginKey,s))}function dR({pluginId:t,hostContext:n,children:s}){const r=c.useMemo(()=>({pluginId:t,hostContext:n}),[t,n]);return e.jsx(Ex.Provider,{value:r,children:s})}class uR extends c.Component{constructor(){super(...arguments);Ci(this,"state",{hasError:!1})}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(s,r){console.error("Plugin launcher render failed",{pluginKey:this.props.launcher.pluginKey,launcherId:this.props.launcher.id,error:s,info:r.componentStack})}render(){return this.state.hasError?e.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive",children:[this.props.launcher.pluginDisplayName,": failed to render"]}):this.props.children}}function mR({instance:t,renderEnvironment:n}){var l,u;const s=t.component,{data:r}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),a=((l=r==null?void 0:r.user)==null?void 0:l.id)??((u=r==null?void 0:r.session)==null?void 0:u.userId)??null,o=c.useMemo(()=>sR(t.hostContext,n,a),[t.hostContext,n,a]);if(!s)return n.environment==="iframe"?e.jsx("iframe",{src:`/_plugins/${encodeURIComponent(t.launcher.pluginId)}/ui/${t.launcher.action.target}`,title:`${t.launcher.pluginDisplayName} ${t.launcher.displayName}`,className:"h-full min-h-[24rem] w-full rounded-md border border-border bg-background"}):e.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive",children:[t.launcher.pluginDisplayName,': could not resolve launcher target "',t.launcher.action.target,'".']});if(s.kind==="web-component")return c.createElement(s.tagName,{className:"block w-full",pluginLauncher:t.launcher,pluginContext:o});const i=c.createElement(s.component,{launcher:t.launcher,context:o});return e.jsx(uR,{launcher:t.launcher,children:e.jsx(dR,{pluginId:t.launcher.pluginId,hostContext:o,children:i})})}function pR({instance:t,stackIndex:n,isTopmost:s,requestBounds:r,closeLauncher:a}){const o=c.useRef(null),i=c.useId();c.useEffect(()=>{if(!s)return;const x=requestAnimationFrame(()=>{rR(o.current)});return()=>cancelAnimationFrame(x)},[s]),c.useEffect(()=>{if(!s)return;const x=f=>{if(o.current){if(f.key==="Escape"){f.preventDefault(),a(t.key,{reason:"escapeKey",nativeEvent:f});return}aR(o.current,f)}};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[a,t.key,s]);const l=c.useMemo(()=>{var x;return{environment:((x=t.launcher.render)==null?void 0:x.environment)??"hostOverlay",launcherId:t.launcher.id,bounds:t.bounds,requestModalBounds:f=>r(t.key,f),closeLifecycle:{onBeforeClose:f=>(t.beforeCloseHandlers.add(f),()=>t.beforeCloseHandlers.delete(f)),onClose:f=>(t.closeHandlers.add(f),()=>t.closeHandlers.delete(f))}}},[t,r]),u=eR+n*20,d=t.launcher.action.type,m=d==="openPopover"?iR(t):x0(t.bounds),p=d==="openDrawer"?"fixed right-0 top-0 h-full max-w-[min(44rem,100vw)] overflow-hidden border-l border-border bg-background shadow-2xl":d==="openPopover"?"fixed overflow-hidden rounded-xl border border-border bg-background shadow-2xl":"fixed left-1/2 top-1/2 max-h-[calc(100vh-2rem)] -translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-2xl border border-border bg-background shadow-2xl";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/45",style:{zIndex:u},"aria-hidden":"true",onMouseDown:x=>{s&&x.target===x.currentTarget&&a(t.key,{reason:"backdrop",nativeEvent:x})}}),e.jsxs("div",{ref:o,role:"dialog","aria-modal":"true","aria-labelledby":i,tabIndex:-1,className:p,style:{zIndex:u+1,...d==="openDrawer"?{width:m.width??"min(44rem, 100vw)"}:m},onMouseDown:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-3 border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:i,className:"truncate text-sm font-semibold",children:t.launcher.displayName}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.launcher.pluginDisplayName})]}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"ml-auto",onClick:()=>void a(t.key,{reason:"programmatic"}),children:"Close"})]}),e.jsx("div",{className:O("overflow-auto p-4",d==="openDrawer"?"h-[calc(100%-3.5rem)]":"max-h-[calc(100vh-7rem)]"),children:e.jsx(mR,{instance:t,renderEnvironment:l})})]})]})}function xR({children:t}){const[n,s]=c.useState([]),r=c.useRef(n);r.current=n;const a=fn(),o=Sn(),i=c.useCallback(async(m,p)=>{const x=r.current.find(f=>f.key===m);if(x){for(const f of[...x.beforeCloseHandlers])await f(p);s(f=>f.filter(h=>h.key!==m)),queueMicrotask(()=>{for(const f of[...x.closeHandlers])f(p);x.sourceElement&&document.contains(x.sourceElement)&&x.sourceElement.focus()})}},[]);c.useEffect(()=>{n.length!==0&&Promise.all(n.map(m=>i(m.key,{reason:"hostNavigation"})))},[a.key]);const l=c.useCallback(async(m,p)=>{lR(p.bounds)&&s(x=>x.map(f=>f.key===m?{...f,bounds:p.bounds}:f))},[]),u=c.useCallback(async(m,p,x,f)=>{var h;switch(m.action.type){case"navigate":o(m.action.target);return;case"deepLink":/^https?:\/\//.test(m.action.target)?window.open(m.action.target,"_blank","noopener,noreferrer"):o(m.action.target);return;case"performAction":await Mn.bridgePerformAction(m.pluginId,m.action.target,m.action.params,p.companyId??null);return;case"openModal":case"openDrawer":case"openPopover":{const j=await cR(x,m),b=(f==null?void 0:f.getBoundingClientRect())??null,g={key:`${m.pluginId}:${m.id}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,launcher:m,hostContext:p,contribution:x,component:j,sourceElement:f??null,sourceRect:b,bounds:((h=m.render)==null?void 0:h.bounds)??"default",beforeCloseHandlers:new Set,closeHandlers:new Set};s(y=>[...y,g]);return}}},[o]),d=c.useMemo(()=>({activateLauncher:u}),[u]);return e.jsxs(p0.Provider,{value:d,children:[t,n.map((m,p)=>e.jsx(pR,{instance:m,stackIndex:p,isTopmost:p===n.length-1,requestBounds:l,closeLauncher:i},m.key))]})}function fR(){const t=c.useContext(p0);if(!t)throw new Error("usePluginLauncherRuntime must be used within PluginLauncherProvider");return t}function hR({launcher:t,placementZone:n,onClick:s}){return e.jsx(G,{type:"button",variant:n==="toolbarButton"||n==="globalToolbarButton"?"outline":"ghost",size:"sm",className:oR(n),onClick:s,children:t.displayName})}function $x({placementZones:t,context:n,entityType:s,className:r,itemClassName:a,errorClassName:o}){const{activateLauncher:i}=fR(),{launchers:l,contributionsByPluginId:u,errorMessage:d}=f0({placementZones:t,entityType:s,companyId:n.companyId,enabled:!!n.companyId});return d?e.jsxs("div",{className:O("rounded-md border border-destructive/30 bg-destructive/5 px-2 py-1 text-xs text-destructive",o),children:["Plugin launchers unavailable: ",d]}):l.length===0?null:e.jsx("div",{className:r,children:l.map(m=>e.jsx("div",{className:a,children:e.jsx(hR,{launcher:m,placementZone:m.placementZone,onClick:p=>{const x=u.get(m.pluginId);x&&i(m,n,x,p.currentTarget)}})},`${m.pluginKey}:${m.id}`))})}function gR({context:t}){const{slots:n}=yi({slotTypes:["globalToolbarButton"],companyId:t.companyId}),{launchers:s}=f0({placementZones:["globalToolbarButton"],companyId:t.companyId,enabled:!!t.companyId});return n.length===0&&s.length===0?null:e.jsxs("div",{className:"flex items-center gap-1 ml-auto shrink-0 pl-2",children:[e.jsx(Vr,{slotTypes:["globalToolbarButton"],context:t,className:"flex items-center gap-1"}),e.jsx($x,{placementZones:["globalToolbarButton"],context:t,className:"flex items-center gap-1"})]})}function bR(){const{breadcrumbs:t}=Ft(),{toggleSidebar:n,isMobile:s}=mr(),{selectedCompanyId:r,selectedCompany:a}=et(),o=c.useMemo(()=>({companyId:r??null,companyPrefix:(a==null?void 0:a.issuePrefix)??null}),[r,a==null?void 0:a.issuePrefix]),i=e.jsx(gR,{context:o});if(t.length===0)return e.jsx("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:i});const l=s&&e.jsx(G,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:e.jsx(p1,{className:"h-5 w-5"})});return t.length===1?e.jsxs("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center",children:[l,e.jsx("div",{className:"min-w-0 overflow-hidden flex-1",children:e.jsx("h1",{className:"text-sm font-semibold uppercase tracking-wider truncate",children:t[0].label})}),i]}):e.jsxs("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center",children:[l,e.jsx("div",{className:"min-w-0 overflow-hidden flex-1",children:e.jsx(c0,{className:"min-w-0 overflow-hidden",children:e.jsx(d0,{className:"flex-nowrap",children:t.map((u,d)=>{const m=d===t.length-1;return e.jsxs(c.Fragment,{children:[d>0&&e.jsx(Hm,{}),e.jsx(hc,{className:m?"min-w-0":"shrink-0",children:m||!u.href?e.jsx(u0,{className:"truncate",children:u.label}):e.jsx(Wm,{asChild:!0,children:e.jsx(Oe,{to:u.href,children:u.label})})})]},d)})})})}),i]})}const h0="crewspace:panel-visible",g0=c.createContext(null);function yR(){try{const t=localStorage.getItem(h0);return t===null?!0:t==="true"}catch{return!0}}function ph(t){try{localStorage.setItem(h0,String(t))}catch{}}function vR({children:t}){const[n,s]=c.useState(null),[r,a]=c.useState(yR),o=c.useCallback(d=>{s(d)},[]),i=c.useCallback(()=>{s(null)},[]),l=c.useCallback(d=>{a(d),ph(d)},[]),u=c.useCallback(()=>{a(d=>{const m=!d;return ph(m),m})},[]);return e.jsx(g0.Provider,{value:{panelContent:n,panelVisible:r,openPanel:o,closePanel:i,setPanelVisible:l,togglePanelVisible:u},children:t})}function ji(){const t=c.useContext(g0);if(!t)throw new Error("usePanel must be used within PanelProvider");return t}function Dx({className:t,children:n,...s}){return e.jsxs(UI,{"data-slot":"scroll-area",className:O("relative flex flex-col overflow-hidden",t),...s,children:[e.jsx(BI,{"data-slot":"scroll-area-viewport",className:"flex-1 min-h-0 w-full focus-visible:ring-ring/50 rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1",children:n}),e.jsx(jR,{}),e.jsx(KI,{})]})}function jR({className:t,orientation:n="vertical",...s}){return e.jsx(gv,{"data-slot":"scroll-area-scrollbar",orientation:n,className:O("flex touch-none p-px transition-colors select-none",n==="vertical"&&"h-full w-2.5 border-l border-l-transparent",n==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",t),...s,children:e.jsx(jv,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}function wR(){const{panelContent:t,panelVisible:n,setPanelVisible:s}=ji();return t?e.jsx("aside",{className:"hidden md:flex border-l border-border bg-card flex-col shrink-0 overflow-hidden transition-[width,opacity] duration-200 ease-in-out",style:{width:n?320:0,opacity:n?1:0},children:e.jsxs("div",{className:"w-80 flex-1 flex flex-col min-w-[320px]",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border",children:[e.jsx("span",{className:"text-sm font-medium",children:"Properties"}),e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:()=>s(!1),children:e.jsx(zt,{className:"h-4 w-4"})})]}),e.jsx(Dx,{className:"flex-1",children:e.jsx("div",{className:"p-4",children:t})})]})}):null}var xh=1,NR=.9,kR=.8,CR=.17,Iu=.1,_u=.999,SR=.9999,IR=.99,_R=/[\\\/_+.#"@\[\(\{&]/,AR=/[\\\/_+.#"@\[\(\{&]/g,ER=/[\s-]/,b0=/[\s-]/g;function Vm(t,n,s,r,a,o,i){if(o===n.length)return a===t.length?xh:IR;var l=`${a},${o}`;if(i[l]!==void 0)return i[l];for(var u=r.charAt(o),d=s.indexOf(u,a),m=0,p,x,f,h;d>=0;)p=Vm(t,n,s,r,d+1,o+1,i),p>m&&(d===a?p*=xh:_R.test(t.charAt(d-1))?(p*=kR,f=t.slice(a,d-1).match(AR),f&&a>0&&(p*=Math.pow(_u,f.length))):ER.test(t.charAt(d-1))?(p*=NR,h=t.slice(a,d-1).match(b0),h&&a>0&&(p*=Math.pow(_u,h.length))):(p*=CR,a>0&&(p*=Math.pow(_u,d-a))),t.charAt(d)!==n.charAt(o)&&(p*=SR)),(p<Iu&&s.charAt(d-1)===r.charAt(o+1)||r.charAt(o+1)===r.charAt(o)&&s.charAt(d-1)!==r.charAt(o))&&(x=Vm(t,n,s,r,d+1,o+2,i),x*Iu>p&&(p=x*Iu)),p>m&&(m=p),d=s.indexOf(u,d+1);return i[l]=m,m}function fh(t){return t.toLowerCase().replace(b0," ")}function TR(t,n,s){return t=s&&s.length>0?`${t+" "+s.join(" ")}`:t,Vm(t,n,fh(t),fh(n),0,0,{})}var Si='[cmdk-group=""]',Au='[cmdk-group-items=""]',RR='[cmdk-group-heading=""]',y0='[cmdk-item=""]',hh=`${y0}:not([aria-disabled="true"])`,Qm="cmdk-item-select",$o="data-value",PR=(t,n,s)=>TR(t,n,s),v0=c.createContext(void 0),Dl=()=>c.useContext(v0),j0=c.createContext(void 0),Ox=()=>c.useContext(j0),w0=c.createContext(void 0),N0=c.forwardRef((t,n)=>{let s=Do(()=>{var H,U;return{search:"",value:(U=(H=t.value)!=null?H:t.defaultValue)!=null?U:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Do(()=>new Set),a=Do(()=>new Map),o=Do(()=>new Map),i=Do(()=>new Set),l=k0(t),{label:u,children:d,value:m,onValueChange:p,filter:x,shouldFilter:f,loop:h,disablePointerSelection:j=!1,vimBindings:b=!0,...g}=t,y=jr(),v=jr(),_=jr(),E=c.useRef(null),S=zR();ro(()=>{if(m!==void 0){let H=m.trim();s.current.value=H,M.emit()}},[m]),ro(()=>{S(6,I)},[]);let M=c.useMemo(()=>({subscribe:H=>(i.current.add(H),()=>i.current.delete(H)),snapshot:()=>s.current,setState:(H,U,Z)=>{var V,W,J,Y;if(!Object.is(s.current[H],U)){if(s.current[H]=U,H==="search")C(),L(),S(1,$);else if(H==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let de=document.getElementById(_);de?de.focus():(V=document.getElementById(y))==null||V.focus()}if(S(7,()=>{var de;s.current.selectedItemId=(de=K())==null?void 0:de.id,M.emit()}),Z||S(5,I),((W=l.current)==null?void 0:W.value)!==void 0){let de=U??"";(Y=(J=l.current).onValueChange)==null||Y.call(J,de);return}}M.emit()}},emit:()=>{i.current.forEach(H=>H())}}),[]),B=c.useMemo(()=>({value:(H,U,Z)=>{var V;U!==((V=o.current.get(H))==null?void 0:V.value)&&(o.current.set(H,{value:U,keywords:Z}),s.current.filtered.items.set(H,k(U,Z)),S(2,()=>{L(),M.emit()}))},item:(H,U)=>(r.current.add(H),U&&(a.current.has(U)?a.current.get(U).add(H):a.current.set(U,new Set([H]))),S(3,()=>{C(),L(),s.current.value||$(),M.emit()}),()=>{o.current.delete(H),r.current.delete(H),s.current.filtered.items.delete(H);let Z=K();S(4,()=>{C(),(Z==null?void 0:Z.getAttribute("id"))===H&&$(),M.emit()})}),group:H=>(a.current.has(H)||a.current.set(H,new Set),()=>{o.current.delete(H),a.current.delete(H)}),filter:()=>l.current.shouldFilter,label:u||t["aria-label"],getDisablePointerSelection:()=>l.current.disablePointerSelection,listId:y,inputId:_,labelId:v,listInnerRef:E}),[]);function k(H,U){var Z,V;let W=(V=(Z=l.current)==null?void 0:Z.filter)!=null?V:PR;return H?W(H,s.current.search,U):0}function L(){if(!s.current.search||l.current.shouldFilter===!1)return;let H=s.current.filtered.items,U=[];s.current.filtered.groups.forEach(V=>{let W=a.current.get(V),J=0;W.forEach(Y=>{let de=H.get(Y);J=Math.max(de,J)}),U.push([V,J])});let Z=E.current;T().sort((V,W)=>{var J,Y;let de=V.getAttribute("id"),fe=W.getAttribute("id");return((J=H.get(fe))!=null?J:0)-((Y=H.get(de))!=null?Y:0)}).forEach(V=>{let W=V.closest(Au);W?W.appendChild(V.parentElement===W?V:V.closest(`${Au} > *`)):Z.appendChild(V.parentElement===Z?V:V.closest(`${Au} > *`))}),U.sort((V,W)=>W[1]-V[1]).forEach(V=>{var W;let J=(W=E.current)==null?void 0:W.querySelector(`${Si}[${$o}="${encodeURIComponent(V[0])}"]`);J==null||J.parentElement.appendChild(J)})}function $(){let H=T().find(Z=>Z.getAttribute("aria-disabled")!=="true"),U=H==null?void 0:H.getAttribute($o);M.setState("value",U||void 0)}function C(){var H,U,Z,V;if(!s.current.search||l.current.shouldFilter===!1){s.current.filtered.count=r.current.size;return}s.current.filtered.groups=new Set;let W=0;for(let J of r.current){let Y=(U=(H=o.current.get(J))==null?void 0:H.value)!=null?U:"",de=(V=(Z=o.current.get(J))==null?void 0:Z.keywords)!=null?V:[],fe=k(Y,de);s.current.filtered.items.set(J,fe),fe>0&&W++}for(let[J,Y]of a.current)for(let de of Y)if(s.current.filtered.items.get(de)>0){s.current.filtered.groups.add(J);break}s.current.filtered.count=W}function I(){var H,U,Z;let V=K();V&&(((H=V.parentElement)==null?void 0:H.firstChild)===V&&((Z=(U=V.closest(Si))==null?void 0:U.querySelector(RR))==null||Z.scrollIntoView({block:"nearest"})),V.scrollIntoView({block:"nearest"}))}function K(){var H;return(H=E.current)==null?void 0:H.querySelector(`${y0}[aria-selected="true"]`)}function T(){var H;return Array.from(((H=E.current)==null?void 0:H.querySelectorAll(hh))||[])}function z(H){let U=T()[H];U&&M.setState("value",U.getAttribute($o))}function w(H){var U;let Z=K(),V=T(),W=V.findIndex(Y=>Y===Z),J=V[W+H];(U=l.current)!=null&&U.loop&&(J=W+H<0?V[V.length-1]:W+H===V.length?V[0]:V[W+H]),J&&M.setState("value",J.getAttribute($o))}function F(H){let U=K(),Z=U==null?void 0:U.closest(Si),V;for(;Z&&!V;)Z=H>0?BR(Z,Si):KR(Z,Si),V=Z==null?void 0:Z.querySelector(hh);V?M.setState("value",V.getAttribute($o)):w(H)}let A=()=>z(T().length-1),R=H=>{H.preventDefault(),H.metaKey?A():H.altKey?F(1):w(1)},Q=H=>{H.preventDefault(),H.metaKey?z(0):H.altKey?F(-1):w(-1)};return c.createElement(Lt.div,{ref:n,tabIndex:-1,...g,"cmdk-root":"",onKeyDown:H=>{var U;(U=g.onKeyDown)==null||U.call(g,H);let Z=H.nativeEvent.isComposing||H.keyCode===229;if(!(H.defaultPrevented||Z))switch(H.key){case"n":case"j":{b&&H.ctrlKey&&R(H);break}case"ArrowDown":{R(H);break}case"p":case"k":{b&&H.ctrlKey&&Q(H);break}case"ArrowUp":{Q(H);break}case"Home":{H.preventDefault(),z(0);break}case"End":{H.preventDefault(),A();break}case"Enter":{H.preventDefault();let V=K();if(V){let W=new Event(Qm);V.dispatchEvent(W)}}}}},c.createElement("label",{"cmdk-label":"",htmlFor:B.inputId,id:B.labelId,style:HR},u),Zd(t,H=>c.createElement(j0.Provider,{value:M},c.createElement(v0.Provider,{value:B},H))))}),MR=c.forwardRef((t,n)=>{var s,r;let a=jr(),o=c.useRef(null),i=c.useContext(w0),l=Dl(),u=k0(t),d=(r=(s=u.current)==null?void 0:s.forceMount)!=null?r:i==null?void 0:i.forceMount;ro(()=>{if(!d)return l.item(a,i==null?void 0:i.id)},[d]);let m=C0(a,o,[t.value,t.children,o],t.keywords),p=Ox(),x=ka(S=>S.value&&S.value===m.current),f=ka(S=>d||l.filter()===!1?!0:S.search?S.filtered.items.get(a)>0:!0);c.useEffect(()=>{let S=o.current;if(!(!S||t.disabled))return S.addEventListener(Qm,h),()=>S.removeEventListener(Qm,h)},[f,t.onSelect,t.disabled]);function h(){var S,M;j(),(M=(S=u.current).onSelect)==null||M.call(S,m.current)}function j(){p.setState("value",m.current,!0)}if(!f)return null;let{disabled:b,value:g,onSelect:y,forceMount:v,keywords:_,...E}=t;return c.createElement(Lt.div,{ref:Qa(o,n),...E,id:a,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!x,"data-disabled":!!b,"data-selected":!!x,onPointerMove:b||l.getDisablePointerSelection()?void 0:j,onClick:b?void 0:h},t.children)}),$R=c.forwardRef((t,n)=>{let{heading:s,children:r,forceMount:a,...o}=t,i=jr(),l=c.useRef(null),u=c.useRef(null),d=jr(),m=Dl(),p=ka(f=>a||m.filter()===!1?!0:f.search?f.filtered.groups.has(i):!0);ro(()=>m.group(i),[]),C0(i,l,[t.value,t.heading,u]);let x=c.useMemo(()=>({id:i,forceMount:a}),[a]);return c.createElement(Lt.div,{ref:Qa(l,n),...o,"cmdk-group":"",role:"presentation",hidden:p?void 0:!0},s&&c.createElement("div",{ref:u,"cmdk-group-heading":"","aria-hidden":!0,id:d},s),Zd(t,f=>c.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":s?d:void 0},c.createElement(w0.Provider,{value:x},f))))}),DR=c.forwardRef((t,n)=>{let{alwaysRender:s,...r}=t,a=c.useRef(null),o=ka(i=>!i.search);return!s&&!o?null:c.createElement(Lt.div,{ref:Qa(a,n),...r,"cmdk-separator":"",role:"separator"})}),OR=c.forwardRef((t,n)=>{let{onValueChange:s,...r}=t,a=t.value!=null,o=Ox(),i=ka(d=>d.search),l=ka(d=>d.selectedItemId),u=Dl();return c.useEffect(()=>{t.value!=null&&o.setState("search",t.value)},[t.value]),c.createElement(Lt.input,{ref:n,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":u.listId,"aria-labelledby":u.labelId,"aria-activedescendant":l,id:u.inputId,type:"text",value:a?t.value:i,onChange:d=>{a||o.setState("search",d.target.value),s==null||s(d.target.value)}})}),LR=c.forwardRef((t,n)=>{let{children:s,label:r="Suggestions",...a}=t,o=c.useRef(null),i=c.useRef(null),l=ka(d=>d.selectedItemId),u=Dl();return c.useEffect(()=>{if(i.current&&o.current){let d=i.current,m=o.current,p,x=new ResizeObserver(()=>{p=requestAnimationFrame(()=>{let f=d.offsetHeight;m.style.setProperty("--cmdk-list-height",f.toFixed(1)+"px")})});return x.observe(d),()=>{cancelAnimationFrame(p),x.unobserve(d)}}},[]),c.createElement(Lt.div,{ref:Qa(o,n),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":l,"aria-label":r,id:u.listId},Zd(t,d=>c.createElement("div",{ref:Qa(i,u.listInnerRef),"cmdk-list-sizer":""},d)))}),FR=c.forwardRef((t,n)=>{let{open:s,onOpenChange:r,overlayClassName:a,contentClassName:o,container:i,...l}=t;return c.createElement(bp,{open:s,onOpenChange:r},c.createElement(yp,{container:i},c.createElement(vp,{"cmdk-overlay":"",className:a}),c.createElement(jp,{"aria-label":t.label,"cmdk-dialog":"",className:o},c.createElement(N0,{ref:n,...l}))))}),qR=c.forwardRef((t,n)=>ka(s=>s.filtered.count===0)?c.createElement(Lt.div,{ref:n,...t,"cmdk-empty":"",role:"presentation"}):null),UR=c.forwardRef((t,n)=>{let{progress:s,children:r,label:a="Loading...",...o}=t;return c.createElement(Lt.div,{ref:n,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":s,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},Zd(t,i=>c.createElement("div",{"aria-hidden":!0},i)))}),yo=Object.assign(N0,{List:LR,Item:MR,Input:OR,Group:$R,Separator:DR,Dialog:FR,Empty:qR,Loading:UR});function BR(t,n){let s=t.nextElementSibling;for(;s;){if(s.matches(n))return s;s=s.nextElementSibling}}function KR(t,n){let s=t.previousElementSibling;for(;s;){if(s.matches(n))return s;s=s.previousElementSibling}}function k0(t){let n=c.useRef(t);return ro(()=>{n.current=t}),n}var ro=typeof window>"u"?c.useEffect:c.useLayoutEffect;function Do(t){let n=c.useRef();return n.current===void 0&&(n.current=t()),n}function ka(t){let n=Ox(),s=()=>t(n.snapshot());return c.useSyncExternalStore(n.subscribe,s,s)}function C0(t,n,s,r=[]){let a=c.useRef(),o=Dl();return ro(()=>{var i;let l=(()=>{var d;for(let m of s){if(typeof m=="string")return m.trim();if(typeof m=="object"&&"current"in m)return m.current?(d=m.current.textContent)==null?void 0:d.trim():a.current}})(),u=r.map(d=>d.trim());o.value(t,l,u),(i=n.current)==null||i.setAttribute($o,l),a.current=l}),a}var zR=()=>{let[t,n]=c.useState(),s=Do(()=>new Map);return ro(()=>{s.current.forEach(r=>r()),s.current=new Map},[t]),(r,a)=>{s.current.set(r,a),n({})}};function WR(t){let n=t.type;return typeof n=="function"?n(t.props):"render"in n?n.render(t.props):t}function Zd({asChild:t,children:n},s){return t&&c.isValidElement(n)?c.cloneElement(WR(n),{ref:n.ref},s(n.props.children)):s(n)}var HR={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function Cs({...t}){return e.jsx(bp,{"data-slot":"dialog",...t})}function S0({...t}){return e.jsx(Fb,{"data-slot":"dialog-trigger",...t})}function I0({...t}){return e.jsx(yp,{"data-slot":"dialog-portal",...t})}function VR({className:t,...n}){return e.jsx(vp,{"data-slot":"dialog-overlay",className:O("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50 duration-100",t),...n})}function Fs({className:t,children:n,showCloseButton:s=!0,...r}){return e.jsxs(I0,{"data-slot":"dialog-portal",children:[e.jsx(VR,{}),e.jsxs(jp,{"data-slot":"dialog-content",className:O("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-[0.97] data-[state=open]:zoom-in-[0.97] data-[state=closed]:slide-out-to-top-[1%] data-[state=open]:slide-in-from-top-[1%] fixed top-[max(1rem,env(safe-area-inset-top))] md:top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-0 md:translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-150 ease-[cubic-bezier(0.16,1,0.3,1)] outline-none sm:max-w-lg",t),...r,children:[n,s&&e.jsxs(Nd,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(zt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function fa({className:t,...n}){return e.jsx("div",{"data-slot":"dialog-header",className:O("flex flex-col gap-2 text-center sm:text-left",t),...n})}function Ho({className:t,showCloseButton:n=!1,children:s,...r}){return e.jsxs("div",{"data-slot":"dialog-footer",className:O("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...r,children:[s,n&&e.jsx(Nd,{asChild:!0,children:e.jsx(G,{variant:"outline",children:"Close"})})]})}function ha({className:t,...n}){return e.jsx(Ob,{"data-slot":"dialog-title",className:O("text-lg leading-none font-semibold",t),...n})}function ga({className:t,...n}){return e.jsx(Lb,{"data-slot":"dialog-description",className:O("text-muted-foreground text-sm",t),...n})}function _0({className:t,...n}){return e.jsx(yo,{"data-slot":"command",className:O("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...n})}function QR({title:t="Command Palette",description:n="Search for a command to run...",children:s,className:r,showCloseButton:a=!0,...o}){return e.jsxs(Cs,{...o,children:[e.jsxs(fa,{className:"sr-only",children:[e.jsx(ha,{children:t}),e.jsx(ga,{children:n})]}),e.jsxs(Fs,{className:O("overflow-hidden p-0",r),showCloseButton:!1,children:[e.jsx(_0,{className:"[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:s}),a&&e.jsxs(Nd,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-0 right-2 flex h-12 items-center rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(zt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function A0({className:t,...n}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[e.jsx(ws,{className:"size-4 shrink-0 opacity-50"}),e.jsx(yo.Input,{"data-slot":"command-input",className:O("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",t),...n})]})}function E0({className:t,...n}){return e.jsx(yo.List,{"data-slot":"command-list",className:O("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...n})}function T0({...t}){return e.jsx(yo.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function Fa({className:t,...n}){return e.jsx(yo.Group,{"data-slot":"command-group",className:O("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",t),...n})}function Fi({className:t,...n}){return e.jsx(yo.Separator,{"data-slot":"command-separator",className:O("bg-border -mx-1 h-px",t),...n})}function Kn({className:t,...n}){return e.jsx(yo.Item,{"data-slot":"command-item",className:O("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...n})}function ta({className:t,size:n="default",...s}){return e.jsx(rS,{"data-slot":"avatar","data-size":n,className:O("group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6 data-[size=xs]:size-5",t),...s})}function GR({className:t,...n}){return e.jsx(aS,{"data-slot":"avatar-image",className:O("aspect-square size-full",t),...n})}function na({className:t,...n}){return e.jsx(oS,{"data-slot":"avatar-fallback",className:O("bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs group-data-[size=xs]/avatar:text-[10px]",t),...n})}function JR({className:t,...n}){return e.jsx("div",{"data-slot":"avatar-group",className:O("*:data-[slot=avatar]:ring-background group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2",t),...n})}function ZR({className:t,...n}){return e.jsx("div",{"data-slot":"avatar-group-count",className:O("bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",t),...n})}function YR(t){const n=t.trim().split(/\s+/);return n.length>=2?(n[0][0]+n[n.length-1][0]).toUpperCase():t.slice(0,2).toUpperCase()}const XR={xs:"text-sm",sm:"text-xs",default:"text-sm",lg:"text-sm"};function Ut({name:t,avatarUrl:n,initials:s,size:r="default",className:a}){const o=s??YR(t);return e.jsxs("span",{className:O("inline-flex gap-1.5",r==="xs"?"items-baseline gap-1":"items-center",r==="lg"&&"gap-2",a),children:[e.jsxs(ta,{size:r,className:r==="xs"?"relative -top-px":void 0,children:[n&&e.jsx(GR,{src:n,alt:t}),e.jsx(na,{children:o})]}),e.jsx("span",{className:O("truncate",XR[r]),children:t})]})}function e3(){const[t,n]=c.useState(!1),[s,r]=c.useState(""),a=Sn(),{selectedCompanyId:o}=et(),{openNewIssue:i,openNewAgent:l}=In(),{isMobile:u,setSidebarOpen:d}=mr(),m=s.trim();c.useEffect(()=>{function v(_){_.key==="k"&&(_.metaKey||_.ctrlKey)&&(_.preventDefault(),n(!0),u&&d(!1))}return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[u,d]),c.useEffect(()=>{t||r("")},[t]);const{data:p=[]}=oe({queryKey:N.issues.list(o),queryFn:()=>nt.list(o),enabled:!!o&&t}),{data:x=[]}=oe({queryKey:N.issues.search(o,m),queryFn:()=>nt.list(o,{q:m}),enabled:!!o&&t&&m.length>0}),{data:f=[]}=oe({queryKey:N.agents.list(o),queryFn:()=>We.list(o),enabled:!!o&&t}),{data:h=[]}=oe({queryKey:N.projects.list(o),queryFn:()=>en.list(o),enabled:!!o&&t}),j=c.useMemo(()=>h.filter(v=>!v.archivedAt),[h]);function b(v){n(!1),a(v)}const g=v=>{var _;return v?((_=f.find(E=>E.id===v))==null?void 0:_.name)??null:null},y=c.useMemo(()=>m.length>0?x:p,[p,x,m]);return e.jsxs(QR,{open:t,onOpenChange:v=>{n(v),v&&u&&d(!1)},children:[e.jsx(A0,{placeholder:"Search issues, agents, projects...",value:s,onValueChange:r}),e.jsxs(E0,{children:[e.jsx(T0,{children:"No results found."}),e.jsxs(Fa,{heading:"Actions",children:[e.jsxs(Kn,{onSelect:()=>{n(!1),i()},children:[e.jsx(Ap,{className:"mr-2 h-4 w-4"}),"Create new issue",e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:"C"})]}),e.jsxs(Kn,{onSelect:()=>{n(!1),l()},children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),"Create new agent"]}),e.jsxs(Kn,{onSelect:()=>b("/projects"),children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),"Create new project"]})]}),e.jsx(Fi,{}),e.jsxs(Fa,{heading:"Pages",children:[e.jsxs(Kn,{onSelect:()=>b("/dashboard"),children:[e.jsx(Ka,{className:"mr-2 h-4 w-4"}),"Dashboard"]}),e.jsxs(Kn,{onSelect:()=>b("/inbox"),children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),"Inbox"]}),e.jsxs(Kn,{onSelect:()=>b("/issues"),children:[e.jsx(rs,{className:"mr-2 h-4 w-4"}),"Issues"]}),e.jsxs(Kn,{onSelect:()=>b("/projects"),children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"}),"Projects"]}),e.jsxs(Kn,{onSelect:()=>b("/goals"),children:[e.jsx(Ir,{className:"mr-2 h-4 w-4"}),"Goals"]}),e.jsxs(Kn,{onSelect:()=>b("/agents"),children:[e.jsx(ss,{className:"mr-2 h-4 w-4"}),"Agents"]}),e.jsxs(Kn,{onSelect:()=>b("/costs"),children:[e.jsx(wr,{className:"mr-2 h-4 w-4"}),"Costs"]}),e.jsxs(Kn,{onSelect:()=>b("/activity"),children:[e.jsx(sl,{className:"mr-2 h-4 w-4"}),"Activity"]})]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Fi,{}),e.jsx(Fa,{heading:"Issues",children:y.slice(0,10).map(v=>e.jsxs(Kn,{value:m.length>0?`${m} ${v.identifier??""} ${v.title}`:void 0,onSelect:()=>b(`/issues/${v.identifier??v.id}`),children:[e.jsx(rs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"text-muted-foreground mr-2 font-mono text-xs",children:v.identifier??v.id.slice(0,8)}),e.jsx("span",{className:"flex-1 truncate",children:v.title}),v.assigneeAgentId&&(()=>{const _=g(v.assigneeAgentId);return _?e.jsx(Ut,{name:_,size:"sm",className:"ml-2 hidden sm:inline-flex"}):null})()]},v.id))})]}),f.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Fi,{}),e.jsx(Fa,{heading:"Agents",children:f.slice(0,10).map(v=>e.jsxs(Kn,{onSelect:()=>b(Na(v)),children:[e.jsx(ss,{className:"mr-2 h-4 w-4"}),v.name,e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:v.role})]},v.id))})]}),j.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Fi,{}),e.jsx(Fa,{heading:"Projects",children:j.slice(0,10).map(v=>e.jsxs(Kn,{onSelect:()=>b(El(v)),children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"}),v.name]},v.id))})]})]})]})}const t3={r:24,g:24,b:27},n3={r:255,g:255,b:255};function Lx(t){const n=/^#?([0-9a-f]{3,6})$/i.exec(t.trim());if(!n)return null;let s=n[1];return s.length===3&&(s=s.split("").map(r=>`${r}${r}`).join("")),s.length!==6?null:{r:parseInt(s.slice(0,2),16),g:parseInt(s.slice(2,4),16),b:parseInt(s.slice(4,6),16)}}function Eu(t){const n=t/255;return n<=.03928?n/12.92:((n+.055)/1.055)**2.4}function Vo(t,n,s){return .2126*Eu(t)+.7152*Eu(n)+.0722*Eu(s)}function Jc(t,n){const s=Math.max(t,n),r=Math.min(t,n);return(s+.05)/(r+.05)}function s3(){return typeof document>"u"?!0:document.documentElement.classList.contains("dark")}function r3(t,n,s){return{r:Math.round(s*t.r+(1-s)*n.r),g:Math.round(s*t.g+(1-s)*n.g),b:Math.round(s*t.b+(1-s)*n.b)}}const Zc="#f8fafc",R0="#111827";function gh(t){const n=Lx(t);if(!n)return Zc;const s=Vo(n.r,n.g,n.b),r=Vo(248,250,252),a=Vo(17,24,39);return Jc(s,r)>=Jc(s,a)?Zc:R0}function Yd(t,n=.22){const s=Lx(t);if(!s)return Zc;const r=s3()?t3:n3,a=r3(s,r,n),o=Vo(a.r,a.g,a.b),i=Vo(248,250,252),l=Vo(17,24,39);return Jc(o,i)>=Jc(o,l)?Zc:R0}const or={list:(t,n)=>{const s=new URLSearchParams;n!=null&&n.projectId&&s.set("projectId",n.projectId),n!=null&&n.projectWorkspaceId&&s.set("projectWorkspaceId",n.projectWorkspaceId),n!=null&&n.issueId&&s.set("issueId",n.issueId),n!=null&&n.status&&s.set("status",n.status),n!=null&&n.reuseEligible&&s.set("reuseEligible","true");const r=s.toString();return ne.get(`/companies/${t}/execution-workspaces${r?`?${r}`:""}`)},get:t=>ne.get(`/execution-workspaces/${t}`),getCloseReadiness:t=>ne.get(`/execution-workspaces/${t}/close-readiness`),listWorkspaceOperations:t=>ne.get(`/execution-workspaces/${t}/workspace-operations`),controlRuntimeServices:(t,n)=>ne.post(`/execution-workspaces/${t}/runtime-services/${n}`,{}),update:(t,n)=>ne.patch(`/execution-workspaces/${t}`,n)},Rr={getGeneral:()=>ne.get("/instance/settings/general"),updateGeneral:t=>ne.patch("/instance/settings/general",t),getExperimental:()=>ne.get("/instance/settings/experimental"),updateExperimental:t=>ne.patch("/instance/settings/experimental",t)},Aa={uploadImage:async(t,n,s)=>{const r=await n.arrayBuffer(),a=new File([r],n.name,{type:n.type}),o=new FormData;return s&&s.trim().length>0&&o.append("namespace",s.trim()),o.append("file",a),ne.postForm(`/companies/${t}/assets/images`,o)},uploadCompanyLogo:async(t,n)=>{const s=await n.arrayBuffer(),r=new File([s],n.name,{type:n.type}),a=new FormData;return a.append("file",r),ne.postForm(`/companies/${t}/logo`,a)}},P0="crewspace:recent-assignees",bh=10;function Ol(){try{const t=localStorage.getItem(P0);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return[]}}function Xd(t){if(!t)return;const n=Ol().filter(s=>s!==t);n.unshift(t),n.length>bh&&(n.length=bh),localStorage.setItem(P0,JSON.stringify(n))}function eu(t,n){const s=new Map(n.map((r,a)=>[r,a]));return[...t].sort((r,a)=>{const o=s.get(r.id),i=s.get(a.id);return o!==void 0&&i!==void 0?o-i:o!==void 0?-1:i!==void 0?1:r.name.localeCompare(a.name)})}function Ds(t){return t.assigneeAgentId?`agent:${t.assigneeAgentId}`:t.assigneeUserId?`user:${t.assigneeUserId}`:""}function a3(t,n,s,r){if(n&&n.length>0&&(s||r))for(let a=n.length-1;a>=0;a--){const o=n[a];if(o.authorAgentId&&o.authorAgentId!==r)return Ds({assigneeAgentId:o.authorAgentId});if(o.authorUserId&&o.authorUserId!==s)return Ds({assigneeUserId:o.authorUserId})}return Ds(t)}function Vl(t){return t?t.startsWith("agent:")?{assigneeAgentId:t.slice(6)||null,assigneeUserId:null}:t.startsWith("user:")?{assigneeAgentId:null,assigneeUserId:t.slice(5)||null}:{assigneeAgentId:t,assigneeUserId:null}:{assigneeAgentId:null,assigneeUserId:null}}function o3(t){return t?[{id:Ds({assigneeUserId:t}),label:"Me",searchText:t==="local-board"?"me board human local-board":`me human ${t}`}]:[]}function Gm(t,n){return t?n&&t===n?"Me":t==="local-board"?"Board":t.slice(0,5):null}function Jm(t){const n=t.trim();return n.includes("/")&&n.slice(0,n.indexOf("/")).trim()||null}function Vi(t,n="other"){return Jm(t)??n}function M0(t){const n=t.trim();return n.includes("/")?n.slice(n.indexOf("/")+1).trim():n}const i3={backlog:"text-muted-foreground border-muted-foreground",todo:"text-blue-600 border-blue-600 dark:text-blue-400 dark:border-blue-400",in_progress:"text-yellow-600 border-yellow-600 dark:text-yellow-400 dark:border-yellow-400",in_review:"text-violet-600 border-violet-600 dark:text-violet-400 dark:border-violet-400",done:"text-green-600 border-green-600 dark:text-green-400 dark:border-green-400",cancelled:"text-neutral-500 border-neutral-500",blocked:"text-red-600 border-red-600 dark:text-red-400 dark:border-red-400"},l3="text-muted-foreground border-muted-foreground",Ii={backlog:"text-muted-foreground",todo:"text-blue-600 dark:text-blue-400",in_progress:"text-yellow-600 dark:text-yellow-400",in_review:"text-violet-600 dark:text-violet-400",done:"text-green-600 dark:text-green-400"},$0={active:"bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300",running:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300",paused:"bg-orange-100 text-orange-700 dark:bg-orange-900/50 dark:text-orange-300",idle:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-300",archived:"bg-muted text-muted-foreground",planned:"bg-muted text-muted-foreground",achieved:"bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300",completed:"bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300",failed:"bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300",timed_out:"bg-orange-100 text-orange-700 dark:bg-orange-900/50 dark:text-orange-300",succeeded:"bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300",error:"bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300",terminated:"bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300",pending:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-300",pending_approval:"bg-amber-100 text-amber-700 dark:bg-amber-900/50 dark:text-amber-300",revision_requested:"bg-amber-100 text-amber-700 dark:bg-amber-900/50 dark:text-amber-300",approved:"bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300",rejected:"bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300",backlog:"bg-muted text-muted-foreground",todo:"bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300",in_progress:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-300",in_review:"bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300",blocked:"bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300",done:"bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300",cancelled:"bg-muted text-muted-foreground"},D0="bg-muted text-muted-foreground",Fx={running:"bg-cyan-400 animate-pulse",active:"bg-green-400",paused:"bg-yellow-400",idle:"bg-yellow-400",pending_approval:"bg-amber-400",error:"bg-red-400",archived:"bg-neutral-400"},qx="bg-neutral-400",ua={critical:"text-red-600 dark:text-red-400",high:"text-orange-600 dark:text-orange-400",medium:"text-yellow-600 dark:text-yellow-400",low:"text-blue-600 dark:text-blue-400"},yh=new Map;function Ux(t){const n=M_(t);if(n)return{kind:"agent",agentId:n.agentId,icon:n.icon};const s=P_(t);return s?{kind:"project",projectId:s.projectId,color:s.color}:null}function O0(t){const n={};if(t.kind==="project"&&t.color){const s=c3(t.color);Object.assign(n,s),n["--crewspace-mention-project-color"]=t.color}if(t.kind==="agent"){const s=d3(t.icon);s&&(n["--crewspace-mention-icon-mask"]=s)}return Object.keys(n).length>0?n:void 0}function vh(t,n){L0(t),t.dataset.mentionKind=n.kind,t.setAttribute("contenteditable","false"),t.classList.add("crewspace-mention-chip",`crewspace-mention-chip--${n.kind}`),n.kind==="project"&&t.classList.add("crewspace-project-mention-chip");const s=O0(n);if(s)for(const[r,a]of Object.entries(s))typeof a=="string"&&(r.startsWith("--")?t.style.setProperty(r,a):t.style[r]=a)}function L0(t){delete t.dataset.mentionKind,t.classList.remove("crewspace-mention-chip","crewspace-mention-chip--agent","crewspace-mention-chip--project","crewspace-project-mention-chip"),t.removeAttribute("contenteditable"),t.style.removeProperty("border-color"),t.style.removeProperty("background-color"),t.style.removeProperty("color"),t.style.removeProperty("--crewspace-mention-project-color"),t.style.removeProperty("--crewspace-mention-icon-mask")}function c3(t){const n=Lx(t);return n?{borderColor:t,backgroundColor:`rgba(${n.r}, ${n.g}, ${n.b}, 0.22)`,color:Yd(t)}:{}}function d3(t){const n=t??"__default__",s=yh.get(n);if(s)return s;const r=e0(t),a=u3(r);if(!Array.isArray(a)||a.length===0)return null;const i=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${a.map(([u,d])=>{const m=Object.entries(d).filter(([p])=>p!=="key").map(([p,x])=>`${p}="${m3(String(x))}"`).join(" ");return`<${u}${m?` ${m}`:""}></${u}>`}).join("")}</svg>`,l=`url("data:image/svg+xml,${encodeURIComponent(i)}")`;return yh.set(n,l),l}function u3(t){var o;const n=t.iconNode;if(Array.isArray(n)&&n.length>0)return n;const s=t.render,r=typeof s=="function"?s({},null):null,a=(o=r==null?void 0:r.props)==null?void 0:o.iconNode;return Array.isArray(a)&&a.length>0?a:null}function m3(t){return t.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}const p3=/^(agent|project):\/\//;class oi extends qb{static getType(){return"mention-aware-link"}static clone(n){return new oi(n.getURL(),{rel:n.getRel(),target:n.getTarget(),title:n.getTitle()},n.getKey())}static importJSON(n){return new oi(n.url??"",{rel:n.rel??null,target:n.target??null,title:n.title??null})}constructor(n,s,r){super(n,s,r)}sanitizeUrl(n){return p3.test(n)?n:super.sanitizeUrl(n)}}function x3(t){return{url:t.getURL(),attributes:{rel:t.getRel(),target:t.getTarget(),title:t.getTitle()}}}const f3={replace:qb,with:t=>{const{url:n,attributes:s}=x3(t);return new oi(n,s)},withKlass:oi};function jh(t){return!!(t&&nC(t)&&Ux(t.getURL()))}function Ua(t){if(!t)return null;if(jh(t))return t;let n=t.getParent();for(;n;){if(jh(n))return n;n=n.getParent()}return null}function h3(t,n){const s=t.getNode(),r=Ua(s);if(r)return r;if(t.type==="element"&&eC(s)){const a=n==="backward"?t.offset-1:t.offset;return a<0?null:Ua(s.getChildAtIndex(a))}if(t.type==="text"&&tC(s)){if(n==="backward"&&t.offset===0)return Ua(s.getPreviousSibling());if(n==="forward"&&t.offset===s.getTextContentSize())return Ua(s.getNextSibling())}return null}function g3(t){const n=Zk();if(!n)return null;if(Yk(n)){const[a]=n.getNodes();return a?Ua(a):null}if(!Xk(n))return null;const s=Ua(n.anchor.getNode()),r=Ua(n.focus.getNode());return s&&r&&s.is(r)?s:n.isCollapsed()?h3(n.anchor,t):null}function b3(t){const n=g3(t);if(!n)return!1;const s=n.getPreviousSibling(),r=n.getNextSibling(),a=n.getParentOrThrow();return n.remove(),t==="backward"?s?(s.selectEnd(),!0):r?(r.selectStart(),!0):(a.selectStart(),!0):r?(r.selectStart(),!0):s?(s.selectEnd(),!0):(a.selectEnd(),!0)}function wh(t,n){return b3(t)?(n==null||n.preventDefault(),n==null||n.stopPropagation(),!0):!1}const y3=Vk({init(t){t.pub(Qk,[n=>n.registerCommand(Gk,s=>wh("backward",s),bf),n=>n.registerCommand(Jk,s=>wh("forward",s),bf)])}});function v3(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j3(t){const n=t.trim();return n?!/^(javascript|data|vbscript):/i.test(n):!0}const w3={txt:"Text",md:"Markdown",js:"JavaScript",jsx:"JavaScript (JSX)",ts:"TypeScript",tsx:"TypeScript (TSX)",json:"JSON",bash:"Bash",sh:"Shell",python:"Python",go:"Go",rust:"Rust",sql:"SQL",html:"HTML",css:"CSS",yaml:"YAML",yml:"YAML"},N3={priority:0,match:()=>!0,Editor:pC};function k3(t){const n=window.getSelection();if(!n||n.rangeCount===0||!n.isCollapsed)return null;const s=n.getRangeAt(0),r=s.startContainer;if(r.nodeType!==Node.TEXT_NODE||!t.contains(r))return null;const a=r.textContent??"",o=s.startOffset;let i=-1;for(let p=o-1;p>=0;p--){const x=a[p];if(x==="@"){(p===0||/\s/.test(a[p-1]))&&(i=p);break}if(/\s/.test(x))break}if(i===-1)return null;const l=a.slice(i+1,o),u=document.createRange();u.setStart(r,i),u.setEnd(r,i+1);const d=u.getBoundingClientRect(),m=t.getBoundingClientRect();return{query:l,top:d.bottom-m.top,left:d.left-m.left,viewportTop:d.bottom,viewportLeft:d.left,textNode:r,atPos:i,endPos:o}}function C3(t){if(t.kind==="project"&&t.projectId)return`[@${t.name}](${oj(t.projectId,t.projectColor??null)}) `;const n=t.agentId??t.id.replace(/^agent:/,"");return`[@${t.name}](${ij(n,t.agentIcon??null)}) `}function S3(t,n,s){const r=`@${n}`,a=C3(s),o=t.lastIndexOf(r);return o===-1?t:t.slice(0,o)+a+t.slice(o+r.length)}const ps=c.forwardRef(function({value:n,onChange:s,placeholder:r,className:a,contentClassName:o,onBlur:i,imageUploadHandler:l,bordered:u=!0,mentions:d,onSubmit:m},p){const x=c.useRef(null),f=c.useRef(null),h=c.useRef(n),[j,b]=c.useState(null),[g,y]=c.useState(!1),v=c.useRef(0),_=c.useRef(l);_.current=l;const[E,S]=c.useState(null),M=c.useRef(null),[B,k]=c.useState(0),L=E!==null&&d&&d.length>0,$=c.useMemo(()=>{const R=new Map;for(const Q of d??[]){if(Q.kind==="agent"){const H=Q.agentId??Q.id.replace(/^agent:/,"");R.set(`agent:${H}`,Q)}Q.kind==="project"&&Q.projectId&&R.set(`project:${Q.projectId}`,Q)}return R},[d]),C=c.useMemo(()=>{if(!E||!d)return[];const R=E.query.toLowerCase();return d.filter(Q=>Q.name.toLowerCase().includes(R)).slice(0,8)},[E==null?void 0:E.query,d]);c.useImperativeHandle(p,()=>({focus:()=>{var R;(R=f.current)==null||R.focus(void 0,{defaultSelection:"rootEnd"})}}),[]);const I=!!l,K=c.useMemo(()=>{const R=I?async H=>{const U=_.current;if(!U)throw new Error("No image upload handler");try{const Z=await U(H);return b(null),setTimeout(()=>{var Y;const V=h.current,W=v3(Z),J=V.replace(new RegExp(`(!\\[[^\\]]*\\]\\(${W}\\))(?!\\n\\n)`,"g"),`$1
|
|
34
|
+
|
|
35
|
+
`);J!==V&&(h.current=J,(Y=f.current)==null||Y.setMarkdown(J),s(J),requestAnimationFrame(()=>{var de;(de=f.current)==null||de.focus(void 0,{defaultSelection:"rootEnd"})}))},100),Z}catch(Z){const V=Z instanceof Error?Z.message:"Image upload failed";throw b(V),Z}}:void 0,Q=[aC(),oC(),iC(),lC(),cC({validateUrl:j3}),dC(),y3(),uC(),mC({defaultCodeBlockLanguage:"txt",codeBlockEditorDescriptors:[N3]}),xC({codeBlockLanguages:w3}),fC()];return R&&Q.push(sC({imageUploadHandler:R})),Q},[I]);c.useEffect(()=>{var R;n!==h.current&&((R=f.current)==null||R.setMarkdown(n),h.current=n)},[n]);const T=c.useCallback(()=>{var H;const R=(H=x.current)==null?void 0:H.querySelector('[contenteditable="true"]');if(!R)return;const Q=R.querySelectorAll("a");for(const U of Q){const Z=U,V=Ux(Z.getAttribute("href")??"");if(!V){L0(Z);continue}if(V.kind==="project"){const J=$.get(`project:${V.projectId}`);vh(Z,{...V,color:V.color??(J==null?void 0:J.projectColor)??null});continue}const W=$.get(`agent:${V.agentId}`);vh(Z,{...V,icon:V.icon??(W==null?void 0:W.agentIcon)??null})}},[$]),z=c.useCallback(()=>{if(!d||d.length===0||!x.current){M.current=null,S(null);return}const R=k3(x.current);M.current=R,R?(S(R),k(0)):S(null)},[d]);c.useEffect(()=>{if(!d||d.length===0)return;const R=x.current,Q=()=>requestAnimationFrame(z);return document.addEventListener("selectionchange",z),R==null||R.addEventListener("input",Q,!0),()=>{document.removeEventListener("selectionchange",z),R==null||R.removeEventListener("input",Q,!0)}},[z,d]),c.useEffect(()=>{var H;const R=(H=x.current)==null?void 0:H.querySelector('[contenteditable="true"]');if(!R)return;T();const Q=new MutationObserver(()=>{T()});return Q.observe(R,{subtree:!0,childList:!0,characterData:!0}),()=>Q.disconnect()},[T,n]);const w=c.useCallback(R=>{var Z;const Q=M.current;if(!Q)return;const H=h.current,U=S3(H,Q.query,R);U!==H&&(h.current=U,(Z=f.current)==null||Z.setMarkdown(U),s(U)),requestAnimationFrame(()=>{requestAnimationFrame(()=>{var Re,Pe;const V=(Re=x.current)==null?void 0:Re.querySelector('[contenteditable="true"]');if(!(V instanceof HTMLElement))return;T(),V.focus();const W=R.kind==="project"&&R.projectId?oj(R.projectId,R.projectColor??null):ij(R.agentId??R.id.replace(/^agent:/,""),R.agentIcon??null),J=Array.from(V.querySelectorAll("a")).filter(Fe=>Fe instanceof HTMLAnchorElement).filter(Fe=>(Fe.getAttribute("href")??"")===W&&Fe.textContent===`@${R.name}`),Y=(Pe=x.current)==null?void 0:Pe.getBoundingClientRect(),de=J.sort((Fe,pe)=>{const Le=Fe.getBoundingClientRect(),q=pe.getBoundingClientRect(),D=Y?Le.left-Y.left:Le.left,ie=Y?Le.top-Y.top:Le.top,Ie=Y?q.left-Y.left:q.left,ue=Y?q.top-Y.top:q.top,Be=Math.hypot(D-Q.left,ie-Q.top),be=Math.hypot(Ie-Q.left,ue-Q.top);return Be-be})[0]??null;if(!de)return;const fe=window.getSelection();if(!fe)return;const Ce=document.createRange(),le=de.nextSibling;if((le==null?void 0:le.nodeType)===Node.TEXT_NODE&&(le.textContent??"").startsWith(" ")){Ce.setStart(le,1),Ce.collapse(!0),fe.removeAllRanges(),fe.addRange(Ce);return}Ce.setStartAfter(de),Ce.collapse(!0),fe.removeAllRanges(),fe.addRange(Ce)})}),M.current=null,S(null)},[T,s]);function F(R){var Q;return Array.from(((Q=R.dataTransfer)==null?void 0:Q.types)??[]).includes("Files")}const A=!!l;return e.jsxs("div",{ref:x,className:O("relative crewspace-mdxeditor-scope",u?"rounded-md border border-border bg-transparent":"bg-transparent",g&&"ring-1 ring-primary/60 bg-accent/20",a),onKeyDownCapture:R=>{if(m&&R.key==="Enter"&&(R.metaKey||R.ctrlKey)){R.preventDefault(),R.stopPropagation(),m();return}if(L){if(R.key===" "){M.current=null,S(null);return}if(R.key==="Escape"){R.preventDefault(),R.stopPropagation(),M.current=null,S(null);return}if(C.length>0){if(R.key==="ArrowDown"){R.preventDefault(),R.stopPropagation(),k(Q=>Math.min(Q+1,C.length-1));return}if(R.key==="ArrowUp"){R.preventDefault(),R.stopPropagation(),k(Q=>Math.max(Q-1,0));return}if(R.key==="Enter"||R.key==="Tab"){R.preventDefault(),R.stopPropagation(),w(C[B]);return}}}},onDragEnter:R=>{!A||!F(R)||(v.current+=1,y(!0))},onDragOver:R=>{!A||!F(R)||(R.preventDefault(),R.dataTransfer.dropEffect="copy")},onDragLeave:()=>{A&&(v.current=Math.max(0,v.current-1),v.current===0&&y(!1))},onDrop:()=>{v.current=0,y(!1)},children:[e.jsx(rC,{ref:f,markdown:n,placeholder:r,onChange:R=>{h.current=R,s(R)},onBlur:()=>i==null?void 0:i(),className:O("crewspace-mdxeditor",!u&&"crewspace-mdxeditor--borderless"),contentEditableClassName:O("crewspace-mdxeditor-content focus:outline-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:list-item",o),additionalLexicalNodes:[oi,f3],plugins:K}),L&&C.length>0&&Lo.createPortal(e.jsx("div",{className:"fixed z-[9999] min-w-[180px] max-w-[calc(100vw-16px)] max-h-[200px] overflow-y-auto rounded-md border border-border bg-popover shadow-md",style:{top:Math.min(E.viewportTop+4,window.innerHeight-208),left:Math.max(8,Math.min(E.viewportLeft,window.innerWidth-188))},children:C.map((R,Q)=>e.jsxs("button",{className:O("flex items-center gap-2 w-full px-3 py-1.5 text-sm text-left hover:bg-accent/50 transition-colors",Q===B&&"bg-accent"),onMouseDown:H=>{H.preventDefault(),w(R)},onMouseEnter:()=>k(Q),children:[R.kind==="project"&&R.projectId?e.jsx("span",{className:"inline-flex h-2 w-2 rounded-full border border-border/50",style:{backgroundColor:R.projectColor??"#64748b"}}):e.jsx(Cn,{icon:R.agentIcon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:R.name}),R.kind==="project"&&R.projectId&&e.jsx("span",{className:"ml-auto text-[10px] uppercase tracking-wide text-muted-foreground",children:"Project"})]},R.id))}),document.body),g&&A&&e.jsx("div",{className:O("pointer-events-none absolute inset-1 z-40 flex items-center justify-center rounded-md border border-dashed border-primary/80 bg-primary/10 text-xs font-medium text-primary",!u&&"inset-0 rounded-sm"),children:"Drop image to upload"}),j&&e.jsx("p",{className:"px-3 pb-2 text-xs text-destructive",children:j})]})}),ba=c.forwardRef(function({value:n,options:s,placeholder:r,noneLabel:a,searchPlaceholder:o,emptyMessage:i,onChange:l,onConfirm:u,className:d,renderTriggerValue:m,renderOption:p,disablePortal:x},f){const[h,j]=c.useState(!1),[b,g]=c.useState(""),[y,v]=c.useState(0),_=c.useRef(null),E=c.useRef(!1),S=c.useRef(!1),M=c.useMemo(()=>[{id:"",label:a,searchText:a},...s],[a,s]),B=c.useMemo(()=>{const $=b.trim().toLowerCase();return $?M.filter(C=>`${C.label} ${C.searchText??""}`.toLowerCase().includes($)):M},[M,b]),k=s.find($=>$.id===n)??null;c.useEffect(()=>{if(!h)return;const $=B.findIndex(C=>C.id===n);v($>=0?$:0)},[B,h,n]);const L=($,C)=>{const I=B[$]??B[0];I&&l(I.id),E.current=C,j(!1),g(""),u&&requestAnimationFrame(()=>{u()})};return e.jsxs(Ht,{open:h,onOpenChange:$=>{j($),$||g("")},children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{ref:f,type:"button",className:O("inline-flex min-w-0 items-center gap-1 rounded-md border border-border bg-muted/40 px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",d),onPointerDown:()=>{S.current=!0},onFocus:()=>{S.current||j(!0),S.current=!1},children:m?m(k):(k==null?void 0:k.label)??e.jsx("span",{className:"text-muted-foreground",children:r})})}),e.jsxs(Qt,{align:"start",side:"bottom",collisionPadding:16,className:"w-[min(20rem,calc(100vw-2rem))] p-1",disablePortal:x,onOpenAutoFocus:$=>{var I;$.preventDefault(),window.matchMedia("(pointer: coarse)").matches||(I=_.current)==null||I.focus()},onCloseAutoFocus:$=>{E.current&&($.preventDefault(),E.current=!1)},children:[e.jsx("input",{ref:_,className:"w-full border-b border-border bg-transparent px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground/60",placeholder:o,value:b,onChange:$=>{g($.target.value)},onKeyDown:$=>{if($.key==="ArrowDown"){$.preventDefault(),v(C=>B.length===0?0:(C+1)%B.length);return}if($.key==="ArrowUp"){$.preventDefault(),v(C=>B.length===0?0:C<=0?B.length-1:C-1);return}if($.key==="Enter"){$.preventDefault(),L(y,!0);return}if($.key==="Tab"&&!$.shiftKey){$.preventDefault(),L(y,!0);return}$.key==="Escape"&&($.preventDefault(),j(!1))}}),e.jsx("div",{className:"max-h-56 overflow-y-auto overscroll-contain py-1 touch-pan-y",children:B.length===0?e.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:i}):B.map(($,C)=>{const I=$.id===n,K=C===y;return e.jsxs("button",{type:"button",className:O("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm touch-manipulation",K&&"bg-accent"),onMouseEnter:()=>v(C),onClick:()=>L(C,!0),children:[p?p($,I):e.jsx("span",{className:"truncate",children:$.label}),e.jsx(Nn,{className:O("ml-auto h-3.5 w-3.5 text-muted-foreground",I?"opacity-100":"opacity-0")})]},$.id||"__none__")})})]})]})}),Bx="crewspace:issue-draft",I3=800,F0=new Set(["claude_local","codex_local","opencode_local"]),_3="image/*,application/pdf,text/plain,text/markdown,application/json,text/csv,text/html,.md,.markdown",wo={claude_local:[{value:"",label:"Default"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],codex_local:[{value:"",label:"Default"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"X-High"}],opencode_local:[{value:"",label:"Default"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"X-High"},{value:"max",label:"Max"}]};function A3(t){const n=t.adapterType??null;if(!n||!F0.has(n))return null;const s={};t.modelOverride&&(s.model=t.modelOverride),t.thinkingEffortOverride&&(n==="codex_local"?s.modelReasoningEffort=t.thinkingEffortOverride:n==="opencode_local"?s.variant=t.thinkingEffortOverride:n==="claude_local"?s.effort=t.thinkingEffortOverride:n==="opencode_local"&&(s.variant=t.thinkingEffortOverride)),n==="claude_local"&&t.chrome&&(s.chrome=!0);const r={};return Object.keys(s).length>0&&(r.adapterConfig=s),Object.keys(r).length>0?r:null}function Nh(){try{const t=localStorage.getItem(Bx);return t?JSON.parse(t):null}catch{return null}}function E3(t){localStorage.setItem(Bx,JSON.stringify(t))}function kh(){localStorage.removeItem(Bx)}function T3(t){const n=t.name.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".txt")||t.type==="text/markdown"||t.type==="text/plain"}function R3(t){return t.replace(/\.[^.]+$/,"")}function P3(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"document"}function M3(t){return t.split(/[-_ ]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function $3(t,n){const s=new Set(n.filter(a=>a.kind==="document").map(a=>a.documentKey).filter(a=>!!a));if(!s.has(t))return t;let r=2;for(;s.has(`${t}-${r}`);)r+=1;return`${t}-${r}`}function Ch(t){return t.size<1024?`${t.size} B`:t.size<1024*1024?`${(t.size/1024).toFixed(1)} KB`:`${(t.size/(1024*1024)).toFixed(1)} MB`}const Tu=[{value:"backlog",label:"Backlog",color:Ii.backlog},{value:"todo",label:"Todo",color:Ii.todo},{value:"in_progress",label:"In Progress",color:Ii.in_progress},{value:"in_review",label:"In Review",color:Ii.in_review},{value:"done",label:"Done",color:Ii.done}],Sh=[{value:"critical",label:"Critical",icon:ir,color:ua.critical},{value:"high",label:"High",icon:Qb,color:ua.high},{value:"medium",label:"Medium",icon:Ep,color:ua.medium},{value:"low",label:"Low",icon:Tp,color:ua.low}],D3=[{value:"shared_workspace",label:"Project default"},{value:"isolated_workspace",label:"New isolated workspace"},{value:"reuse_existing",label:"Reuse existing workspace"}];function _i(t){var n,s,r,a,o;return t?((n=t.executionWorkspacePolicy)==null?void 0:n.defaultProjectWorkspaceId)??((r=(s=t.workspaces)==null?void 0:s.find(i=>i.isPrimary))==null?void 0:r.id)??((o=(a=t.workspaces)==null?void 0:a[0])==null?void 0:o.id)??"":""}function Ai(t){var s;const n=(s=t==null?void 0:t.executionWorkspacePolicy)!=null&&s.enabled?t.executionWorkspacePolicy.defaultMode:null;return n==="isolated_workspace"||n==="operator_branch"||n==="adapter_default"?n==="adapter_default"?"agent_default":n:"shared_workspace"}function O3(t){return t==="isolated_workspace"||t==="operator_branch"||t==="shared_workspace"?t:t==="adapter_managed"||t==="cloud_sandbox"?"agent_default":"shared_workspace"}function L3(){var xf,ff,hf;const{newIssueOpen:t,newIssueDefaults:n,closeNewIssue:s}=In(),{companies:r,selectedCompanyId:a,selectedCompany:o}=et(),i=at(),{pushToast:l}=ds(),[u,d]=c.useState(""),[m,p]=c.useState(""),[x,f]=c.useState("todo"),[h,j]=c.useState(""),[b,g]=c.useState(""),[y,v]=c.useState(""),[_,E]=c.useState(""),[S,M]=c.useState(!1),[B,k]=c.useState(""),[L,$]=c.useState(""),[C,I]=c.useState(!1),[K,T]=c.useState("shared_workspace"),[z,w]=c.useState(""),[F,A]=c.useState(!1),[R,Q]=c.useState(null),[H,U]=c.useState([]),[Z,V]=c.useState(!1),W=c.useRef(null),J=c.useRef(null),Y=R??a,de=r.find(X=>X.id===Y)??o,[fe,Ce]=c.useState(!1),[le,Re]=c.useState(!1),[Pe,Fe]=c.useState(!1),[pe,Le]=c.useState(!1),q=c.useRef(null),D=c.useRef(null),ie=c.useRef(null),Ie=c.useRef(null),{data:ue}=oe({queryKey:N.agents.list(Y),queryFn:()=>We.list(Y),enabled:!!Y&&t}),Be=c.useMemo(()=>(ue??[]).find(X=>X.role==="ceo")??null,[ue]);c.useEffect(()=>{!t||!Be||g(X=>X||Ds({assigneeAgentId:Be.id}))},[Be,t]);const{data:be}=oe({queryKey:N.projects.list(Y),queryFn:()=>en.list(Y),enabled:!!Y&&t}),{data:he}=oe({queryKey:N.executionWorkspaces.list(Y,{projectId:y,projectWorkspaceId:_||void 0,reuseEligible:!0}),queryFn:()=>or.list(Y,{projectId:y,projectWorkspaceId:_||void 0,reuseEligible:!0}),enabled:!!Y&&t&&!!y}),{data:Se}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),{data:we}=oe({queryKey:N.instance.experimentalSettings,queryFn:()=>Rr.getExperimental(),enabled:t}),ee=((xf=Se==null?void 0:Se.user)==null?void 0:xf.id)??((ff=Se==null?void 0:Se.session)==null?void 0:ff.userId)??null,me=c.useMemo(()=>(be??[]).filter(X=>!X.archivedAt),[be]),{orderedProjects:ye}=$l({projects:me,companyId:Y,userId:ee}),Ke=c.useMemo(()=>Vl(b),[b]),qe=Ke.assigneeAgentId,se=Ke.assigneeUserId,ce=((hf=(ue??[]).find(X=>X.id===qe))==null?void 0:hf.adapterType)??null,Te=!!(ce&&F0.has(ce)),ae=c.useMemo(()=>{const X=[],Ge=[...ue??[]].filter(tt=>tt.status!=="terminated").sort((tt,Ct)=>tt.name.localeCompare(Ct.name));for(const tt of Ge)X.push({id:`agent:${tt.id}`,name:tt.name,kind:"agent",agentId:tt.id,agentIcon:tt.icon});for(const tt of ye)X.push({id:`project:${tt.id}`,name:tt.name,kind:"project",projectId:tt.id,projectColor:tt.color});return X},[ue,ye]),{data:je}=oe({queryKey:Y&&ce?N.agents.adapterModels(Y,ce):["agents","none","adapter-models",ce??"none"],queryFn:()=>We.adapterModels(Y,ce),enabled:!!Y&&t&&Te}),ke=ge({mutationFn:async({companyId:X,stagedFiles:Ge,...tt})=>{const Ct=await nt.create(X,tt),Dn=[];for(const es of Ge)try{if(es.kind==="document"){const Ea=await es.file.text();await nt.upsertDocument(Ct.id,es.documentKey??"document",{title:es.documentKey==="plan"?null:es.title??null,format:"markdown",body:Ea,baseRevisionId:null})}else await nt.uploadAttachment(X,Ct.id,es.file)}catch{Dn.push(es.file.name)}return{issue:Ct,companyId:X,failures:Dn}},onSuccess:({issue:X,companyId:Ge,failures:tt})=>{var Ct;if(i.invalidateQueries({queryKey:N.issues.list(Ge)}),i.invalidateQueries({queryKey:N.issues.listMineByMe(Ge)}),i.invalidateQueries({queryKey:N.issues.listTouchedByMe(Ge)}),i.invalidateQueries({queryKey:N.issues.listUnreadTouchedByMe(Ge)}),i.invalidateQueries({queryKey:N.sidebarBadges(Ge)}),W.current&&clearTimeout(W.current),tt.length>0){const Dn=(((Ct=r.find(Ea=>Ea.id===Ge))==null?void 0:Ct.issuePrefix)??"").trim(),es=X.identifier??X.id;l({title:`Created ${es} with upload warnings`,body:`${tt.length} staged ${tt.length===1?"file":"files"} could not be added.`,tone:"warn",action:Dn?{label:`Open ${es}`,href:`/${Dn}/issues/${es}`}:void 0})}kh(),It(),s()}}),Xe=ge({mutationFn:async X=>{if(!Y)throw new Error("No company selected");return Aa.uploadImage(Y,X,"issues/drafts")}}),lt=c.useCallback(X=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{X.title.trim()&&E3(X)},I3)},[]);c.useEffect(()=>{t&<({title:u,description:m,status:x,priority:h,assigneeValue:b,projectId:y,projectWorkspaceId:_,assigneeModelOverride:B,assigneeThinkingEffort:L,assigneeChrome:C,executionWorkspaceMode:K,selectedExecutionWorkspaceId:z})},[u,m,x,h,b,y,_,B,L,C,K,z,t,lt]),c.useEffect(()=>{if(!t)return;Q(a),J.current=null;const X=Nh();if(n.title){d(n.title),p(n.description??""),f(n.status??"todo"),j(n.priority??"");const Ge=n.projectId??"",tt=ye.find(Ct=>Ct.id===Ge);v(Ge),E(_i(tt)),g(Ds(n)||(Be?Ds({assigneeAgentId:Be.id}):"")),k(""),$(""),I(!1),T(Ai(tt)),w(""),J.current=Ge||null}else if(X&&X.title.trim()){const Ge=n.projectId??X.projectId,tt=ye.find(Ct=>Ct.id===Ge);d(X.title),p(X.description),f(X.status||"todo"),j(X.priority),g(n.assigneeAgentId||n.assigneeUserId?Ds(n):X.assigneeValue||X.assigneeId||(Be?Ds({assigneeAgentId:Be.id}):"")),v(Ge),E(X.projectWorkspaceId??_i(tt)),k(X.assigneeModelOverride??""),$(X.assigneeThinkingEffort??""),I(X.assigneeChrome??!1),T(X.executionWorkspaceMode??(X.useIsolatedExecutionWorkspace?"isolated_workspace":Ai(tt))),w(X.selectedExecutionWorkspaceId??""),J.current=Ge||null}else{const Ge=n.projectId??"",tt=ye.find(Ct=>Ct.id===Ge);f(n.status??"todo"),j(n.priority??""),v(Ge),E(_i(tt)),g(Ds(n)||(Be?Ds({assigneeAgentId:Be.id}):"")),k(""),$(""),I(!1),T(Ai(tt)),w(""),J.current=Ge||null}},[t,n,ye]),c.useEffect(()=>{if(!Te){M(!1),k(""),$(""),I(!1);return}(ce==="codex_local"?wo.codex_local:ce==="opencode_local"?wo.opencode_local:wo.claude_local).some(Ge=>Ge.value===L)||$("")},[Te,ce,L]),c.useEffect(()=>()=>{W.current&&clearTimeout(W.current)},[]);function It(){d(""),p(""),f("todo"),j(""),g(""),v(""),E(""),M(!1),k(""),$(""),I(!1),T("shared_workspace"),w(""),A(!1),Q(null),U([]),V(!1),Le(!1),J.current=null}function Ue(X){X!==Y&&(Q(X),g(""),v(""),E(""),k(""),$(""),I(!1),T("shared_workspace"),w(""))}function pt(){kh(),It(),s()}function ht(){if(!Y||!u.trim()||ke.isPending)return;const X=A3({adapterType:ce,modelOverride:B,thinkingEffortOverride:L,chrome:C}),Ge=ye.find(Ea=>Ea.id===y),tt=(we==null?void 0:we.enableIsolatedWorkspaces)===!0?(Ge==null?void 0:Ge.executionWorkspacePolicy)??null:null,Ct=Ae.find(Ea=>Ea.id===z),Dn=K==="reuse_existing"?O3(Ct==null?void 0:Ct.mode):K,es=tt!=null&&tt.enabled?{mode:Dn}:null;ke.mutate({companyId:Y,stagedFiles:H,title:u.trim(),description:m.trim()||void 0,status:x,priority:h||"medium",...qe?{assigneeAgentId:qe}:{},...se?{assigneeUserId:se}:{},...y?{projectId:y}:{},..._?{projectWorkspaceId:_}:{},...X?{assigneeAdapterOverrides:X}:{},...tt!=null&&tt.enabled?{executionWorkspacePreference:K}:{},...K==="reuse_existing"&&z?{executionWorkspaceId:z}:{},...es?{executionWorkspaceSettings:es}:{}})}function ln(X){X.key==="Enter"&&(X.metaKey||X.ctrlKey)&&(X.preventDefault(),ht())}function yt(X){X.length!==0&&U(Ge=>{const tt=[...Ge];for(const Ct of X){if(T3(Ct)){const Dn=R3(Ct.name),es=$3(P3(Dn),tt);tt.push({id:`${Ct.name}:${Ct.size}:${Ct.lastModified}:${es}`,file:Ct,kind:"document",documentKey:es,title:M3(Dn)});continue}tt.push({id:`${Ct.name}:${Ct.size}:${Ct.lastModified}`,file:Ct,kind:"attachment"})}return tt})}function hn(X){yt(Array.from(X.target.files??[])),D.current&&(D.current.value="")}function pn(X){X.dataTransfer.types.includes("Files")&&(X.preventDefault(),V(!0))}function re(X){X.dataTransfer.types.includes("Files")&&(X.preventDefault(),X.dataTransfer.dropEffect="copy",V(!0))}function $e(X){X.currentTarget.contains(X.relatedTarget)||V(!1)}function Ee(X){X.dataTransfer.files.length&&(X.preventDefault(),V(!1),yt(Array.from(X.dataTransfer.files)))}function He(X){U(Ge=>Ge.filter(tt=>tt.id!==X))}const rt=u.trim().length>0||m.trim().length>0||H.length>0,xt=Tu.find(X=>X.value===x)??Tu[1],Pt=Sh.find(X=>X.value===h),gn=qe?(ue??[]).find(X=>X.id===qe):null,$n=ye.find(X=>X.id===y),Ne=(we==null?void 0:we.enableIsolatedWorkspaces)===!0?($n==null?void 0:$n.executionWorkspacePolicy)??null:null,te=!!(Ne!=null&&Ne.enabled),Ae=c.useMemo(()=>{const X=he??[],Ge=new Map;for(const tt of X){const Ct=tt.cwd??tt.id,Dn=Ge.get(Ct);(!Dn||new Date(tt.lastUsedAt)>new Date(Dn.lastUsedAt))&&Ge.set(Ct,tt)}return Array.from(Ge.values())},[he]),Je=Ae.find(X=>X.id===z),ft=ce==="claude_local"?"Claude options":ce==="codex_local"?"Codex options":ce==="opencode_local"?"OpenCode options":"Agent options",xn=ce==="codex_local"?wo.codex_local:ce==="opencode_local"?wo.opencode_local:wo.claude_local,_n=c.useMemo(()=>Ol(),[t]),bt=c.useMemo(()=>[...o3(ee),...eu((ue??[]).filter(X=>X.status!=="terminated"),_n).map(X=>({id:Ds({assigneeAgentId:X.id}),label:X.name,searchText:`${X.name} ${X.role} ${X.title??""}`}))],[ue,ee,_n]),Gt=c.useMemo(()=>ye.map(X=>({id:X.id,label:X.name,searchText:X.description??""})),[ye]),Jr=Nh(),cu=!!(Jr!=null&&Jr.title.trim()||Jr!=null&&Jr.description.trim()),ki=rt||cu,Bl=ke.error instanceof Error?ke.error.message:"Failed to create issue. Try again.",qt=H.filter(X=>X.kind==="document"),us=H.filter(X=>X.kind==="attachment"),qs=c.useCallback(X=>{v(X);const Ge=ye.find(tt=>tt.id===X);J.current=X||null,E(_i(Ge)),T(Ai(Ge)),w("")},[ye]);c.useEffect(()=>{if(!t||!y||J.current===y)return;const X=ye.find(Ge=>Ge.id===y);X&&(J.current=y,E(_i(X)),T(Ai(X)),w(""))},[t,ye,y]);const ok=c.useMemo(()=>[...je??[]].sort((X,Ge)=>{const tt=Vi(X.id),Ct=Vi(Ge.id),Dn=tt.localeCompare(Ct);return Dn!==0?Dn:X.id.localeCompare(Ge.id)}).map(X=>({id:X.id,label:X.label,searchText:`${X.id} ${Vi(X.id)}`})),[je]);return e.jsx(Cs,{open:t,onOpenChange:X=>{!X&&!ke.isPending&&s()},children:e.jsxs(Fs,{showCloseButton:!1,"aria-describedby":void 0,className:O("p-0 gap-0 flex flex-col max-h-[calc(100dvh-2rem)]",F?"sm:max-w-2xl h-[calc(100dvh-2rem)]":"sm:max-w-lg"),onKeyDown:ln,onEscapeKeyDown:X=>{ke.isPending&&X.preventDefault()},onPointerDownOutside:X=>{if(ke.isPending){X.preventDefault();return}const Ge=X.detail.originalEvent.target;Ge!=null&&Ge.closest("[data-radix-popper-content-wrapper]")&&X.preventDefault()},children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(Ht,{open:pe,onOpenChange:Le,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:O("px-1.5 py-0.5 rounded text-xs font-semibold cursor-pointer hover:opacity-80 transition-opacity",!(de!=null&&de.brandColor)&&"bg-muted"),style:de!=null&&de.brandColor?{backgroundColor:de.brandColor,color:gh(de.brandColor)}:void 0,children:((de==null?void 0:de.name)??"").slice(0,3).toUpperCase()})}),e.jsx(Qt,{className:"w-48 p-1",align:"start",children:r.filter(X=>X.status!=="archived").map(X=>e.jsxs("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",X.id===Y&&"bg-accent"),onClick:()=>{Ue(X.id),Le(!1)},children:[e.jsx("span",{className:O("px-1 py-0.5 rounded text-[10px] font-semibold leading-none",!X.brandColor&&"bg-muted"),style:X.brandColor?{backgroundColor:X.brandColor,color:gh(X.brandColor)}:void 0,children:X.name.slice(0,3).toUpperCase()}),e.jsx("span",{className:"truncate",children:X.name})]},X.id))})]}),e.jsx("span",{className:"text-muted-foreground/60",children:"›"}),e.jsx("span",{children:"New issue"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>A(!F),disabled:ke.isPending,children:F?e.jsx(Rp,{className:"h-3.5 w-3.5"}):e.jsx(Pp,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>s(),disabled:ke.isPending,children:e.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),e.jsx("div",{className:"px-4 pt-4 pb-2 shrink-0",children:e.jsx("textarea",{className:"w-full text-lg font-semibold bg-transparent outline-none resize-none overflow-hidden placeholder:text-muted-foreground/50",placeholder:"Issue title",rows:1,value:u,onChange:X=>{d(X.target.value),X.target.style.height="auto",X.target.style.height=`${X.target.scrollHeight}px`},readOnly:ke.isPending,onKeyDown:X=>{var Ge,tt,Ct,Dn;X.key==="Enter"&&!X.metaKey&&!X.ctrlKey&&!X.nativeEvent.isComposing&&(X.preventDefault(),(Ge=q.current)==null||Ge.focus()),X.key==="Tab"&&!X.shiftKey&&(X.preventDefault(),b?y?(tt=q.current)==null||tt.focus():(Ct=Ie.current)==null||Ct.focus():(Dn=ie.current)==null||Dn.focus())},autoFocus:!0})}),e.jsx("div",{className:"px-4 pb-2 shrink-0",children:e.jsx("div",{className:"overflow-x-auto overscroll-x-contain",children:e.jsxs("div",{className:"inline-flex items-center gap-2 text-sm text-muted-foreground flex-wrap sm:flex-nowrap sm:min-w-max",children:[e.jsx("span",{children:"For"}),e.jsx(ba,{ref:ie,value:b,options:bt,placeholder:"Assignee",disablePortal:!0,noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:X=>{const Ge=Vl(X);Ge.assigneeAgentId&&Xd(Ge.assigneeAgentId),g(X)},onConfirm:()=>{var X,Ge;y?(X=q.current)==null||X.focus():(Ge=Ie.current)==null||Ge.focus()},renderTriggerValue:X=>X?gn?e.jsxs(e.Fragment,{children:[e.jsx(Cn,{icon:gn.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:X.label})]}):e.jsx("span",{className:"truncate",children:X.label}):e.jsx("span",{className:"text-muted-foreground",children:"Assignee"}),renderOption:X=>{if(!X.id)return e.jsx("span",{className:"truncate",children:X.label});const Ge=Vl(X.id).assigneeAgentId?(ue??[]).find(tt=>tt.id===Vl(X.id).assigneeAgentId):null;return e.jsxs(e.Fragment,{children:[Ge?e.jsx(Cn,{icon:Ge.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,e.jsx("span",{className:"truncate",children:X.label})]})}}),e.jsx("span",{children:"in"}),e.jsx(ba,{ref:Ie,value:y,options:Gt,placeholder:"Project",disablePortal:!0,noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:qs,onConfirm:()=>{var X;(X=q.current)==null||X.focus()},renderTriggerValue:X=>X&&$n?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:$n.color??"#6366f1"}}),e.jsx("span",{className:"truncate",children:X.label})]}):e.jsx("span",{className:"text-muted-foreground",children:"Project"}),renderOption:X=>{if(!X.id)return e.jsx("span",{className:"truncate",children:X.label});const Ge=ye.find(tt=>tt.id===X.id);return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:(Ge==null?void 0:Ge.color)??"#6366f1"}}),e.jsx("span",{className:"truncate",children:X.label})]})}})]})})}),$n&&te&&e.jsx("div",{className:"px-4 py-3 shrink-0 space-y-2",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium",children:"Execution workspace"}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Control whether this issue runs in the shared workspace, a new isolated workspace, or an existing one."}),e.jsx("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:K,onChange:X=>{T(X.target.value),X.target.value!=="reuse_existing"&&w("")},children:D3.map(X=>e.jsx("option",{value:X.value,children:X.label},X.value))}),K==="reuse_existing"&&e.jsxs("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:z,onChange:X=>w(X.target.value),children:[e.jsx("option",{value:"",children:"Choose an existing workspace"}),Ae.map(X=>e.jsxs("option",{value:X.id,children:[X.name," · ",X.status," · ",X.branchName??X.cwd??X.id.slice(0,8)]},X.id))]}),K==="reuse_existing"&&Je&&e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Reusing ",Je.name," from ",Je.branchName??Je.cwd??"existing execution workspace","."]})]})}),Te&&e.jsxs("div",{className:"px-4 pb-2 shrink-0",children:[e.jsxs("button",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors",onClick:()=>M(X=>!X),children:[S?e.jsx(rn,{className:"h-3 w-3"}):e.jsx(sn,{className:"h-3 w-3"}),ft]}),S&&e.jsxs("div",{className:"mt-2 rounded-md border border-border p-3 bg-muted/20 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Model"}),e.jsx(ba,{value:B,options:ok,placeholder:"Default model",disablePortal:!0,noneLabel:"Default model",searchPlaceholder:"Search models...",emptyMessage:"No models found.",onChange:k})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Thinking effort"}),e.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:xn.map(X=>e.jsx("button",{className:O("px-2 py-1 rounded-md text-xs border border-border hover:bg-accent/50 transition-colors",L===X.value&&"bg-accent"),onClick:()=>$(X.value),children:X.label},X.value||"default"))})]}),ce==="claude_local"&&e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border px-2 py-1.5",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Enable Chrome (--chrome)"}),e.jsx("button",{"data-slot":"toggle",className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors",C?"bg-green-600":"bg-muted"),onClick:()=>I(X=>!X),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",C?"translate-x-4.5":"translate-x-0.5")})})]})]})]}),e.jsxs("div",{className:O("px-4 pb-2 overflow-y-auto min-h-0 border-t border-border/60 pt-3",F?"flex-1":""),onDragEnter:pn,onDragOver:re,onDragLeave:$e,onDrop:Ee,children:[e.jsx("div",{className:O("rounded-md transition-colors",Z&&"bg-accent/20"),children:e.jsx(ps,{ref:q,value:m,onChange:p,placeholder:"Add description...",bordered:!1,mentions:ae,contentClassName:O("text-sm text-muted-foreground pb-12",F?"min-h-[220px]":"min-h-[120px]"),imageUploadHandler:async X=>(await Xe.mutateAsync(X)).contentPath})}),H.length>0?e.jsxs("div",{className:"mt-4 space-y-3 rounded-lg border border-border/70 p-3",children:[qt.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Documents"}),e.jsx("div",{className:"space-y-2",children:qt.map(X=>e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"rounded-full border border-border px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:X.documentKey}),e.jsx("span",{className:"truncate text-sm",children:X.file.name})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx(Id,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:X.title||X.file.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Ch(X.file)})]})]}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"shrink-0 text-muted-foreground",onClick:()=>He(X.id),disabled:ke.isPending,title:"Remove document",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]},X.id))})]}):null,us.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Attachments"}),e.jsx("div",{className:"space-y-2",children:us.map(X=>e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ai,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate text-sm",children:X.file.name})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[X.file.type||"application/octet-stream"," • ",Ch(X.file)]})]}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"shrink-0 text-muted-foreground",onClick:()=>He(X.id),disabled:ke.isPending,title:"Remove attachment",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]},X.id))})]}):null]}):null]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap shrink-0",children:[e.jsxs(Ht,{open:fe,onOpenChange:Ce,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[e.jsx(rs,{className:O("h-3 w-3",xt.color)}),xt.label]})}),e.jsx(Qt,{className:"w-36 p-1",align:"start",children:Tu.map(X=>e.jsxs("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",X.value===x&&"bg-accent"),onClick:()=>{f(X.value),Ce(!1)},children:[e.jsx(rs,{className:O("h-3 w-3",X.color)}),X.label]},X.value))})]}),e.jsxs(Ht,{open:le,onOpenChange:Re,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:Pt?e.jsxs(e.Fragment,{children:[e.jsx(Pt.icon,{className:O("h-3 w-3",Pt.color)}),Pt.label]}):e.jsxs(e.Fragment,{children:[e.jsx(Ep,{className:"h-3 w-3 text-muted-foreground"}),"Priority"]})})}),e.jsx(Qt,{className:"w-36 p-1",align:"start",children:Sh.map(X=>e.jsxs("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",X.value===h&&"bg-accent"),onClick:()=>{j(X.value),Re(!1)},children:[e.jsx(X.icon,{className:O("h-3 w-3",X.color)}),X.label]},X.value))})]}),e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground",children:[e.jsx(Gb,{className:"h-3 w-3"}),"Labels"]}),e.jsx("input",{ref:D,type:"file",accept:_3,className:"hidden",onChange:hn,multiple:!0}),e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground",onClick:()=>{var X;return(X=D.current)==null?void 0:X.click()},disabled:ke.isPending,children:[e.jsx(ai,{className:"h-3 w-3"}),"Upload"]}),e.jsxs(Ht,{open:Pe,onOpenChange:Fe,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:"inline-flex items-center justify-center rounded-md border border-border p-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground",children:e.jsx(xi,{className:"h-3 w-3"})})}),e.jsxs(Qt,{className:"w-44 p-1",align:"start",children:[e.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",children:[e.jsx(Nc,{className:"h-3 w-3"}),"Start date"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",children:[e.jsx(Nc,{className:"h-3 w-3"}),"Due date"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-t border-border shrink-0",children:[e.jsx(G,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:pt,disabled:ke.isPending||!ki,children:"Discard Draft"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"min-h-5 text-right",children:ke.isPending?e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[e.jsx(kn,{className:"h-3 w-3 animate-spin"}),"Creating issue..."]}):ke.isError?e.jsx("span",{className:"text-xs text-destructive",children:Bl}):null}),e.jsx(G,{size:"sm",className:"min-w-[8.5rem] disabled:opacity-100",disabled:!u.trim()||ke.isPending,onClick:ht,"aria-busy":ke.isPending,children:e.jsxs("span",{className:"inline-flex items-center justify-center gap-1.5",children:[ke.isPending?e.jsx(kn,{className:"h-3.5 w-3.5 animate-spin"}):null,e.jsx("span",{children:ke.isPending?"Creating...":"Create Issue"})]})})]})]})]})})}const Zs={list:t=>ne.get(`/companies/${t}/goals`),get:t=>ne.get(`/goals/${t}`),create:(t,n)=>ne.post(`/companies/${t}/goals`,n),update:(t,n)=>ne.patch(`/goals/${t}`,n),remove:t=>ne.delete(`/goals/${t}`)};function Dt({status:t}){return e.jsx("span",{className:O("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",$0[t]??D0),children:t.replace("_"," ")})}const F3=[{id:"mac",label:"macOS",icon:x1},{id:"windows",label:"Windows",icon:f1},{id:"linux",label:"Linux",icon:kd}],q3={mac:{steps:["Open Finder and navigate to the folder.","Right-click (or Control-click) the folder.",'Hold the Option (⌥) key — "Copy" changes to "Copy as Pathname".','Click "Copy as Pathname", then paste here.'],tip:"You can also open Terminal, type cd, drag the folder into the terminal window, and press Enter. Then type pwd to see the full path."},windows:{steps:["Open File Explorer and navigate to the folder.","Click in the address bar at the top — the full path will appear.","Copy the path, then paste here."],tip:'Alternatively, hold Shift and right-click the folder, then select "Copy as path".'},linux:{steps:["Open a terminal and navigate to the directory with cd.","Run pwd to print the full path.","Copy the output and paste here."],tip:"In most file managers, Ctrl+L reveals the full path in the address bar."}};function U3(){const t=navigator.userAgent.toLowerCase();return t.includes("mac")?"mac":t.includes("win")?"windows":"linux"}function B3({open:t,onOpenChange:n}){const[s,r]=c.useState(U3),a=q3[s];return e.jsx(Cs,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(fa,{children:[e.jsx(ha,{className:"text-base",children:"How to get a full path"}),e.jsxs(ga,{children:["Paste the absolute path (e.g."," ",e.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded",children:"/Users/you/project"}),") into the input field."]})]}),e.jsx("div",{className:"flex gap-1 rounded-md border border-border p-0.5",children:F3.map(o=>e.jsxs("button",{type:"button",className:O("flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors",s===o.id?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground hover:bg-accent/50"),onClick:()=>r(o.id),children:[e.jsx(o.icon,{className:"h-3.5 w-3.5"}),o.label]},o.id))}),e.jsx("ol",{className:"space-y-2 text-sm",children:a.steps.map((o,i)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsxs("span",{className:"text-muted-foreground font-mono text-xs mt-0.5 shrink-0",children:[i+1,"."]}),e.jsx("span",{children:o})]},i))}),a.tip&&e.jsx("p",{className:"text-xs text-muted-foreground border-l-2 border-border pl-3",children:a.tip})]})})}function pr({className:t}){const[n,s]=c.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:O("inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0",t),onClick:()=>s(!0),children:"Choose"}),e.jsx(B3,{open:n,onOpenChange:s})]})}const K3=[{value:"backlog",label:"Backlog"},{value:"planned",label:"Planned"},{value:"in_progress",label:"In Progress"},{value:"completed",label:"Completed"},{value:"cancelled",label:"Cancelled"}];function z3(){const{newProjectOpen:t,closeNewProject:n}=In(),{selectedCompanyId:s,selectedCompany:r}=et(),a=at(),[o,i]=c.useState(""),[l,u]=c.useState(""),[d,m]=c.useState("planned"),[p,x]=c.useState([]),[f,h]=c.useState(""),[j,b]=c.useState(!1),[g,y]=c.useState(""),[v,_]=c.useState(""),[E,S]=c.useState(null),[M,B]=c.useState(!1),[k,L]=c.useState(!1),$=c.useRef(null),{data:C}=oe({queryKey:N.goals.list(s),queryFn:()=>Zs.list(s),enabled:!!s&&t}),{data:I}=oe({queryKey:N.agents.list(s),queryFn:()=>We.list(s),enabled:!!s&&t}),K=c.useMemo(()=>{const W=[],J=[...I??[]].filter(Y=>Y.status!=="terminated").sort((Y,de)=>Y.name.localeCompare(de.name));for(const Y of J)W.push({id:`agent:${Y.id}`,name:Y.name,kind:"agent",agentId:Y.id,agentIcon:Y.icon});return W},[I]),T=ge({mutationFn:W=>en.create(s,W)}),z=ge({mutationFn:async W=>{if(!s)throw new Error("No company selected");return Aa.uploadImage(s,W,"projects/drafts")}});function w(){i(""),u(""),m("planned"),x([]),h(""),b(!1),y(""),_(""),S(null)}const F=W=>W.startsWith("/")||/^[A-Za-z]:[\\/]/.test(W),A=W=>{try{const J=new URL(W),Y=J.hostname.toLowerCase();return Y!=="github.com"&&Y!=="www.github.com"?!1:J.pathname.split("/").filter(Boolean).length>=2}catch{return!1}},R=W=>{const Y=W.trim().replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return Y[Y.length-1]??"Local folder"},Q=W=>{var J;try{const de=new URL(W).pathname.split("/").filter(Boolean);return(((J=de[de.length-1])==null?void 0:J.replace(/\.git$/i,""))??"")||"GitHub repo"}catch{return"GitHub repo"}};async function H(){if(!s||!o.trim())return;const W=g.trim(),J=v.trim();if(W&&!F(W)){S("Local folder must be a full absolute path.");return}if(J&&!A(J)){S("Repo must use a valid GitHub repo URL.");return}S(null);try{const Y=await T.mutateAsync({name:o.trim(),description:l.trim()||void 0,status:d,color:Cm[Math.floor(Math.random()*Cm.length)],...p.length>0?{goalIds:p}:{},...f?{targetDate:f}:{}});if(W||J){const de={name:W?R(W):Q(J),...W?{cwd:W}:{},...J?{repoUrl:J}:{}};await en.createWorkspace(Y.id,de)}a.invalidateQueries({queryKey:N.projects.list(s)}),a.invalidateQueries({queryKey:N.projects.detail(Y.id)}),w(),n()}catch{}}function U(W){W.key==="Enter"&&(W.metaKey||W.ctrlKey)&&(W.preventDefault(),H())}const Z=(C??[]).filter(W=>p.includes(W.id)),V=(C??[]).filter(W=>!p.includes(W.id));return e.jsx(Cs,{open:t,onOpenChange:W=>{W||(w(),n())},children:e.jsxs(Fs,{showCloseButton:!1,className:O("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:U,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[r&&e.jsx("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:r.name.slice(0,3).toUpperCase()}),e.jsx("span",{className:"text-muted-foreground/60",children:"›"}),e.jsx("span",{children:"New project"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>b(!j),children:j?e.jsx(Rp,{className:"h-3.5 w-3.5"}):e.jsx(Pp,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{w(),n()},children:e.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),e.jsx("div",{className:"px-4 pt-4 pb-2 shrink-0",children:e.jsx("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Project name",value:o,onChange:W=>i(W.target.value),onKeyDown:W=>{var J;W.key==="Tab"&&!W.shiftKey&&(W.preventDefault(),(J=$.current)==null||J.focus())},autoFocus:!0})}),e.jsx("div",{className:"px-4 pb-2",children:e.jsx(ps,{ref:$,value:l,onChange:u,placeholder:"Add description...",bordered:!1,mentions:K,contentClassName:O("text-sm text-muted-foreground",j?"min-h-[220px]":"min-h-[120px]"),imageUploadHandler:async W=>(await z.mutateAsync(W)).contentPath})}),e.jsxs("div",{className:"px-4 pt-3 pb-3 space-y-3 border-t border-border",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5",children:[e.jsx("label",{className:"block text-xs text-muted-foreground",children:"Repo URL"}),e.jsx("span",{className:"text-xs text-muted-foreground/50",children:"optional"}),e.jsxs(Jn,{delayDuration:300,children:[e.jsx(Zn,{asChild:!0,children:e.jsx(zo,{className:"h-3 w-3 text-muted-foreground/50 cursor-help"})}),e.jsx(Yn,{side:"top",className:"max-w-[240px] text-xs",children:"Link a GitHub repository so agents can clone, read, and push code for this project."})]})]}),e.jsx("input",{className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs outline-none",value:v,onChange:W=>{_(W.target.value),S(null)},placeholder:"https://github.com/org/repo"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5",children:[e.jsx("label",{className:"block text-xs text-muted-foreground",children:"Local folder"}),e.jsx("span",{className:"text-xs text-muted-foreground/50",children:"optional"}),e.jsxs(Jn,{delayDuration:300,children:[e.jsx(Zn,{asChild:!0,children:e.jsx(zo,{className:"h-3 w-3 text-muted-foreground/50 cursor-help"})}),e.jsx(Yn,{side:"top",className:"max-w-[240px] text-xs",children:"Set an absolute path on this machine where local agents will read and write files for this project."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",value:g,onChange:W=>{y(W.target.value),S(null)},placeholder:"/absolute/path/to/workspace"}),e.jsx(pr,{})]})]}),E&&e.jsx("p",{className:"text-xs text-destructive",children:E})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[e.jsxs(Ht,{open:M,onOpenChange:B,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:e.jsx(Dt,{status:d})})}),e.jsx(Qt,{className:"w-40 p-1",align:"start",children:K3.map(W=>e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",W.value===d&&"bg-accent"),onClick:()=>{m(W.value),B(!1)},children:W.label},W.value))})]}),Z.map(W=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-xs",children:[e.jsx(Ir,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"max-w-[160px] truncate",children:W.title}),e.jsx("button",{className:"text-muted-foreground hover:text-foreground",onClick:()=>x(J=>J.filter(Y=>Y!==W.id)),"aria-label":`Remove goal ${W.title}`,type:"button",children:e.jsx(zt,{className:"h-3 w-3"})})]},W.id)),e.jsxs(Ht,{open:k,onOpenChange:L,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors disabled:opacity-60",disabled:Z.length>0&&V.length===0,children:[Z.length>0?e.jsx(Ot,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Ir,{className:"h-3 w-3 text-muted-foreground"}),Z.length>0?"+ Goal":"Goal"]})}),e.jsxs(Qt,{className:"w-56 p-1",align:"start",children:[Z.length===0&&e.jsx("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:()=>L(!1),children:"No goal"}),V.map(W=>e.jsx("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",onClick:()=>{x(J=>[...J,W.id]),L(!1)},children:W.title},W.id)),Z.length>0&&V.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All goals already selected."})]})]}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs",children:[e.jsx(Nc,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("input",{type:"date",className:"bg-transparent outline-none text-xs w-24",value:f,onChange:W=>h(W.target.value),placeholder:"Target date"})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-t border-border",children:[T.isError?e.jsx("p",{className:"text-xs text-destructive",children:"Failed to create project."}):e.jsx("span",{}),e.jsx(G,{size:"sm",disabled:!o.trim()||T.isPending,onClick:H,children:T.isPending?"Creating…":"Create project"})]})]})})}const Ih={company:"Company",team:"Team",agent:"Agent",task:"Task"};function W3(){const{newGoalOpen:t,newGoalDefaults:n,closeNewGoal:s}=In(),{selectedCompanyId:r,selectedCompany:a}=et(),o=at(),[i,l]=c.useState(""),[u,d]=c.useState(""),[m,p]=c.useState("planned"),[x,f]=c.useState("task"),[h,j]=c.useState(""),[b,g]=c.useState(!1),[y,v]=c.useState(!1),[_,E]=c.useState(!1),[S,M]=c.useState(!1),B=c.useRef(null),k=h||n.parentId||"",{data:L}=oe({queryKey:N.goals.list(r),queryFn:()=>Zs.list(r),enabled:!!r&&t}),$=ge({mutationFn:w=>Zs.create(r,w),onSuccess:()=>{o.invalidateQueries({queryKey:N.goals.list(r)}),I(),s()}}),C=ge({mutationFn:async w=>{if(!r)throw new Error("No company selected");return Aa.uploadImage(r,w,"goals/drafts")}});function I(){l(""),d(""),p("planned"),f("task"),j(""),g(!1)}function K(){!r||!i.trim()||$.mutate({title:i.trim(),description:u.trim()||void 0,status:m,level:x,...k?{parentId:k}:{}})}function T(w){w.key==="Enter"&&(w.metaKey||w.ctrlKey)&&(w.preventDefault(),K())}const z=(L??[]).find(w=>w.id===k);return e.jsx(Cs,{open:t,onOpenChange:w=>{w||(I(),s())},children:e.jsxs(Fs,{showCloseButton:!1,className:O("p-0 gap-0",b?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:T,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a&&e.jsx("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:a.name.slice(0,3).toUpperCase()}),e.jsx("span",{className:"text-muted-foreground/60",children:"›"}),e.jsx("span",{children:n.parentId?"New sub-goal":"New goal"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>g(!b),children:b?e.jsx(Rp,{className:"h-3.5 w-3.5"}):e.jsx(Pp,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{I(),s()},children:e.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),e.jsx("div",{className:"px-4 pt-4 pb-2 shrink-0",children:e.jsx("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:i,onChange:w=>l(w.target.value),onKeyDown:w=>{var F;w.key==="Tab"&&!w.shiftKey&&(w.preventDefault(),(F=B.current)==null||F.focus())},autoFocus:!0})}),e.jsx("div",{className:"px-4 pb-2",children:e.jsx(ps,{ref:B,value:u,onChange:d,placeholder:"Add description...",bordered:!1,contentClassName:O("text-sm text-muted-foreground",b?"min-h-[220px]":"min-h-[120px]"),imageUploadHandler:async w=>(await C.mutateAsync(w)).contentPath})}),e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[e.jsxs(Ht,{open:y,onOpenChange:v,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:e.jsx(Dt,{status:m})})}),e.jsx(Qt,{className:"w-40 p-1",align:"start",children:ix.map(w=>e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",w===m&&"bg-accent"),onClick:()=>{p(w),v(!1)},children:w},w))})]}),e.jsxs(Ht,{open:_,onOpenChange:E,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[e.jsx(Jb,{className:"h-3 w-3 text-muted-foreground"}),Ih[x]??x]})}),e.jsx(Qt,{className:"w-40 p-1",align:"start",children:ox.map(w=>e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",w===x&&"bg-accent"),onClick:()=>{f(w),E(!1)},children:Ih[w]??w},w))})]}),e.jsxs(Ht,{open:S,onOpenChange:M,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[e.jsx(Ir,{className:"h-3 w-3 text-muted-foreground"}),z?z.title:"Parent goal"]})}),e.jsxs(Qt,{className:"w-48 p-1",align:"start",children:[e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!k&&"bg-accent"),onClick:()=>{j(""),M(!1)},children:"No parent"}),(L??[]).map(w=>e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",w.id===k&&"bg-accent"),onClick:()=>{j(w.id),M(!1)},children:w.title},w.id))]})]})]}),e.jsx("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:e.jsx(G,{size:"sm",disabled:!i.trim()||$.isPending,onClick:K,children:$.isPending?"Creating…":n.parentId?"Create sub-goal":"Create goal"})})]})})}function Yc({className:t}){return e.jsxs(e.Fragment,{children:[e.jsx("img",{src:"/brands/opencode-logo-light-square.svg",alt:"OpenCode",className:O("dark:hidden",t)}),e.jsx("img",{src:"/brands/opencode-logo-dark-square.svg",alt:"OpenCode",className:O("hidden dark:block",t)})]})}function q0({className:t}){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:O(t),children:[e.jsx("line",{x1:"12",y1:"6",x2:"12",y2:"23"}),e.jsx("path",{d:"M12 8 C10 9 9.5 11 10.5 13 C11.5 15 10 17 12 18"}),e.jsx("path",{d:"M12 8 C14 9 14.5 11 13.5 13 C12.5 15 14 17 12 18"}),e.jsx("circle",{cx:"10",cy:"8",r:"0.8",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"14",cy:"8",r:"0.8",fill:"currentColor",stroke:"none"}),e.jsx("path",{d:"M12 6 L8 3 L6 5 L9 6",strokeWidth:"1.2"}),e.jsx("path",{d:"M12 6 L16 3 L18 5 L15 6",strokeWidth:"1.2"}),e.jsx("line",{x1:"7.5",y1:"4",x2:"7",y2:"5.2",strokeWidth:"1"}),e.jsx("line",{x1:"16.5",y1:"4",x2:"17",y2:"5.2",strokeWidth:"1"}),e.jsx("circle",{cx:"12",cy:"6.5",r:"1.2"})]})}const H3=[{value:"claude_local",label:"Claude Code",icon:xo,desc:"Local Claude agent",recommended:!0},{value:"codex_local",label:"Codex",icon:_p,desc:"Local Codex agent",recommended:!0},{value:"gemini_local",label:"Gemini CLI",icon:Sp,desc:"Local Gemini agent"},{value:"opencode_local",label:"OpenCode",icon:Yc,desc:"Local multi-provider agent"},{value:"hermes_local",label:"Hermes Agent",icon:q0,desc:"Local multi-provider agent"},{value:"pi_local",label:"Pi",icon:kd,desc:"Local Pi agent"},{value:"cursor",label:"Cursor",icon:Zb,desc:"Local Cursor agent"},{value:"openclaw_gateway",label:"OpenClaw Gateway",icon:ss,desc:"Invoke OpenClaw via gateway protocol"}];function V3(){const{newAgentOpen:t,closeNewAgent:n,openNewIssue:s}=In(),{selectedCompanyId:r}=et(),a=Sn(),[o,i]=c.useState(!1),{data:l}=oe({queryKey:N.agents.list(r),queryFn:()=>We.list(r),enabled:!!r&&t}),u=(l??[]).find(x=>x.role==="ceo");function d(){n(),s({assigneeAgentId:u==null?void 0:u.id,title:"Create a new agent",description:"(type in what kind of agent you want here)"})}function m(){i(!0)}function p(x){n(),i(!1),a(`/agents/new?adapterType=${encodeURIComponent(x)}`)}return e.jsx(Cs,{open:t,onOpenChange:x=>{x||(i(!1),n())},children:e.jsxs(Fs,{showCloseButton:!1,className:"sm:max-w-md p-0 gap-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Add a new agent"}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{i(!1),n()},children:e.jsx("span",{className:"text-lg leading-none",children:"×"})})]}),e.jsx("div",{className:"p-6 space-y-6",children:o?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",onClick:()=>i(!1),children:[e.jsx(fo,{className:"h-3.5 w-3.5"}),"Back"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose your adapter type for advanced setup."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:H3.map(x=>e.jsxs("button",{className:O("flex flex-col items-center gap-1.5 rounded-md border border-border p-3 text-xs transition-colors hover:bg-accent/50 relative"),onClick:()=>p(x.value),children:[x.recommended&&e.jsx("span",{className:"absolute -top-1.5 right-1.5 bg-green-500 text-white text-[9px] font-semibold px-1.5 py-0.5 rounded-full leading-none",children:"Recommended"}),e.jsx(x.icon,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:x.label}),e.jsx("span",{className:"text-muted-foreground text-[10px]",children:x.desc})]},x.value))})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-accent",children:e.jsx(xo,{className:"h-6 w-6 text-foreground"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We recommend letting your CEO handle agent setup — they know the org structure and can configure reporting, permissions, and adapters."})]}),e.jsxs(G,{className:"w-full",size:"lg",onClick:d,children:[e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Ask the CEO to create a new agent"]}),e.jsx("div",{className:"text-center",children:e.jsx("button",{className:"text-xs text-muted-foreground hover:text-foreground underline underline-offset-2 transition-colors",onClick:m,children:"I want advanced configuration myself"})})]})})]})})}const Q3={info:"border-sky-300 bg-sky-50 text-sky-900 dark:border-sky-500/25 dark:bg-sky-950/60 dark:text-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-500/25 dark:bg-emerald-950/60 dark:text-emerald-100",warn:"border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-500/25 dark:bg-amber-950/60 dark:text-amber-100",error:"border-red-300 bg-red-50 text-red-900 dark:border-red-500/30 dark:bg-red-950/60 dark:text-red-100"},G3={info:"bg-sky-500 dark:bg-sky-400",success:"bg-emerald-500 dark:bg-emerald-400",warn:"bg-amber-500 dark:bg-amber-400",error:"bg-red-500 dark:bg-red-400"};function J3({toast:t,onDismiss:n}){const[s,r]=c.useState(!1);return c.useEffect(()=>{const a=requestAnimationFrame(()=>r(!0));return()=>cancelAnimationFrame(a)},[]),e.jsx("li",{className:O("pointer-events-auto rounded-sm border shadow-lg backdrop-blur-xl transition-[transform,opacity] duration-200 ease-out",s?"translate-y-0 opacity-100":"translate-y-3 opacity-0",Q3[t.tone]),children:e.jsxs("div",{className:"flex items-start gap-3 px-3 py-2.5",children:[e.jsx("span",{className:O("mt-1 h-2 w-2 shrink-0 rounded-full",G3[t.tone])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold leading-5",children:t.title}),t.body&&e.jsx("p",{className:"mt-1 text-xs leading-4 opacity-70",children:t.body}),t.action&&e.jsx(Oe,{to:t.action.href,onClick:()=>n(t.id),className:"mt-2 inline-flex text-xs font-medium underline underline-offset-4 hover:opacity-90",children:t.action.label})]}),e.jsx("button",{type:"button","aria-label":"Dismiss notification",onClick:()=>n(t.id),className:"mt-0.5 shrink-0 rounded p-1 opacity-50 hover:bg-black/10 hover:opacity-100 dark:hover:bg-white/10",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]})})}function Z3(){const{toasts:t,dismissToast:n}=ds();return t.length===0?null:e.jsx("aside",{"aria-live":"polite","aria-atomic":"false",className:"pointer-events-none fixed bottom-3 left-3 z-[120] w-full max-w-sm px-1",children:e.jsx("ol",{className:"flex w-full flex-col-reverse gap-2",children:t.map(s=>e.jsx(J3,{toast:s,onDismiss:n},s.id))})})}function Y3({visible:t}){const n=fn(),{selectedCompanyId:s}=et(),{openNewIssue:r}=In(),a=i0(s),o=c.useMemo(()=>[{type:"link",to:"/dashboard",label:"Home",icon:h1},{type:"link",to:"/issues",label:"Issues",icon:rs},{type:"action",label:"New Task",icon:Ap,onClick:()=>r()},{type:"link",to:"/agents/all",label:"Agents",icon:Mp},{type:"link",to:"/inbox",label:"Inbox",icon:Ga,badge:a.inbox}],[r,a.inbox]);return e.jsx("nav",{className:O("fixed bottom-0 left-0 right-0 z-30 border-t border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85 transition-transform duration-200 ease-out md:hidden pb-[env(safe-area-inset-bottom)]",t?"translate-y-0":"translate-y-full"),"aria-label":"Mobile navigation",children:e.jsx("div",{className:"grid h-16 grid-cols-5 px-1",children:o.map(i=>{if(i.type==="action"){const u=i.icon,d=/\/issues\/new(?:\/|$)/.test(n.pathname);return e.jsxs("button",{type:"button",onClick:i.onClick,className:O("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-[10px] font-medium transition-colors",d?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[e.jsx(u,{className:"h-[18px] w-[18px]"}),e.jsx("span",{className:"truncate",children:i.label})]},i.label)}const l=i.icon;return e.jsx(Cl,{to:i.to,className:({isActive:u})=>O("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-[10px] font-medium transition-colors",u?"text-foreground":"text-muted-foreground hover:text-foreground"),children:({isActive:u})=>e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"relative",children:[e.jsx(l,{className:O("h-[18px] w-[18px]",u&&"stroke-[2.3]")}),i.badge!=null&&i.badge>0&&e.jsx("span",{className:"absolute -right-2 -top-2 rounded-full bg-primary px-1.5 py-0.5 text-[10px] leading-none text-primary-foreground",children:i.badge>99?"99+":i.badge})]}),e.jsx("span",{className:"truncate",children:i.label})]})},i.label)})})})}function Ql(t){var r;if(typeof document>"u")return null;const n=document.querySelector(`meta[name="${t}"]`),s=(r=n==null?void 0:n.getAttribute("content"))==null?void 0:r.trim();return s||null}function Zm(t){if(!t)return null;const n=t.startsWith("#")?t.slice(1):t;return/^[0-9a-fA-F]{3}$/.test(n)?`#${n.split("").map(s=>`${s}${s}`).join("").toLowerCase()}`:/^[0-9a-fA-F]{6}$/.test(n)?`#${n.toLowerCase()}`:null}function X3(t){const n=Zm(t)??"#000000";return{r:Number.parseInt(n.slice(1,3),16),g:Number.parseInt(n.slice(3,5),16),b:Number.parseInt(n.slice(5,7),16)}}function Ru(t){const n=t/255;return n<=.03928?n/12.92:((n+.055)/1.055)**2.4}function eP(t){const{r:n,g:s,b:r}=X3(t),a=.2126*Ru(n)+.7152*Ru(s)+.0722*Ru(r),o=1.05/(a+.05),i=(a+.05)/.05;return o>=i?"#f8fafc":"#111827"}function tP(){if(Ql("crewspace-worktree-enabled")!=="true")return null;const t=Ql("crewspace-worktree-name"),n=Zm(Ql("crewspace-worktree-color"));return!t||!n?null:{enabled:!0,name:t,color:n,textColor:Zm(Ql("crewspace-worktree-text-color"))??eP(n)}}function nP(){const t=tP();return t?e.jsx("div",{className:"relative overflow-hidden border-b px-3 py-1.5 text-[11px] font-medium tracking-[0.2em] uppercase",style:{backgroundColor:t.color,color:t.textColor,borderColor:`${t.textColor}22`,boxShadow:`inset 0 -1px 0 ${t.textColor}18`,backgroundImage:`linear-gradient(90deg, ${t.textColor}14, transparent 28%, transparent 72%, ${t.textColor}12), repeating-linear-gradient(135deg, transparent 0 10px, ${t.textColor}08 10px 20px)`},children:e.jsxs("div",{className:"flex items-center gap-2 overflow-hidden whitespace-nowrap",children:[e.jsx("span",{className:"shrink-0 opacity-70",children:"Worktree"}),e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-70","aria-hidden":"true"}),e.jsx("span",{className:"truncate font-semibold tracking-[0.12em]",children:t.name})]})}):null}function sP(t){if(!t)return null;const n=new Date(t).getTime();if(Number.isNaN(n))return null;const s=Date.now()-n;if(s<6e4)return"just now";const r=Math.round(s/6e4);if(r<60)return`${r}m ago`;const a=Math.round(r/60);return a<24?`${a}h ago`:`${Math.round(a/24)}d ago`}function rP(t){return t.reason==="backend_changes_and_pending_migrations"?"backend files changed and migrations are pending":t.reason==="pending_migrations"?"pending migrations need a fresh boot":"backend files changed since this server booted"}function aP({devServer:t}){if(!(t!=null&&t.enabled)||!t.restartRequired)return null;const n=sP(t.lastChangedAt),s=t.changedPathsSample.slice(0,3);return e.jsx("div",{className:"border-b border-amber-300/60 bg-amber-50 text-amber-950 dark:border-amber-500/25 dark:bg-amber-500/10 dark:text-amber-100",children:e.jsxs("div",{className:"flex flex-col gap-3 px-3 py-2.5 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[12px] font-semibold uppercase tracking-[0.18em]",children:[e.jsx(ir,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:"Restart Required"}),t.autoRestartEnabled?e.jsx("span",{className:"rounded-full bg-amber-900/10 px-2 py-0.5 text-[10px] tracking-[0.14em] dark:bg-amber-100/10",children:"Auto-Restart On"}):null]}),e.jsxs("p",{className:"mt-1 text-sm",children:[rP(t),n?` · updated ${n}`:""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-amber-900/80 dark:text-amber-100/75",children:[s.length>0?e.jsxs("span",{children:["Changed: ",s.join(", "),t.changedPathCount>s.length?` +${t.changedPathCount-s.length} more`:""]}):null,t.pendingMigrations.length>0?e.jsxs("span",{children:["Pending migrations: ",t.pendingMigrations.slice(0,2).join(", "),t.pendingMigrations.length>2?` +${t.pendingMigrations.length-2} more`:""]}):null]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2 text-xs font-medium",children:t.waitingForIdle?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[e.jsx(g1,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:["Waiting for ",t.activeRunCount," live run",t.activeRunCount===1?"":"s"," to finish"]})]}):t.autoRestartEnabled?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Auto-restart will trigger when the instance is idle"})]}):e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:["Restart ",e.jsx("code",{children:"pnpm dev:once"})," after the active work is safe to interrupt"]})]})})]})})}const oP="crewspace.theme",iP="#18181b",lP="#ffffff",U0=c.createContext(void 0);function cP(){return typeof document>"u"||document.documentElement.classList.contains("dark")?"dark":"light"}function dP(t){if(typeof document>"u")return;const n=t==="dark",s=document.documentElement;s.classList.toggle("dark",n),s.style.colorScheme=n?"dark":"light";const r=document.querySelector('meta[name="theme-color"]');r instanceof HTMLMetaElement&&r.setAttribute("content",n?iP:lP)}function uP({children:t}){const[n,s]=c.useState(()=>cP()),r=c.useCallback(i=>{s(i)},[]),a=c.useCallback(()=>{s(i=>i==="dark"?"light":"dark")},[]);c.useEffect(()=>{dP(n);try{localStorage.setItem(oP,n)}catch{}},[n]);const o=c.useMemo(()=>({theme:n,setTheme:r,toggleTheme:a}),[n,r,a]);return e.jsx(U0.Provider,{value:o,children:t})}function B0(){const t=c.useContext(U0);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}function mP({onNewIssue:t,onToggleSidebar:n,onTogglePanel:s}){c.useEffect(()=>{function r(a){const o=a.target;o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable||(a.key==="c"&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&(a.preventDefault(),t==null||t()),a.key==="["&&!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),n==null||n()),a.key==="]"&&!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),s==null||s()))}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,n,s])}const pP=new Set(["auth","invite","board-claim","cli-auth","docs"]);function K0(t){const s=(t.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[r]=s;return!pP.has(r)}function xP(t){const n=va(t.companyPrefix);return t.companies.find(s=>va(s.issuePrefix)===n)??null}function fP(t){var s;const n=qp(t.pathname);return n?((s=xP({companies:t.companies,companyPrefix:n}))==null?void 0:s.id)??null:t.fallbackCompanyId}function hP(t){const n=t.path?Up(t.path):"/dashboard";if(!K0(n))return"/dashboard";const r=(n.split("?")[0]??"").split("/").filter(Boolean),[a,o]=r;if(a==="issues"&&o){const i=/^([A-Za-z]+)-\d+$/.exec(o);if(i&&va(i[1]??"")!==va(t.companyPrefix))return"/dashboard"}return n}const z0="crewspace.companyPaths";function W0(){try{const t=localStorage.getItem(z0);if(t)return JSON.parse(t)}catch{}return{}}function gP(t,n){const s=W0();s[t]=n,localStorage.setItem(z0,JSON.stringify(s))}function bP(){const{companies:t,selectedCompanyId:n,selectedCompany:s,selectionSource:r}=et(),a=fn(),o=Sn(),i=c.useRef(n),l=c.useMemo(()=>fP({companies:t,pathname:a.pathname,fallbackCompanyId:i.current}),[t,a.pathname]),u=a.pathname+a.search;c.useEffect(()=>{const d=l,m=Up(u);d&&K0(m)&&gP(d,m)},[u,l]),c.useEffect(()=>{if(n){if(i.current!==null&&n!==i.current&&r!=="route_sync"&&s){const d=W0(),m=hP({path:d[n],companyPrefix:s.issuePrefix});o(`/${s.issuePrefix}${m}`,{replace:!0})}i.current=n}},[s,n,r,o])}const Kx={get:async()=>{const t=await fetch("/api/health",{credentials:"include",headers:{Accept:"application/json"}});if(!t.ok){const n=await t.json().catch(()=>null);throw new Error((n==null?void 0:n.error)??`Failed to load health (${t.status})`)}return t.json()}};function yP(t){const{selectionSource:n,selectedCompanyId:s,routeCompanyId:r}=t;return!(s===r||n==="manual"&&s)}const Xc="/instance/settings/general";function H0(t){if(!t)return Xc;const n=t.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/),s=(n==null?void 0:n[1])??t,r=(n==null?void 0:n[2])??"",a=(n==null?void 0:n[3])??"";return s==="/instance/settings/general"||s==="/instance/settings/heartbeats"||s==="/instance/settings/plugins"||s==="/instance/settings/experimental"?`${s}${r}${a}`:/^\/instance\/settings\/plugins\/[^/?#]+$/.test(s)?`${s}${r}${a}`:Xc}function pl({scope:t="global",requestedPrefix:n}){const s=fn(),{setBreadcrumbs:r}=Ft(),{companies:a,selectedCompany:o}=et();c.useEffect(()=>{r([{label:"Not Found"}])},[r]);const i=o??a[0]??null,l=i?`/${i.issuePrefix}/dashboard`:"/",u=`${s.pathname}${s.search}${s.hash}`,d=n==null?void 0:n.toUpperCase(),m=t==="invalid_company_prefix"?"Company not found":"Page not found",p=t==="invalid_company_prefix"?`No company matches prefix "${d??"unknown"}".`:"This route does not exist.";return e.jsx("div",{className:"mx-auto max-w-2xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:e.jsx(ir,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold",children:m}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p})]})]}),e.jsxs("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",e.jsx("code",{className:"font-mono",children:u})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(G,{asChild:!0,children:e.jsxs(Oe,{to:l,children:[e.jsx(b1,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),e.jsx(G,{variant:"outline",asChild:!0,children:e.jsx(Oe,{to:"/",children:"Go home"})})]})]})})}const V0="crewspace.lastInstanceSettingsPath";function vP(t){return/\/(memory|agent-chat|office)$/.test(t)}function jP(){if(typeof window>"u")return Xc;try{return H0(window.localStorage.getItem(V0))}catch{return Xc}}function _h(){const{sidebarOpen:t,setSidebarOpen:n,toggleSidebar:s,isMobile:r}=mr(),{openNewIssue:a,openOnboarding:o}=In(),{togglePanelVisible:i}=ji(),{companies:l,loading:u,selectedCompany:d,selectedCompanyId:m,selectionSource:p,setSelectedCompanyId:x}=et(),{theme:f,toggleTheme:h}=B0(),{companyPrefix:j}=Xn(),b=Sn(),g=fn(),y=g.pathname.startsWith("/instance/"),v=c.useRef(!1),_=c.useRef(0),[E,S]=c.useState(!0),[M,B]=c.useState(()=>jP()),k=f==="dark"?"light":"dark",L=c.useMemo(()=>{if(!j)return null;const T=j.toUpperCase();return l.find(z=>z.issuePrefix.toUpperCase()===T)??null},[l,j]),$=!!j&&!u&&l.length>0&&!L,{data:C}=oe({queryKey:N.health,queryFn:()=>Kx.get(),retry:!1,refetchInterval:T=>{var w;const z=T.state.data;return(w=z==null?void 0:z.devServer)!=null&&w.enabled?2e3:!1},refetchIntervalInBackground:!0});c.useEffect(()=>{u||v.current||(C==null?void 0:C.deploymentMode)!=="authenticated"&&l.length===0&&(v.current=!0,o())},[l,u,o,C==null?void 0:C.deploymentMode]),c.useEffect(()=>{if(!(!j||u||l.length===0)){if(!L){const T=(m?l.find(z=>z.id===m):null)??l[0]??null;T&&m!==T.id&&x(T.id,{source:"route_sync"});return}if(j!==L.issuePrefix){const T=g.pathname.replace(/^\/[^/]+/,"");b(`/${L.issuePrefix}${T}${g.search}`,{replace:!0});return}yP({selectionSource:p,selectedCompanyId:m,routeCompanyId:L.id})&&x(L.id,{source:"route_sync"})}},[j,l,u,L,g.pathname,g.search,b,p,m,x]);const I=i;bP(),mP({onNewIssue:()=>a(),onToggleSidebar:s,onTogglePanel:I}),c.useEffect(()=>{if(!r){S(!0);return}_.current=0,S(!0)},[r]),c.useEffect(()=>{if(!r)return;const T=30,z=50,w=75;let F=0,A=0;const R=H=>{const U=H.touches[0];F=U.clientX,A=U.clientY},Q=H=>{const U=H.changedTouches[0],Z=U.clientX-F;if(!(Math.abs(U.clientY-A)>w)){if(!t&&F<T&&Z>z){n(!0);return}t&&Z<-z&&n(!1)}};return document.addEventListener("touchstart",R,{passive:!0}),document.addEventListener("touchend",Q,{passive:!0}),()=>{document.removeEventListener("touchstart",R),document.removeEventListener("touchend",Q)}},[r,t,n]);const K=c.useCallback(T=>{const z=T-_.current;T<=24?S(!0):z>8?S(!1):z<-8&&S(!0),_.current=T},[]);return c.useEffect(()=>{if(!r){S(!0),_.current=0;return}const T=()=>{K(window.scrollY||document.documentElement.scrollTop||0)};return T(),window.addEventListener("scroll",T,{passive:!0}),()=>{window.removeEventListener("scroll",T)}},[r,K]),c.useEffect(()=>{const T=document.body.style.overflow;return document.body.style.overflow=r?"visible":"hidden",()=>{document.body.style.overflow=T}},[r]),c.useEffect(()=>{if(!g.pathname.startsWith("/instance/settings/"))return;const T=H0(`${g.pathname}${g.search}${g.hash}`);B(T);try{window.localStorage.setItem(V0,T)}catch{}},[g.hash,g.pathname,g.search]),e.jsx(LT,{children:e.jsxs("div",{className:O("bg-background text-foreground pt-[env(safe-area-inset-top)]",r?"min-h-dvh":"flex h-dvh flex-col overflow-hidden"),children:[e.jsx("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-[200] focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),e.jsx(nP,{}),e.jsx(aP,{devServer:C==null?void 0:C.devServer}),e.jsxs("div",{className:O("min-h-0 flex-1",r?"w-full":"flex overflow-hidden"),children:[r&&t&&e.jsx("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:()=>n(!1),"aria-label":"Close sidebar"}),r?e.jsxs("div",{className:O("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-[env(safe-area-inset-top)] transition-transform duration-100 ease-out",t?"translate-x-0":"-translate-x-full"),children:[e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[e.jsx(th,{}),y?e.jsx(mh,{}):e.jsx(uh,{})]}),e.jsx("div",{className:"border-t border-r border-border px-3 py-2 bg-background",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("a",{href:"https://docs.crewspace.ing/",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium transition-colors text-foreground/80 hover:bg-accent/50 hover:text-foreground flex-1 min-w-0",children:[e.jsx(ym,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:"Documentation"})]}),(C==null?void 0:C.version)&&e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("span",{className:"px-2 text-xs text-muted-foreground shrink-0 cursor-default",children:"v"})}),e.jsxs(Yn,{children:["v",C.version]})]}),e.jsx(G,{variant:"ghost",size:"icon-sm",className:"text-muted-foreground shrink-0",asChild:!0,children:e.jsx(Oe,{to:M,"aria-label":"Instance settings",title:"Instance settings",onClick:()=>{r&&n(!1)},children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsx(G,{type:"button",variant:"ghost",size:"icon-sm",className:"text-muted-foreground shrink-0",onClick:h,"aria-label":`Switch to ${k} mode`,title:`Switch to ${k} mode`,children:f==="dark"?e.jsx(jf,{className:"h-4 w-4"}):e.jsx(wf,{className:"h-4 w-4"})})]})})]}):e.jsxs("div",{className:"flex h-full flex-col shrink-0",children:[e.jsxs("div",{className:"flex flex-1 min-h-0",children:[e.jsx(th,{}),e.jsx("div",{className:O("overflow-hidden transition-[width] duration-100 ease-out",t?"w-60":"w-0"),children:y?e.jsx(mh,{}):e.jsx(uh,{})})]}),e.jsx("div",{className:"border-t border-r border-border px-3 py-2",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("a",{href:"https://docs.crewspace.ing/",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium transition-colors text-foreground/80 hover:bg-accent/50 hover:text-foreground flex-1 min-w-0",children:[e.jsx(ym,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:"Documentation"})]}),(C==null?void 0:C.version)&&e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("span",{className:"px-2 text-xs text-muted-foreground shrink-0 cursor-default",children:"v"})}),e.jsxs(Yn,{children:["v",C.version]})]}),e.jsx(G,{variant:"ghost",size:"icon-sm",className:"text-muted-foreground shrink-0",asChild:!0,children:e.jsx(Oe,{to:M,"aria-label":"Instance settings",title:"Instance settings",onClick:()=>{r&&n(!1)},children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsx(G,{type:"button",variant:"ghost",size:"icon-sm",className:"text-muted-foreground shrink-0",onClick:h,"aria-label":`Switch to ${k} mode`,title:`Switch to ${k} mode`,children:f==="dark"?e.jsx(jf,{className:"h-4 w-4"}):e.jsx(wf,{className:"h-4 w-4"})})]})})]}),e.jsxs("div",{className:O("flex min-w-0 flex-col",r?"w-full":"h-full flex-1"),children:[e.jsx("div",{className:O(r&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:e.jsx(bR,{})}),e.jsxs("div",{className:O(r?"block":"flex flex-1 min-h-0"),children:[e.jsx("main",{id:"main-content",tabIndex:-1,className:O("flex-1",vP(g.pathname)?"relative min-h-0 overflow-hidden":O("p-4 md:p-6",r?"overflow-visible pb-[calc(5rem+env(safe-area-inset-bottom))]":"overflow-auto")),children:$?e.jsx(pl,{scope:"invalid_company_prefix",requestedPrefix:j??(d==null?void 0:d.issuePrefix)}):e.jsx(Rb,{})}),e.jsx(wR,{})]})]})]}),r&&e.jsx(Y3,{visible:E}),e.jsx(e3,{}),e.jsx(L3,{}),e.jsx(z3,{}),e.jsx(W3,{}),e.jsx(V3,{}),e.jsx(Z3,{})]})})}function sa(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Gl(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function wP(t){if(typeof t=="string")return t;const n=sa(t);if(!n)return"";const s=typeof n.message=="string"&&n.message||typeof n.error=="string"&&n.error||typeof n.code=="string"&&n.code||"";if(s)return s;try{return JSON.stringify(n)}catch{return""}}function NP(t){try{return JSON.parse(t)}catch{return null}}function kP(t,n){const s=sa(NP(t));if(!s)return[{kind:"stdout",ts:n,text:t}];const r=typeof s.type=="string"?s.type:"";if(r==="system"&&s.subtype==="init")return[{kind:"init",ts:n,model:typeof s.model=="string"?s.model:"unknown",sessionId:typeof s.session_id=="string"?s.session_id:""}];if(r==="assistant"){const a=sa(s.message)??{},o=Array.isArray(a.content)?a.content:[],i=[];for(const l of o){const u=sa(l);if(!u)continue;const d=typeof u.type=="string"?u.type:"";if(d==="text"){const m=typeof u.text=="string"?u.text:"";m&&i.push({kind:"assistant",ts:n,text:m})}else if(d==="thinking"){const m=typeof u.thinking=="string"?u.thinking:"";m&&i.push({kind:"thinking",ts:n,text:m})}else d==="tool_use"&&i.push({kind:"tool_call",ts:n,name:typeof u.name=="string"?u.name:"unknown",toolUseId:typeof u.id=="string"?u.id:typeof u.tool_use_id=="string"?u.tool_use_id:void 0,input:u.input??{}})}return i.length>0?i:[{kind:"stdout",ts:n,text:t}]}if(r==="user"){const a=sa(s.message)??{},o=Array.isArray(a.content)?a.content:[],i=[];for(const l of o){const u=sa(l);if(!u)continue;const d=typeof u.type=="string"?u.type:"";if(d==="text"){const m=typeof u.text=="string"?u.text:"";m&&i.push({kind:"user",ts:n,text:m})}else if(d==="tool_result"){const m=typeof u.tool_use_id=="string"?u.tool_use_id:"",p=u.is_error===!0;let x="";if(typeof u.content=="string")x=u.content;else if(Array.isArray(u.content)){const f=[];for(const h of u.content){const j=sa(h);j&&typeof j.text=="string"&&f.push(j.text)}x=f.join(`
|
|
36
|
+
`)}i.push({kind:"tool_result",ts:n,toolUseId:m,content:x,isError:p})}}if(i.length>0)return i}if(r==="result"){const a=sa(s.usage)??{},o=Gl(a.input_tokens),i=Gl(a.output_tokens),l=Gl(a.cache_read_input_tokens),u=Gl(s.total_cost_usd),d=typeof s.subtype=="string"?s.subtype:"",m=s.is_error===!0,p=Array.isArray(s.errors)?s.errors.map(wP).filter(Boolean):[],x=typeof s.result=="string"?s.result:"";return[{kind:"result",ts:n,text:x,inputTokens:o,outputTokens:i,cachedTokens:l,costUsd:u,subtype:d,isError:m,errors:p}]}return[{kind:"stdout",ts:n,text:t}]}function CP(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function SP(t){const n={};for(const s of t.split(/\r?\n/)){const r=s.trim();if(!r||r.startsWith("#"))continue;const a=r.indexOf("=");if(a<=0)continue;const o=r.slice(0,a).trim(),i=r.slice(a+1);/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&(n[o]=i)}return n}function IP(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const n={};for(const[s,r]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;if(typeof r=="string"){n[s]={type:"plain",value:r};continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;const a=r;if(a.type==="plain"&&typeof a.value=="string"){n[s]={type:"plain",value:a.value};continue}a.type==="secret_ref"&&typeof a.secretId=="string"&&(n[s]={type:"secret_ref",secretId:a.secretId,...typeof a.version=="number"||a.version==="latest"?{version:a.version}:{}})}return n}function _P(t){const n=t.trim();if(!n)return null;try{const s=JSON.parse(n);return typeof s!="object"||s===null||Array.isArray(s)?null:s}catch{return null}}function AP(t){const n={};t.cwd&&(n.cwd=t.cwd),t.instructionsFilePath&&(n.instructionsFilePath=t.instructionsFilePath),t.promptTemplate&&(n.promptTemplate=t.promptTemplate),t.bootstrapPrompt&&(n.bootstrapPromptTemplate=t.bootstrapPrompt),t.model&&(n.model=t.model),t.thinkingEffort&&(n.effort=t.thinkingEffort),t.chrome&&(n.chrome=!0),n.timeoutSec=0,n.graceSec=15;const s=IP(t.envBindings),r=SP(t.envVars);for(const[o,i]of Object.entries(r))Object.prototype.hasOwnProperty.call(s,o)||(s[o]={type:"plain",value:i});Object.keys(s).length>0&&(n.env=s),n.maxTurnsPerRun=t.maxTurnsPerRun,n.dangerouslySkipPermissions=t.dangerouslySkipPermissions,t.workspaceStrategyType==="git_worktree"&&(n.workspaceStrategy={type:"git_worktree",...t.workspaceBaseRef?{baseRef:t.workspaceBaseRef}:{},...t.workspaceBranchTemplate?{branchTemplate:t.workspaceBranchTemplate}:{},...t.worktreeParentDir?{worktreeParentDir:t.worktreeParentDir}:{}});const a=_P(t.runtimeServicesJson??"");return a&&Array.isArray(a.services)&&(n.workspaceRuntime=a),t.command&&(n.command=t.command),t.extraArgs&&(n.extraArgs=CP(t.extraArgs)),n}const Rt={name:"Display name for this agent.",title:"Job title shown in the org chart.",reportsTo:"The agent this one reports to in the org hierarchy.",capabilities:"Describes what this agent can do. Shown in the org chart and used for task routing.",adapterType:"How this agent runs: local CLI (Claude/Codex/OpenCode), OpenClaw Gateway, spawned process, or generic HTTP webhook.",cwd:"Deprecated legacy working directory fallback for local adapters. Existing agents may still carry this value, but new configurations should use project workspaces instead.",promptTemplate:"Sent on every heartbeat. Keep this small and dynamic. Use it for current-task framing, not large static instructions. Supports {{ agent.id }}, {{ agent.name }}, {{ agent.role }} and other template variables.",model:"Override the default model used by the adapter.",thinkingEffort:"Control model reasoning depth. Supported values vary by adapter/model.",chrome:"Enable Claude's Chrome integration by passing --chrome.",dangerouslySkipPermissions:"Run unattended by auto-approving adapter permission prompts when supported.",dangerouslyBypassSandbox:"Run Codex without sandbox restrictions. Required for filesystem/network access.",search:"Enable Codex web search capability during runs.",maxTurnsPerRun:"Maximum number of agentic turns (tool calls) per heartbeat run.",command:"The command to execute (e.g. node, python).",localCommand:"Override the path to the CLI command you want the adapter to call (e.g. /usr/local/bin/claude, codex, opencode).",args:"Command-line arguments, comma-separated.",extraArgs:"Extra CLI arguments for local adapters, comma-separated.",envVars:"Environment variables injected into the adapter process. Use plain values or secret references.",bootstrapPrompt:"Only sent when CrewSpace starts a fresh session. Use this for stable setup guidance that should not be repeated on every heartbeat.",payloadTemplateJson:"Optional JSON merged into remote adapter request payloads before CrewSpace adds its standard wake and workspace fields.",webhookUrl:"The URL that receives POST requests when the agent is invoked.",heartbeatInterval:"Run this agent automatically on a timer. Useful for periodic tasks like checking for new work.",intervalSec:"Seconds between automatic heartbeat invocations.",timeoutSec:"Maximum seconds a run can take before being terminated. 0 means no timeout.",graceSec:"Seconds to wait after sending interrupt before force-killing the process.",wakeOnDemand:"Allow this agent to be woken by assignments, API calls, UI actions, or automated systems.",cooldownSec:"Minimum seconds between consecutive heartbeat runs.",maxConcurrentRuns:"Maximum number of heartbeat runs that can execute simultaneously for this agent."},tu={claude_local:"Claude (local)",codex_local:"Codex (local)",gemini_local:"Gemini CLI (local)",opencode_local:"OpenCode (local)",openclaw_gateway:"OpenClaw Gateway",cursor:"Cursor (local)",hermes_local:"Hermes Agent",process:"Process",http:"HTTP"},ed=rx;function xl({text:t}){return e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex text-muted-foreground/50 hover:text-muted-foreground transition-colors",children:e.jsx(zo,{className:"h-3 w-3"})})}),e.jsx(Yn,{side:"top",className:"max-w-xs",children:t})]})}function ct({label:t,hint:n,children:s}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),n&&e.jsx(xl,{text:n})]}),s]})}function ao({label:t,hint:n,checked:s,onChange:r,toggleTestId:a}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t}),n&&e.jsx(xl,{text:n})]}),e.jsx("button",{"data-slot":"toggle","data-testid":a,type:"button",className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors",s?"bg-green-600":"bg-muted"),onClick:()=>r(!s),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",s?"translate-x-4.5":"translate-x-0.5")})})]})}function Ah({label:t,hint:n,checked:s,onCheckedChange:r,number:a,onNumberChange:o,numberLabel:i,numberHint:l,numberPrefix:u,showNumber:d}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t}),n&&e.jsx(xl,{text:n})]}),e.jsx("button",{"data-slot":"toggle",className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0",s?"bg-green-600":"bg-muted"),onClick:()=>r(!s),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",s?"translate-x-4.5":"translate-x-0.5")})})]}),d&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[u&&e.jsx("span",{children:u}),e.jsx("input",{type:"number",className:"w-16 rounded-md border border-border px-2 py-0.5 bg-transparent outline-none text-xs font-mono text-center",value:a,onChange:m=>o(Number(m.target.value))}),e.jsx("span",{children:i}),l&&e.jsx(xl,{text:l})]})]})}function EP({title:t,icon:n,open:s,onToggle:r,bordered:a,children:o}){return e.jsxs("div",{className:O(a&&"border-t border-border"),children:[e.jsxs("button",{className:"flex items-center gap-2 w-full px-4 py-2 text-xs font-medium text-muted-foreground hover:bg-accent/30 transition-colors",onClick:r,children:[s?e.jsx(rn,{className:"h-3 w-3"}):e.jsx(sn,{className:"h-3 w-3"}),n,t]}),s&&e.jsx("div",{className:"px-4 pb-3",children:o})]})}function nn({value:t,onCommit:n,immediate:s,className:r,...a}){const[o,i]=c.useState(t);return c.useEffect(()=>i(t),[t]),e.jsx("input",{className:r,value:o,onChange:l=>{i(l.target.value),s&&n(l.target.value)},onBlur:()=>{o!==t&&n(o)},...a})}function qi({value:t,onCommit:n,immediate:s,className:r,...a}){const[o,i]=c.useState(String(t));return c.useEffect(()=>i(String(t)),[t]),e.jsx("input",{type:"number",className:r,value:o,onChange:l=>{i(l.target.value),s&&n(Number(l.target.value)||0)},onBlur:()=>{const l=Number(o)||0;l!==t&&n(l)},...a})}function Q0(t){return null}const Ym="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",TP="Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the system prompt at runtime.";function RP({mode:t,isCreate:n,adapterType:s,values:r,set:a,config:o,eff:i,mark:l,models:u,hideInstructionsFile:d}){return e.jsxs(e.Fragment,{children:[!d&&e.jsx(ct,{label:"Agent instructions file",hint:TP,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{value:n?r.instructionsFilePath??"":i("adapterConfig","instructionsFilePath",String(o.instructionsFilePath??"")),onCommit:m=>n?a({instructionsFilePath:m}):l("adapterConfig","instructionsFilePath",m||void 0),immediate:!0,className:Ym,placeholder:"/absolute/path/to/AGENTS.md"}),e.jsx(pr,{})]})}),e.jsx(Q0,{isCreate:n,values:r,set:a,config:o,mark:l,eff:i,mode:t,adapterType:s,models:u})]})}function PP({isCreate:t,values:n,set:s,config:r,eff:a,mark:o}){return e.jsxs(e.Fragment,{children:[e.jsx(ao,{label:"Enable Chrome",hint:Rt.chrome,checked:t?n.chrome:a("adapterConfig","chrome",r.chrome===!0),onChange:i=>t?s({chrome:i}):o("adapterConfig","chrome",i)}),e.jsx(ao,{label:"Skip permissions",hint:Rt.dangerouslySkipPermissions,checked:t?n.dangerouslySkipPermissions:a("adapterConfig","dangerouslySkipPermissions",r.dangerouslySkipPermissions!==!1),onChange:i=>t?s({dangerouslySkipPermissions:i}):o("adapterConfig","dangerouslySkipPermissions",i)}),e.jsx(ct,{label:"Max turns per run",hint:Rt.maxTurnsPerRun,children:t?e.jsx("input",{type:"number",className:Ym,value:n.maxTurnsPerRun,onChange:i=>s({maxTurnsPerRun:Number(i.target.value)})}):e.jsx(qi,{value:a("adapterConfig","maxTurnsPerRun",Number(r.maxTurnsPerRun??300)),onCommit:i=>o("adapterConfig","maxTurnsPerRun",i||300),immediate:!0,className:Ym})})]})}const MP={type:"claude_local",label:"Claude Code (local)",parseStdoutLine:kP,ConfigFields:RP,buildAdapterConfig:AP};function $P(t){try{return JSON.parse(t)}catch{return null}}function qo(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function dn(t,n=""){return typeof t=="string"?t:n}function xr(t,n=0){return typeof t=="number"&&Number.isFinite(t)?t:n}function gc(t){if(typeof t=="string")return t;const n=qo(t);if(!n)return"";const s=typeof n.message=="string"&&n.message||typeof n.error=="string"&&n.error||typeof n.code=="string"&&n.code||"";if(s)return s;try{return JSON.stringify(n)}catch{return""}}function DP(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}function OP(t,n,s){const r=dn(t.id),a=dn(t.command),o=dn(t.status),i=typeof t.exit_code=="number"&&Number.isFinite(t.exit_code)?t.exit_code:null,l=a,u=dn(t.aggregated_output).replace(/\s+$/,"");if(s==="started")return[{kind:"tool_call",ts:n,name:"command_execution",toolUseId:r||a||"command_execution",input:{id:r,command:l}}];const d=[];l&&d.push(`command: ${l}`),o&&d.push(`status: ${o}`),i!==null&&d.push(`exit_code: ${i}`),u&&(d.length>0&&d.push(""),d.push(u));const m=i!==null&&i!==0||o==="failed"||o==="errored"||o==="error"||o==="cancelled";return[{kind:"tool_result",ts:n,toolUseId:r||a||"command_execution",content:d.join(`
|
|
37
|
+
`).trim()||"command completed",isError:m}]}function LP(t,n){const r=(Array.isArray(t.changes)?t.changes:[]).map(i=>qo(i)).filter(i=>!!i).map(i=>{const l=dn(i.kind,"update"),u=dn(i.path,"unknown");return`${l} ${u}`});if(r.length===0)return[{kind:"system",ts:n,text:"file changes applied"}];const a=r.slice(0,6).join(", "),o=r.length>6?` (+${r.length-6} more)`:"";return[{kind:"system",ts:n,text:`file changes: ${a}${o}`}]}function FP(t,n,s){const r=dn(t.type);if(r==="agent_message"){const l=dn(t.text);return l?[{kind:"assistant",ts:n,text:l}]:[]}if(r==="reasoning"){const l=dn(t.text);return l?[{kind:"thinking",ts:n,text:l}]:[{kind:"system",ts:n,text:s==="started"?"reasoning started":"reasoning completed"}]}if(r==="command_execution")return OP(t,n,s);if(r==="file_change"&&s==="completed")return LP(t,n);if(r==="tool_use")return[{kind:"tool_call",ts:n,name:dn(t.name,"unknown"),toolUseId:dn(t.id),input:t.input??{}}];if(r==="tool_result"&&s==="completed"){const l=dn(t.tool_use_id,dn(t.id)),u=dn(t.content)||dn(t.output)||dn(t.result)||DP(t.content??t.output??t.result),d=t.is_error===!0||dn(t.status)==="error";return[{kind:"tool_result",ts:n,toolUseId:l,content:u,isError:d}]}if(r==="error"&&s==="completed"){const l=gc(t.message??t.error??t);return[{kind:"stderr",ts:n,text:l||"error"}]}const a=dn(t.id),o=dn(t.status),i=[a?`id=${a}`:"",o?`status=${o}`:""].filter(Boolean).join(" ");return[{kind:"system",ts:n,text:`item ${s}: ${r||"unknown"}${i?` (${i})`:""}`}]}function qP(t,n){const s=qo($P(t));if(!s)return[{kind:"stdout",ts:n,text:t}];const r=dn(s.type);if(r==="thread.started"){const a=dn(s.thread_id);return[{kind:"init",ts:n,model:dn(s.model,"codex"),sessionId:a}]}if(r==="turn.started")return[{kind:"system",ts:n,text:"turn started"}];if(r==="item.started"||r==="item.completed"){const a=qo(s.item);return a?FP(a,n,r==="item.started"?"started":"completed"):[{kind:"system",ts:n,text:r.replace("."," ")}]}if(r==="turn.completed"){const a=qo(s.usage),o=xr(a==null?void 0:a.input_tokens),i=xr(a==null?void 0:a.output_tokens),l=xr(a==null?void 0:a.cached_input_tokens,xr(a==null?void 0:a.cache_read_input_tokens));return[{kind:"result",ts:n,text:dn(s.result),inputTokens:o,outputTokens:i,cachedTokens:l,costUsd:xr(s.total_cost_usd),subtype:dn(s.subtype),isError:s.is_error===!0,errors:Array.isArray(s.errors)?s.errors.map(gc).filter(Boolean):[]}]}if(r==="turn.failed"){const a=qo(s.usage),o=xr(a==null?void 0:a.input_tokens),i=xr(a==null?void 0:a.output_tokens),l=xr(a==null?void 0:a.cached_input_tokens,xr(a==null?void 0:a.cache_read_input_tokens)),u=gc(s.error??s.message);return[{kind:"result",ts:n,text:dn(s.result),inputTokens:o,outputTokens:i,cachedTokens:l,costUsd:xr(s.total_cost_usd),subtype:dn(s.subtype,"turn.failed"),isError:!0,errors:u?[u]:[]}]}if(r==="error"){const a=gc(s.message??s.error??s);return[{kind:"stderr",ts:n,text:a||t}]}return[{kind:"stdout",ts:n,text:t}]}const ii="gpt-5.3-codex",fl=!0;function UP(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function BP(t){const n={};for(const s of t.split(/\r?\n/)){const r=s.trim();if(!r||r.startsWith("#"))continue;const a=r.indexOf("=");if(a<=0)continue;const o=r.slice(0,a).trim(),i=r.slice(a+1);/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&(n[o]=i)}return n}function KP(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const n={};for(const[s,r]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;if(typeof r=="string"){n[s]={type:"plain",value:r};continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;const a=r;if(a.type==="plain"&&typeof a.value=="string"){n[s]={type:"plain",value:a.value};continue}a.type==="secret_ref"&&typeof a.secretId=="string"&&(n[s]={type:"secret_ref",secretId:a.secretId,...typeof a.version=="number"||a.version==="latest"?{version:a.version}:{}})}return n}function zP(t){const n=t.trim();if(!n)return null;try{const s=JSON.parse(n);return typeof s!="object"||s===null||Array.isArray(s)?null:s}catch{return null}}function WP(t){const n={};t.cwd&&(n.cwd=t.cwd),t.instructionsFilePath&&(n.instructionsFilePath=t.instructionsFilePath),t.promptTemplate&&(n.promptTemplate=t.promptTemplate),t.bootstrapPrompt&&(n.bootstrapPromptTemplate=t.bootstrapPrompt),n.model=t.model||ii,t.thinkingEffort&&(n.modelReasoningEffort=t.thinkingEffort),n.timeoutSec=0,n.graceSec=15;const s=KP(t.envBindings),r=BP(t.envVars);for(const[o,i]of Object.entries(r))Object.prototype.hasOwnProperty.call(s,o)||(s[o]={type:"plain",value:i});Object.keys(s).length>0&&(n.env=s),n.search=t.search,n.dangerouslyBypassApprovalsAndSandbox=typeof t.dangerouslyBypassSandbox=="boolean"?t.dangerouslyBypassSandbox:fl,t.workspaceStrategyType==="git_worktree"&&(n.workspaceStrategy={type:"git_worktree",...t.workspaceBaseRef?{baseRef:t.workspaceBaseRef}:{},...t.workspaceBranchTemplate?{branchTemplate:t.workspaceBranchTemplate}:{},...t.worktreeParentDir?{worktreeParentDir:t.worktreeParentDir}:{}});const a=zP(t.runtimeServicesJson??"");return a&&Array.isArray(a.services)&&(n.workspaceRuntime=a),t.command&&(n.command=t.command),t.extraArgs&&(n.extraArgs=UP(t.extraArgs)),n}const HP="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",VP="Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the system prompt at runtime. Note: Codex may still auto-apply repo-scoped AGENTS.md files from the workspace.";function QP({mode:t,isCreate:n,adapterType:s,values:r,set:a,config:o,eff:i,mark:l,models:u,hideInstructionsFile:d}){const m=o.dangerouslyBypassApprovalsAndSandbox===!0||o.dangerouslyBypassSandbox===!0;return e.jsxs(e.Fragment,{children:[!d&&e.jsx(ct,{label:"Agent instructions file",hint:VP,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{value:n?r.instructionsFilePath??"":i("adapterConfig","instructionsFilePath",String(o.instructionsFilePath??"")),onCommit:p=>n?a({instructionsFilePath:p}):l("adapterConfig","instructionsFilePath",p||void 0),immediate:!0,className:HP,placeholder:"/absolute/path/to/AGENTS.md"}),e.jsx(pr,{})]})}),e.jsx(ao,{label:"Bypass sandbox",hint:Rt.dangerouslyBypassSandbox,checked:n?r.dangerouslyBypassSandbox:i("adapterConfig","dangerouslyBypassApprovalsAndSandbox",m),onChange:p=>n?a({dangerouslyBypassSandbox:p}):l("adapterConfig","dangerouslyBypassApprovalsAndSandbox",p)}),e.jsx(ao,{label:"Enable search",hint:Rt.search,checked:n?r.search:i("adapterConfig","search",!!o.search),onChange:p=>n?a({search:p}):l("adapterConfig","search",p)}),e.jsx(Q0,{isCreate:n,values:r,set:a,config:o,mark:l,eff:i,mode:t,adapterType:s,models:u})]})}const GP={type:"codex_local",label:"Codex (local)",parseStdoutLine:qP,ConfigFields:QP,buildAdapterConfig:WP};function JP(t){var o;const n=t.trim();if(!n)return{stream:null,line:""};const s=n.match(/^(stdout|stderr)\s*[:=]?\s*([\[{].*)$/i);if(!s)return{stream:null,line:n};const r=((o=s[1])==null?void 0:o.toLowerCase())==="stderr"?"stderr":"stdout",a=(s[2]??"").trim();return{stream:r,line:a}}function ZP(t){try{return JSON.parse(t)}catch{return null}}function bn(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function it(t,n=""){return typeof t=="string"?t:n}function is(t,n=0){return typeof t=="number"&&Number.isFinite(t)?t:n}function za(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}const Jl=2e3;function G0(t){const n=bn(t);if(!n)return za(t);const s=bn(n.success);if(!s)return za(t);const r=is(s.exitCode,NaN),a=it(s.stdout).trim(),o=it(s.stderr).trim();if(!(Number.isFinite(r)||a.length>0||o.length>0))return za(t);const l=[];if(Number.isFinite(r)&&l.push(`exit ${r}`),a){const u=a.length>Jl?a.slice(0,Jl)+`
|
|
38
|
+
... (truncated)`:a;l.push("<stdout>"),l.push(u)}if(o){const u=o.length>Jl?o.slice(0,Jl)+`
|
|
39
|
+
... (truncated)`:o;l.push("<stderr>"),l.push(u)}return l.join(`
|
|
40
|
+
`)}function J0(t,n){var r;const s=it((n==null?void 0:n.command)??((r=bn(t))==null?void 0:r.command));return s?{command:s}:t}function YP(t,n){if(typeof t=="string"){const i=t.trim();return i?[{kind:"user",ts:n,text:i}]:[]}const s=bn(t);if(!s)return[];const r=[],a=it(s.text).trim();a&&r.push({kind:"user",ts:n,text:a});const o=Array.isArray(s.content)?s.content:[];for(const i of o){const l=bn(i);if(!l)continue;const u=it(l.type).trim();if(u!=="output_text"&&u!=="text")continue;const d=it(l.text).trim();d&&r.push({kind:"user",ts:n,text:d})}return r}function XP(t,n){if(typeof t=="string"){const i=t.trim();return i?[{kind:"assistant",ts:n,text:i}]:[]}const s=bn(t);if(!s)return[];const r=[],a=it(s.text).trim();a&&r.push({kind:"assistant",ts:n,text:a});const o=Array.isArray(s.content)?s.content:[];for(const i of o){const l=bn(i);if(!l)continue;const u=it(l.type).trim();if(u==="output_text"||u==="text"){const d=it(l.text).trim();d&&r.push({kind:"assistant",ts:n,text:d});continue}if(u==="thinking"){const d=it(l.text).trim();d&&r.push({kind:"thinking",ts:n,text:d});continue}if(u==="tool_call"){const d=it(l.name,it(l.tool,"tool")),m=l.input??l.arguments??l.args??{},p=d==="shellToolCall"||d==="shell"?J0(m,bn(m)??void 0):m;r.push({kind:"tool_call",ts:n,name:d,toolUseId:it(l.tool_use_id)||it(l.toolUseId)||it(l.call_id)||it(l.id)||void 0,input:p});continue}if(u==="tool_result"){const d=it(l.tool_use_id)||it(l.toolUseId)||it(l.call_id)||it(l.id)||"tool_result",m=l.output??l.result??l.text,p=typeof m=="object"&&m!==null?G0(m):it(m)||za(m),x=l.is_error===!0||it(l.status).toLowerCase()==="error";r.push({kind:"tool_result",ts:n,toolUseId:d,content:p,isError:x})}}return r}function eM(t,n){var m,p,x;const s=it(t.subtype).trim().toLowerCase(),r=it(t.call_id)||it(t.callId)||it(t.id)||"tool_call",a=bn(t.tool_call??t.toolCall);if(!a)return[{kind:"system",ts:n,text:`tool_call${s?` (${s})`:""}`}];const[o]=Object.keys(a);if(!o)return[{kind:"system",ts:n,text:`tool_call${s?` (${s})`:""}`}];const i=bn(a[o])??{},l=i.args??((m=bn(i.function))==null?void 0:m.arguments)??i,u=o==="shellToolCall"||o==="shell",d=u?J0(l,i):l;if(s==="started"||s==="start")return[{kind:"tool_call",ts:n,name:o,toolUseId:r,input:d}];if(s==="completed"||s==="complete"||s==="finished"){const f=i.result??i.output??i.error??((p=bn(i.function))==null?void 0:p.result)??((x=bn(i.function))==null?void 0:x.output),h=t.is_error===!0||i.is_error===!0||it(i.status).toLowerCase()==="error"||it(i.status).toLowerCase()==="failed"||it(i.status).toLowerCase()==="cancelled"||i.error!==void 0,j=f!==void 0?u?G0(f):za(f):`${o} completed`;return[{kind:"tool_result",ts:n,toolUseId:r,content:j,isError:h}]}return[{kind:"system",ts:n,text:`tool_call${s?` (${s})`:""}: ${o}`}]}function tM(t,n){var o,i;const s=JP(t);if(!s.line)return[];const r=bn(ZP(s.line));if(!r)return[{kind:"stdout",ts:n,text:s.line}];const a=it(r.type);if(a==="system"){const l=it(r.subtype);if(l==="init"){const u=it(r.session_id)||it(r.sessionId)||it(r.sessionID);return[{kind:"init",ts:n,model:it(r.model,"cursor"),sessionId:u}]}return[{kind:"system",ts:n,text:l?`system: ${l}`:"system"}]}if(a==="assistant"){const l=XP(r.message,n);return l.length>0?l:[{kind:"assistant",ts:n,text:it(r.result)}]}if(a==="user")return YP(r.message,n);if(a==="thinking"){const l=it(r.text),u=it((o=bn(r.delta))==null?void 0:o.text),d=l.length>0?l:u,p=it(r.subtype).trim().toLowerCase()==="delta"||bn(r.delta)!==null;return d.trim()?[{kind:"thinking",ts:n,text:p?d:d.trim(),...p?{delta:!0}:{}}]:[]}if(a==="tool_call")return eM(r,n);if(a==="result"){const l=bn(r.usage),u=is(l==null?void 0:l.input_tokens,is(l==null?void 0:l.inputTokens)),d=is(l==null?void 0:l.output_tokens,is(l==null?void 0:l.outputTokens)),m=is(l==null?void 0:l.cached_input_tokens,is(l==null?void 0:l.cachedInputTokens,is(l==null?void 0:l.cache_read_input_tokens))),p=it(r.subtype,"result"),x=Array.isArray(r.errors)?r.errors.map(j=>za(j)).filter(Boolean):[],f=it(r.error).trim();f&&x.push(f);const h=r.is_error===!0||p==="error"||p==="failed";return[{kind:"result",ts:n,text:it(r.result),inputTokens:u,outputTokens:d,cachedTokens:m,costUsd:is(r.total_cost_usd,is(r.cost_usd,is(r.cost))),subtype:p,isError:h,errors:x}]}if(a==="error"){const l=it(r.message)||za(r.error??r.detail)||s.line;return[{kind:"stderr",ts:n,text:l}]}if(a==="step_start"){const l=it(r.sessionID);return[{kind:"system",ts:n,text:`step started${l?` (${l})`:""}`}]}if(a==="text"){const l=bn(r.part),u=it(l==null?void 0:l.text).trim();return u?[{kind:"assistant",ts:n,text:u}]:[]}if(a==="tool_use"){const l=bn(r.part),u=it(l==null?void 0:l.callID,it(l==null?void 0:l.id,"tool_use")),d=it(l==null?void 0:l.tool,"tool"),m=bn(l==null?void 0:l.state),p=(m==null?void 0:m.input)??{},x=it(m==null?void 0:m.output).trim(),f=it(m==null?void 0:m.status).trim(),h=is((i=bn(m==null?void 0:m.metadata))==null?void 0:i.exit,NaN),j=f==="failed"||f==="error"||f==="cancelled"||Number.isFinite(h)&&h!==0,b=[{kind:"tool_call",ts:n,name:d,input:p}];if(f||x){const g=[];f&&g.push(`status: ${f}`),Number.isFinite(h)&&g.push(`exit: ${h}`),x&&(g.length>0&&g.push(""),g.push(x)),b.push({kind:"tool_result",ts:n,toolUseId:u,content:g.join(`
|
|
41
|
+
`).trim()||"tool completed",isError:j})}return b}if(a==="step_finish"){const l=bn(r.part),u=bn(l==null?void 0:l.tokens),d=bn(u==null?void 0:u.cache),m=it(l==null?void 0:l.reason);return[{kind:"result",ts:n,text:m,inputTokens:is(u==null?void 0:u.input),outputTokens:is(u==null?void 0:u.output),cachedTokens:is(d==null?void 0:d.read),costUsd:is(l==null?void 0:l.cost),subtype:m||"step_finish",isError:m==="error"||m==="failed",errors:[]}]}return[{kind:"stdout",ts:n,text:s.line}]}const li="auto";function nM(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function sM(t){const n={};for(const s of t.split(/\r?\n/)){const r=s.trim();if(!r||r.startsWith("#"))continue;const a=r.indexOf("=");if(a<=0)continue;const o=r.slice(0,a).trim(),i=r.slice(a+1);/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&(n[o]=i)}return n}function rM(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const n={};for(const[s,r]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;if(typeof r=="string"){n[s]={type:"plain",value:r};continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;const a=r;if(a.type==="plain"&&typeof a.value=="string"){n[s]={type:"plain",value:a.value};continue}a.type==="secret_ref"&&typeof a.secretId=="string"&&(n[s]={type:"secret_ref",secretId:a.secretId,...typeof a.version=="number"||a.version==="latest"?{version:a.version}:{}})}return n}function aM(t){const n=t.trim().toLowerCase();return n==="plan"||n==="ask"?n:null}function oM(t){const n={};t.cwd&&(n.cwd=t.cwd),t.instructionsFilePath&&(n.instructionsFilePath=t.instructionsFilePath),t.promptTemplate&&(n.promptTemplate=t.promptTemplate),t.bootstrapPrompt&&(n.bootstrapPromptTemplate=t.bootstrapPrompt),n.model=t.model||li;const s=aM(t.thinkingEffort);s&&(n.mode=s),n.timeoutSec=0,n.graceSec=15;const r=rM(t.envBindings),a=sM(t.envVars);for(const[o,i]of Object.entries(a))Object.prototype.hasOwnProperty.call(r,o)||(r[o]={type:"plain",value:i});return Object.keys(r).length>0&&(n.env=r),t.command&&(n.command=t.command),t.extraArgs&&(n.extraArgs=nM(t.extraArgs)),n}const iM="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",lM="Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the prompt at runtime.";function cM({isCreate:t,values:n,set:s,config:r,eff:a,mark:o,hideInstructionsFile:i}){return i?null:e.jsx(ct,{label:"Agent instructions file",hint:lM,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{value:t?n.instructionsFilePath??"":a("adapterConfig","instructionsFilePath",String(r.instructionsFilePath??"")),onCommit:l=>t?s({instructionsFilePath:l}):o("adapterConfig","instructionsFilePath",l||void 0),immediate:!0,className:iM,placeholder:"/absolute/path/to/AGENTS.md"}),e.jsx(pr,{})]})})}const dM={type:"cursor",label:"Cursor CLI (local)",parseStdoutLine:tM,ConfigFields:cM,buildAdapterConfig:oM};function uM(t){try{return JSON.parse(t)}catch{return null}}function Ys(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Nt(t,n=""){return typeof t=="string"?t:n}function zs(t,n=0){return typeof t=="number"&&Number.isFinite(t)?t:n}function Z0(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}function Pu(t){if(typeof t=="string")return t;const n=Ys(t);if(!n)return"";const s=typeof n.message=="string"&&n.message||typeof n.error=="string"&&n.error||typeof n.code=="string"&&n.code||"";if(s)return s;try{return JSON.stringify(n)}catch{return""}}function mM(t,n,s){if(typeof t=="string"){const l=t.trim();return l?[{kind:s,ts:n,text:l}]:[]}const r=Ys(t);if(!r)return[];const a=[],o=Nt(r.text).trim();o&&a.push({kind:s,ts:n,text:o});const i=Array.isArray(r.content)?r.content:[];for(const l of i){const u=Ys(l);if(!u)continue;const d=Nt(u.type).trim();if(d!=="output_text"&&d!=="text"&&d!=="content")continue;const m=Nt(u.text).trim()||Nt(u.content).trim();m&&a.push({kind:s,ts:n,text:m})}return a}function pM(t,n){if(typeof t=="string"){const i=t.trim();return i?[{kind:"assistant",ts:n,text:i}]:[]}const s=Ys(t);if(!s)return[];const r=[],a=Nt(s.text).trim();a&&r.push({kind:"assistant",ts:n,text:a});const o=Array.isArray(s.content)?s.content:[];for(const i of o){const l=Ys(i);if(!l)continue;const u=Nt(l.type).trim();if(u==="output_text"||u==="text"||u==="content"){const d=Nt(l.text).trim()||Nt(l.content).trim();d&&r.push({kind:"assistant",ts:n,text:d});continue}if(u==="thinking"){const d=Nt(l.text).trim();d&&r.push({kind:"thinking",ts:n,text:d});continue}if(u==="tool_call"){const d=Nt(l.name,Nt(l.tool,"tool"));r.push({kind:"tool_call",ts:n,name:d,input:l.input??l.arguments??l.args??{}});continue}if(u==="tool_result"||u==="tool_response"){const d=Nt(l.tool_use_id)||Nt(l.toolUseId)||Nt(l.call_id)||Nt(l.id)||"tool_result",m=Nt(l.output)||Nt(l.text)||Nt(l.result)||Z0(l.output??l.result??l.text??l.response),p=l.is_error===!0||Nt(l.status).toLowerCase()==="error";r.push({kind:"tool_result",ts:n,toolUseId:d,content:m,isError:p})}}return r}function xM(t,n){const s=Nt(t.subtype).trim().toLowerCase(),r=Nt(t.call_id,Nt(t.callId,Nt(t.id,"tool_call"))),a=Ys(t.tool_call??t.toolCall);if(!a)return[{kind:"system",ts:n,text:`tool_call${s?` (${s})`:""}`}];const[o]=Object.keys(a);if(!o)return[{kind:"system",ts:n,text:`tool_call${s?` (${s})`:""}`}];const i=Ys(a[o])??{};if(s==="started"||s==="start")return[{kind:"tool_call",ts:n,name:o,input:i.args??i.input??i.arguments??i}];if(s==="completed"||s==="complete"||s==="finished"){const l=i.result??i.output??i.error,u=t.is_error===!0||i.is_error===!0||i.error!==void 0||Nt(i.status).toLowerCase()==="error";return[{kind:"tool_result",ts:n,toolUseId:r,content:l!==void 0?Z0(l):`${o} completed`,isError:u}]}return[{kind:"system",ts:n,text:`tool_call${s?` (${s})`:""}: ${o}`}]}function fM(t){return Nt(t.session_id)||Nt(t.sessionId)||Nt(t.sessionID)||Nt(t.checkpoint_id)||Nt(t.thread_id)}function hM(t){const n=Ys(t.usage)??Ys(t.usageMetadata),r=Ys(n==null?void 0:n.usageMetadata)??n??{};return{inputTokens:zs(r.input_tokens,zs(r.inputTokens,zs(r.promptTokenCount))),outputTokens:zs(r.output_tokens,zs(r.outputTokens,zs(r.candidatesTokenCount))),cachedTokens:zs(r.cached_input_tokens,zs(r.cachedInputTokens,zs(r.cachedContentTokenCount)))}}function gM(t,n){var a;const s=Ys(uM(t));if(!s)return[{kind:"stdout",ts:n,text:t}];const r=Nt(s.type);if(r==="system"){const o=Nt(s.subtype);if(o==="init"){const i=fM(s);return[{kind:"init",ts:n,model:Nt(s.model,"gemini"),sessionId:i}]}if(o==="error"){const i=Pu(s.error??s.message??s.detail);return[{kind:"stderr",ts:n,text:i||"error"}]}return[{kind:"system",ts:n,text:`system: ${o||"event"}`}]}if(r==="assistant")return pM(s.message,n);if(r==="user")return mM(s.message,n,"user");if(r==="thinking"){const o=Nt(s.text).trim()||Nt((a=Ys(s.delta))==null?void 0:a.text).trim();return o?[{kind:"thinking",ts:n,text:o}]:[]}if(r==="tool_call")return xM(s,n);if(r==="result"){const o=hM(s),i=s.is_error===!0?[Pu(s.error??s.message??s.result)].filter(Boolean):[];return[{kind:"result",ts:n,text:Nt(s.result)||Nt(s.text)||Nt(s.response),inputTokens:o.inputTokens,outputTokens:o.outputTokens,cachedTokens:o.cachedTokens,costUsd:zs(s.total_cost_usd,zs(s.cost_usd,zs(s.cost))),subtype:Nt(s.subtype,"result"),isError:s.is_error===!0,errors:i}]}if(r==="error"){const o=Pu(s.error??s.message??s.detail);return[{kind:"stderr",ts:n,text:o||"error"}]}return[{kind:"stdout",ts:n,text:t}]}const ci="auto";function bM(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function yM(t){const n={};for(const s of t.split(/\r?\n/)){const r=s.trim();if(!r||r.startsWith("#"))continue;const a=r.indexOf("=");if(a<=0)continue;const o=r.slice(0,a).trim(),i=r.slice(a+1);/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&(n[o]=i)}return n}function vM(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const n={};for(const[s,r]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;if(typeof r=="string"){n[s]={type:"plain",value:r};continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;const a=r;if(a.type==="plain"&&typeof a.value=="string"){n[s]={type:"plain",value:a.value};continue}a.type==="secret_ref"&&typeof a.secretId=="string"&&(n[s]={type:"secret_ref",secretId:a.secretId,...typeof a.version=="number"||a.version==="latest"?{version:a.version}:{}})}return n}function jM(t){const n={};t.cwd&&(n.cwd=t.cwd),t.instructionsFilePath&&(n.instructionsFilePath=t.instructionsFilePath),t.promptTemplate&&(n.promptTemplate=t.promptTemplate),t.bootstrapPrompt&&(n.bootstrapPromptTemplate=t.bootstrapPrompt),n.model=t.model||ci,n.timeoutSec=0,n.graceSec=15;const s=vM(t.envBindings),r=yM(t.envVars);for(const[a,o]of Object.entries(r))Object.prototype.hasOwnProperty.call(s,a)||(s[a]={type:"plain",value:o});return Object.keys(s).length>0&&(n.env=s),n.sandbox=!t.dangerouslyBypassSandbox,t.command&&(n.command=t.command),t.extraArgs&&(n.extraArgs=bM(t.extraArgs)),n}const wM="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",NM="Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Prepended to the Gemini prompt at runtime.";function kM({isCreate:t,values:n,set:s,config:r,eff:a,mark:o,hideInstructionsFile:i}){return i?null:e.jsx(e.Fragment,{children:e.jsx(ct,{label:"Agent instructions file",hint:NM,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{value:t?n.instructionsFilePath??"":a("adapterConfig","instructionsFilePath",String(r.instructionsFilePath??"")),onCommit:l=>t?s({instructionsFilePath:l}):o("adapterConfig","instructionsFilePath",l||void 0),immediate:!0,className:wM,placeholder:"/absolute/path/to/AGENTS.md"}),e.jsx(pr,{})]})})})}const CM={type:"gemini_local",label:"Gemini CLI (local)",parseStdoutLine:gM,ConfigFields:kM,buildAdapterConfig:jM},SM=300,td="┊";function IM(t){return t.replace(/[(][^()]{2,20}[)]\s*/gu,"").trim()}function _M(t){return/^┊\s*💬/.test(t)}function AM(t){return t.replace(/^[\s┊]*💬\s*/,"").trim()}function EM(t){let n=t.trim().replace(/^\[done\]\s*/,"");if(!n.startsWith(td))return null;n=n.slice(td.length),n=IM(n).trim();const s=n.match(/([\d.]+s)\s*(?:\([\d.]+s\))?\s*$/),r=s?s[1]:"";let a=s?n.slice(0,n.lastIndexOf(s[0])).trim():n;const o=/\[(?:exit \d+|error|full)\]/.test(a)||/\[error\]\s*$/.test(n),i=a.match(/^(\S+)\s+(.*)/);if(!i)return{name:"tool",detail:a,duration:r,hasError:o};const l=i[1],u=i[2].trim();return{name:{$:"shell",exec:"shell",terminal:"shell",search:"search",fetch:"fetch",crawl:"crawl",navigate:"browser",snapshot:"browser",click:"browser",type:"browser",scroll:"browser",back:"browser",press:"browser",close:"browser",images:"browser",vision:"browser",read:"read",write:"write",patch:"patch",grep:"search",find:"search",plan:"plan",recall:"recall",proc:"process",delegate:"delegate",todo:"todo",memory:"memory",clarify:"clarify",session_search:"recall",code:"execute",execute:"execute",web_search:"search",web_extract:"fetch",browser_navigate:"browser",browser_click:"browser",browser_type:"browser",browser_snapshot:"browser",browser_vision:"browser",browser_scroll:"browser",browser_press:"browser",browser_back:"browser",browser_close:"browser",browser_get_images:"browser",read_file:"read",write_file:"write_file",search_files:"search",patch_file:"patch",execute_code:"execute"}[l.toLowerCase()]||l,detail:u,duration:r,hasError:o}}let TM=0;function RM(){return`hermes-tool-${++TM}`}function PM(t){return t.includes("💭")||t.startsWith("<thinking>")||t.startsWith("</thinking>")||t.startsWith("Thinking:")}function MM(t,n){const s=t.trim();if(!s)return[];if(s.startsWith("[hermes]")||s.startsWith("[paperclip]"))return[{kind:"system",ts:n,text:s}];if(s.startsWith("[tool]"))return[];if(/^\[\d{4}-\d{2}-\d{2}T/.test(s))return[{kind:"stderr",ts:n,text:s}];if(new RegExp("^\\p{Emoji_Presentation}\\s*(Completed|Running|Error)?\\s*$","u").test(s))return[];if(s.startsWith("session_id:"))return[{kind:"system",ts:n,text:s}];if(s.includes(td)){if(_M(s))return[{kind:"assistant",ts:n,text:AM(s)}];const r=EM(s);if(r){const o=RM(),i=r.duration?`${r.detail} ${r.duration}`:r.detail;return[{kind:"tool_call",ts:n,name:r.name,input:{detail:r.detail},toolUseId:o},{kind:"tool_result",ts:n,toolUseId:o,content:i,isError:r.hasError}]}const a=s.replace(/^\[done\]\s*/,"").replace(new RegExp(`^${td.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*`),"").trim();return[{kind:"stdout",ts:n,text:a}]}return PM(s)?[{kind:"thinking",ts:n,text:s.replace(/^💭\s*/,"")}]:s.startsWith("Error:")||s.startsWith("ERROR:")||s.startsWith("Traceback")?[{kind:"stderr",ts:n,text:s}]:[{kind:"assistant",ts:n,text:s}]}function $M(t){const n={};if(t.model.trim()&&(n.model=t.model.trim()),n.timeoutSec=SM,n.persistSession=!0,t.cwd&&(n.cwd=t.cwd),t.command&&(n.hermesCommand=t.command),t.extraArgs&&(n.extraArgs=t.extraArgs.split(/\s+/).filter(Boolean)),t.thinkingEffort){const s=n.extraArgs||[];s.push("--reasoning-effort",String(t.thinkingEffort)),n.extraArgs=s}return t.promptTemplate&&(n.promptTemplate=t.promptTemplate),n}const DM="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",OM="Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the system prompt at runtime.";function LM({isCreate:t,values:n,set:s,config:r,eff:a,mark:o,hideInstructionsFile:i}){return i?null:e.jsx(ct,{label:"Agent instructions file",hint:OM,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{value:t?n.instructionsFilePath??"":a("adapterConfig","instructionsFilePath",String(r.instructionsFilePath??"")),onCommit:l=>t?s({instructionsFilePath:l}):o("adapterConfig","instructionsFilePath",l||void 0),immediate:!0,className:DM,placeholder:"/absolute/path/to/AGENTS.md"}),e.jsx(pr,{})]})})}const FM={type:"hermes_local",label:"Hermes Agent",parseStdoutLine:MM,ConfigFields:LM,buildAdapterConfig:$M};function qM(t){try{return JSON.parse(t)}catch{return null}}function ar(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function ns(t,n=""){return typeof t=="string"?t:n}function Ei(t,n=0){return typeof t=="number"&&Number.isFinite(t)?t:n}function UM(t){if(typeof t=="string")return t;const n=ar(t);if(!n)return"";const s=ar(n.data),r=ns(n.message)||ns(s==null?void 0:s.message)||ns(n.name)||"";if(r)return r;try{return JSON.stringify(n)}catch{return""}}function BM(t,n){const s=ar(t.part);if(!s)return[{kind:"system",ts:n,text:"tool event"}];const r=ns(s.tool,"tool"),a=ar(s.state),o=(a==null?void 0:a.input)??{},i={kind:"tool_call",ts:n,name:r,toolUseId:ns(s.callID)||ns(s.id)||void 0,input:o},l=ns(a==null?void 0:a.status);if(l!=="completed"&&l!=="error")return[i];const u=ns(a==null?void 0:a.output)||ns(a==null?void 0:a.error)||ns(s.title)||`${r} ${l}`,d=ar(a==null?void 0:a.metadata),m=[`status: ${l}`];if(d)for(const[x,f]of Object.entries(d))f!=null&&m.push(`${x}: ${f}`);const p=`${m.join(`
|
|
42
|
+
`)}
|
|
43
|
+
|
|
44
|
+
${u}`.trim();return[i,{kind:"tool_result",ts:n,toolUseId:ns(s.callID)||ns(s.id,r),content:p,isError:l==="error"}]}function KM(t,n){const s=ar(qM(t));if(!s)return[{kind:"stdout",ts:n,text:t}];const r=ns(s.type);if(r==="text"){const a=ar(s.part),o=ns(a==null?void 0:a.text).trim();return o?[{kind:"assistant",ts:n,text:o}]:[]}if(r==="reasoning"){const a=ar(s.part),o=ns(a==null?void 0:a.text).trim();return o?[{kind:"thinking",ts:n,text:o}]:[]}if(r==="tool_use")return BM(s,n);if(r==="step_start"){const a=ns(s.sessionID);return[{kind:"system",ts:n,text:`step started${a?` (${a})`:""}`}]}if(r==="step_finish"){const a=ar(s.part),o=ar(a==null?void 0:a.tokens),i=ar(o==null?void 0:o.cache),l=ns(a==null?void 0:a.reason,"step"),u=Ei(o==null?void 0:o.output,0)+Ei(o==null?void 0:o.reasoning,0);return[{kind:"result",ts:n,text:l,inputTokens:Ei(o==null?void 0:o.input,0),outputTokens:u,cachedTokens:Ei(i==null?void 0:i.read,0),costUsd:Ei(a==null?void 0:a.cost,0),subtype:l,isError:!1,errors:[]}]}if(r==="error"){const a=UM(s.error??s.message);return[{kind:"stderr",ts:n,text:a||t}]}return[{kind:"stdout",ts:n,text:t}]}function zM(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function WM(t){const n={};for(const s of t.split(/\r?\n/)){const r=s.trim();if(!r||r.startsWith("#"))continue;const a=r.indexOf("=");if(a<=0)continue;const o=r.slice(0,a).trim(),i=r.slice(a+1);/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&(n[o]=i)}return n}function HM(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const n={};for(const[s,r]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;if(typeof r=="string"){n[s]={type:"plain",value:r};continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;const a=r;if(a.type==="plain"&&typeof a.value=="string"){n[s]={type:"plain",value:a.value};continue}a.type==="secret_ref"&&typeof a.secretId=="string"&&(n[s]={type:"secret_ref",secretId:a.secretId,...typeof a.version=="number"||a.version==="latest"?{version:a.version}:{}})}return n}function VM(t){const n={};t.cwd&&(n.cwd=t.cwd),t.instructionsFilePath&&(n.instructionsFilePath=t.instructionsFilePath),t.promptTemplate&&(n.promptTemplate=t.promptTemplate),t.bootstrapPrompt&&(n.bootstrapPromptTemplate=t.bootstrapPrompt),t.model&&(n.model=t.model),t.thinkingEffort&&(n.variant=t.thinkingEffort),n.dangerouslySkipPermissions=t.dangerouslySkipPermissions,n.timeoutSec=0,n.graceSec=20;const s=HM(t.envBindings),r=WM(t.envVars);for(const[a,o]of Object.entries(r))Object.prototype.hasOwnProperty.call(s,a)||(s[a]={type:"plain",value:o});return Object.keys(s).length>0&&(n.env=s),t.command&&(n.command=t.command),t.extraArgs&&(n.extraArgs=zM(t.extraArgs)),n}const QM="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",GM="Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the system prompt at runtime.";function JM({isCreate:t,values:n,set:s,config:r,eff:a,mark:o,hideInstructionsFile:i}){return e.jsxs(e.Fragment,{children:[!i&&e.jsx(ct,{label:"Agent instructions file",hint:GM,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{value:t?n.instructionsFilePath??"":a("adapterConfig","instructionsFilePath",String(r.instructionsFilePath??"")),onCommit:l=>t?s({instructionsFilePath:l}):o("adapterConfig","instructionsFilePath",l||void 0),immediate:!0,className:QM,placeholder:"/absolute/path/to/AGENTS.md"}),e.jsx(pr,{})]})}),e.jsx(ao,{label:"Skip permissions",hint:Rt.dangerouslySkipPermissions,checked:t?n.dangerouslySkipPermissions:a("adapterConfig","dangerouslySkipPermissions",r.dangerouslySkipPermissions!==!1),onChange:l=>t?s({dangerouslySkipPermissions:l}):o("adapterConfig","dangerouslySkipPermissions",l)})]})}const ZM={type:"opencode_local",label:"OpenCode (local)",parseStdoutLine:KM,ConfigFields:JM,buildAdapterConfig:VM};function YM(t){try{return JSON.parse(t)}catch{return null}}function No(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Bs(t,n=""){return typeof t=="string"?t:n}function ko(t){if(typeof t=="string")return{text:t,thinking:""};if(!Array.isArray(t))return{text:"",thinking:""};let n="",s="";for(const r of t)r.type==="text"&&r.text&&(n+=r.text),r.type==="thinking"&&r.thinking&&(s+=r.thinking);return{text:n,thinking:s}}let Zl=new Map;function XM(t,n){const s=No(YM(t));if(!s){const a=t.trim();return a?[{kind:"stdout",ts:n,text:a}]:[]}const r=Bs(s.type);if(r==="response"||r==="extension_ui_request"||r==="extension_ui_response"||r==="extension_error")return[];if(r==="agent_start")return[{kind:"system",ts:n,text:"🚀 Pi agent started"}];if(r==="agent_end"){const a=[],o=s.messages;if(o&&o.length>0){const i=o[o.length-1];if((i==null?void 0:i.role)==="assistant"){const l=i.content,{text:u,thinking:d}=ko(l);d&&a.push({kind:"thinking",ts:n,text:d}),u&&a.push({kind:"assistant",ts:n,text:u});const m=No(i.usage);if(m){const p=m.inputTokens??m.input??0,x=m.outputTokens??m.output??0,f=m.cacheRead??m.cachedInputTokens??0,h=No(m.cost),j=(h==null?void 0:h.total)??m.costUsd??0;(p>0||x>0)&&a.push({kind:"result",ts:n,text:"Run completed",inputTokens:p,outputTokens:x,cachedTokens:f,costUsd:j,subtype:"end",isError:!1,errors:[]})}}}return a.length===0&&a.push({kind:"system",ts:n,text:"✅ Pi agent finished"}),a}if(r==="turn_start")return[];if(r==="turn_end"){const a=No(s.message),o=s.toolResults,i=[];if(a){const l=a.content,{text:u,thinking:d}=ko(l);d&&i.push({kind:"thinking",ts:n,text:d}),u&&i.push({kind:"assistant",ts:n,text:u})}if(o)for(const l of o){const u=Bs(l.toolCallId,`tool-${Date.now()}`),d=l.content,m=l.isError===!0;let p;typeof d=="string"?p=d:Array.isArray(d)?p=ko(d).text||JSON.stringify(d):p=JSON.stringify(d);const x=Zl.get(u),f=Bs(l.toolName,(x==null?void 0:x.toolName)||"tool");i.push({kind:"tool_result",ts:n,toolUseId:u,toolName:f,content:p,isError:m}),Zl.delete(u)}return i}if(r==="message_start")return[];if(r==="message_update"){const a=No(s.assistantMessageEvent);if(a){const o=Bs(a.type);if(o==="thinking_delta"){const i=Bs(a.delta);if(i)return[{kind:"thinking",ts:n,text:i,delta:!0}]}if(o==="text_delta"){const i=Bs(a.delta);if(i)return[{kind:"assistant",ts:n,text:i,delta:!0}]}if(o==="thinking_end"){const i=Bs(a.content);if(i)return[{kind:"thinking",ts:n,text:i}]}if(o==="text_end"){const i=Bs(a.content);if(i)return[{kind:"assistant",ts:n,text:i}]}}return[]}if(r==="message_end"){const a=No(s.message);if(a){const o=a.content,{text:i,thinking:l}=ko(o),u=[];return l&&u.push({kind:"thinking",ts:n,text:l}),i&&u.push({kind:"assistant",ts:n,text:i}),u}return[]}if(r==="tool_execution_start"){const a=Bs(s.toolCallId,`tool-${Date.now()}`),o=Bs(s.toolName,"tool"),i=s.args;return Zl.set(a,{toolName:o,args:i}),[{kind:"tool_call",ts:n,name:o,input:i,toolUseId:a}]}if(r==="tool_execution_update")return[];if(r==="tool_execution_end"){const a=Bs(s.toolCallId,`tool-${Date.now()}`),o=Bs(s.toolName,"tool"),i=s.result,l=s.isError===!0;let u;if(typeof i=="string")u=i;else if(Array.isArray(i))u=ko(i).text||JSON.stringify(i);else if(i&&typeof i=="object"){const d=i;Array.isArray(d.content)?u=ko(d.content).text||JSON.stringify(i):u=JSON.stringify(i)}else u=String(i);return Zl.delete(a),[{kind:"tool_result",ts:n,toolUseId:a,toolName:o,content:u,isError:l}]}return[{kind:"stdout",ts:n,text:t}]}function e$(t){const n={};for(const s of t.split(/\r?\n/)){const r=s.trim();if(!r||r.startsWith("#"))continue;const a=r.indexOf("=");if(a<=0)continue;const o=r.slice(0,a).trim(),i=r.slice(a+1);/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&(n[o]=i)}return n}function t$(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const n={};for(const[s,r]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;if(typeof r=="string"){n[s]={type:"plain",value:r};continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;const a=r;if(a.type==="plain"&&typeof a.value=="string"){n[s]={type:"plain",value:a.value};continue}a.type==="secret_ref"&&typeof a.secretId=="string"&&(n[s]={type:"secret_ref",secretId:a.secretId,...typeof a.version=="number"||a.version==="latest"?{version:a.version}:{}})}return n}function n$(t){const n={};t.cwd&&(n.cwd=t.cwd),t.instructionsFilePath&&(n.instructionsFilePath=t.instructionsFilePath),t.promptTemplate&&(n.promptTemplate=t.promptTemplate),t.bootstrapPrompt&&(n.bootstrapPromptTemplate=t.bootstrapPrompt),t.model&&(n.model=t.model),t.thinkingEffort&&(n.thinking=t.thinkingEffort),n.timeoutSec=0,n.graceSec=20;const s=t$(t.envBindings),r=e$(t.envVars);for(const[a,o]of Object.entries(r))Object.prototype.hasOwnProperty.call(s,a)||(s[a]={type:"plain",value:o});return Object.keys(s).length>0&&(n.env=s),t.command&&(n.command=t.command),t.extraArgs&&(n.extraArgs=t.extraArgs),t.args&&(n.args=t.args),n}const s$="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",r$="Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the system prompt at runtime.";function a$({isCreate:t,values:n,set:s,config:r,eff:a,mark:o,hideInstructionsFile:i}){return i?null:e.jsx(ct,{label:"Agent instructions file",hint:r$,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{value:t?n.instructionsFilePath??"":a("adapterConfig","instructionsFilePath",String(r.instructionsFilePath??"")),onCommit:l=>t?s({instructionsFilePath:l}):o("adapterConfig","instructionsFilePath",l||void 0),immediate:!0,className:s$,placeholder:"/absolute/path/to/AGENTS.md"}),e.jsx(pr,{})]})})}const o$={type:"pi_local",label:"Pi (local)",parseStdoutLine:XM,ConfigFields:a$,buildAdapterConfig:n$};function i$(t){var o;const n=t.trim();if(!n)return{stream:null,line:""};const s=n.match(/^(stdout|stderr)\s*[:=]?\s*(.*)$/i);if(!s)return{stream:null,line:n};const r=((o=s[1])==null?void 0:o.toLowerCase())==="stderr"?"stderr":"stdout",a=(s[2]??"").trim();return{stream:r,line:a}}function l$(t){try{return JSON.parse(t)}catch{return null}}function c$(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Dr(t){return typeof t=="string"?t:""}function d$(t,n){const s=t.match(/^\[openclaw-gateway:event\]\s+run=([^\s]+)\s+stream=([^\s]+)\s+data=(.*)$/s);if(!s)return[{kind:"stdout",ts:n,text:t}];const r=Dr(s[2]).toLowerCase(),a=c$(l$(Dr(s[3]).trim()));if(r==="assistant"){const o=Dr(a==null?void 0:a.delta);if(o.length>0)return[{kind:"assistant",ts:n,text:o,delta:!0}];const i=Dr(a==null?void 0:a.text);return i.length>0?[{kind:"assistant",ts:n,text:i}]:[]}if(r==="error"){const o=Dr(a==null?void 0:a.error)||Dr(a==null?void 0:a.message);return o?[{kind:"stderr",ts:n,text:o}]:[]}if(r==="lifecycle"){const o=Dr(a==null?void 0:a.phase).toLowerCase(),i=Dr(a==null?void 0:a.error)||Dr(a==null?void 0:a.message);if((o==="error"||o==="failed"||o==="cancelled")&&i)return[{kind:"stderr",ts:n,text:i}]}return[]}function u$(t,n){const s=i$(t);if(s.stream==="stderr")return[{kind:"stderr",ts:n,text:s.line}];const r=s.line.trim();return r?r.startsWith("[openclaw-gateway:event]")?d$(r,n):r.startsWith("[openclaw-gateway]")?[{kind:"system",ts:n,text:r.replace(/^\[openclaw-gateway\]\s*/,"")}]:[{kind:"stdout",ts:n,text:s.line}]:[]}function Eh(t){const n=t.trim();if(!n)return null;try{const s=JSON.parse(n);return typeof s!="object"||s===null||Array.isArray(s)?null:s}catch{return null}}function m$(t){const n={};t.url&&(n.url=t.url),n.timeoutSec=120,n.waitTimeoutMs=12e4,n.sessionKeyStrategy="issue",n.role="operator",n.scopes=["operator.admin"];const s=Eh(t.payloadTemplateJson??"");s&&(n.payloadTemplate=s);const r=Eh(t.runtimeServicesJson??"");return r&&Array.isArray(r.services)&&(n.workspaceRuntime=r),n}const p$="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function x$(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function f$(t){const n=x$(t);return Object.keys(n).length>0?JSON.stringify(n,null,2):""}function h$(t,n,s,r,a,o){if(t){r==null||r({[n]:s});return}const i=s.trim();if(!i){a("adapterConfig",o,void 0);return}try{const l=JSON.parse(i);typeof l=="object"&&l!==null&&!Array.isArray(l)&&a("adapterConfig",o,l)}catch{}}function g$({isCreate:t,values:n,set:s,config:r,mark:a}){return null}function b$({isCreate:t,values:n,set:s,config:r,mark:a}){const o=f$(r.payloadTemplate),[i,l]=c.useState(o);c.useEffect(()=>{t||l(o)},[o,t]);const u=t?(n==null?void 0:n.payloadTemplateJson)??"":i;return e.jsx(ct,{label:"Payload template JSON",hint:Rt.payloadTemplateJson,children:e.jsx("textarea",{className:`${p$} min-h-[132px]`,value:u,onChange:d=>{const m=d.target.value;t||l(m),h$(t,"payloadTemplateJson",m,s,a,"payloadTemplate")},placeholder:`{
|
|
45
|
+
"agentId": "remote-agent-123",
|
|
46
|
+
"metadata": {
|
|
47
|
+
"team": "platform"
|
|
48
|
+
}
|
|
49
|
+
}`})})}const ra="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function y$({label:t,value:n,onCommit:s,placeholder:r}){const[a,o]=c.useState(!1);return e.jsx(ct,{label:t,children:e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>o(i=>!i),className:"absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground/50 hover:text-muted-foreground transition-colors",children:a?e.jsx(pi,{className:"h-3.5 w-3.5"}):e.jsx(al,{className:"h-3.5 w-3.5"})}),e.jsx(nn,{value:n,onCommit:s,immediate:!0,type:a?"text":"password",className:ra+" pl-8",placeholder:r})]})})}function v$(t){return Array.isArray(t)?t.filter(n=>typeof n=="string").join(", "):typeof t=="string"?t:""}function j$({isCreate:t,values:n,set:s,config:r,eff:a,mark:o}){const i=r.headers&&typeof r.headers=="object"&&!Array.isArray(r.headers)?r.headers:{},l=a("adapterConfig","headers",i)??{},u=typeof l["x-openclaw-token"]=="string"?String(l["x-openclaw-token"]):typeof l["x-openclaw-auth"]=="string"?String(l["x-openclaw-auth"]):"",d=p=>{const x=p.trim(),f={...l};x?(f["x-openclaw-token"]=x,delete f["x-openclaw-auth"]):(delete f["x-openclaw-token"],delete f["x-openclaw-auth"]),o("adapterConfig","headers",Object.keys(f).length>0?f:void 0)},m=a("adapterConfig","sessionKeyStrategy",String(r.sessionKeyStrategy??"fixed"));return e.jsxs(e.Fragment,{children:[e.jsx(ct,{label:"Gateway URL",hint:Rt.webhookUrl,children:e.jsx(nn,{value:t?n.url:a("adapterConfig","url",String(r.url??"")),onCommit:p=>t?s({url:p}):o("adapterConfig","url",p||void 0),immediate:!0,className:ra,placeholder:"ws://127.0.0.1:18789"})}),e.jsx(b$,{isCreate:t,values:n,set:s,config:r,mark:o}),e.jsx(g$,{isCreate:t,values:n,set:s,config:r,mark:o}),!t&&e.jsxs(e.Fragment,{children:[e.jsx(ct,{label:"CrewSpace API URL override",children:e.jsx(nn,{value:a("adapterConfig","crewspaceApiUrl",String(r.crewspaceApiUrl??"")),onCommit:p=>o("adapterConfig","crewspaceApiUrl",p||void 0),immediate:!0,className:ra,placeholder:"https://crewspace.example"})}),e.jsx(ct,{label:"Session strategy",children:e.jsxs("select",{value:m,onChange:p=>o("adapterConfig","sessionKeyStrategy",p.target.value),className:ra,children:[e.jsx("option",{value:"fixed",children:"Fixed"}),e.jsx("option",{value:"issue",children:"Per issue"}),e.jsx("option",{value:"run",children:"Per run"})]})}),m==="fixed"&&e.jsx(ct,{label:"Session key",children:e.jsx(nn,{value:a("adapterConfig","sessionKey",String(r.sessionKey??"crewspace")),onCommit:p=>o("adapterConfig","sessionKey",p||void 0),immediate:!0,className:ra,placeholder:"crewspace"})}),e.jsx(y$,{label:"Gateway auth token (x-openclaw-token)",value:u,onCommit:d,placeholder:"OpenClaw gateway token"}),e.jsx(ct,{label:"Role",children:e.jsx(nn,{value:a("adapterConfig","role",String(r.role??"operator")),onCommit:p=>o("adapterConfig","role",p||void 0),immediate:!0,className:ra,placeholder:"operator"})}),e.jsx(ct,{label:"Scopes (comma-separated)",children:e.jsx(nn,{value:a("adapterConfig","scopes",v$(r.scopes??["operator.admin"])),onCommit:p=>{const x=p.split(",").map(f=>f.trim()).filter(Boolean);o("adapterConfig","scopes",x.length>0?x:void 0)},immediate:!0,className:ra,placeholder:"operator.admin"})}),e.jsx(ct,{label:"Wait timeout (ms)",children:e.jsx(nn,{value:a("adapterConfig","waitTimeoutMs",String(r.waitTimeoutMs??"120000")),onCommit:p=>{const x=Number.parseInt(p.trim(),10);o("adapterConfig","waitTimeoutMs",Number.isFinite(x)&&x>0?x:void 0)},immediate:!0,className:ra,placeholder:"120000"})}),e.jsx(ct,{label:"Device auth",children:e.jsx("div",{className:"text-xs text-muted-foreground leading-relaxed",children:"Always enabled for gateway agents. CrewSpace persists a device key during onboarding so pairing approvals remain stable across runs."})})]})]})}const w$={type:"openclaw_gateway",label:"OpenClaw Gateway",parseStdoutLine:u$,ConfigFields:j$,buildAdapterConfig:m$};function N$(t,n){return[{kind:"stdout",ts:n,text:t}]}const Th="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function k$(t){return Array.isArray(t)?t.filter(n=>typeof n=="string").join(", "):typeof t=="string"?t:""}function C$(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function S$({isCreate:t,values:n,set:s,config:r,eff:a,mark:o}){return e.jsxs(e.Fragment,{children:[e.jsx(ct,{label:"Command",hint:Rt.command,children:e.jsx(nn,{value:t?n.command:a("adapterConfig","command",String(r.command??"")),onCommit:i=>t?s({command:i}):o("adapterConfig","command",i||void 0),immediate:!0,className:Th,placeholder:"e.g. node, python"})}),e.jsx(ct,{label:"Args (comma-separated)",hint:Rt.args,children:e.jsx(nn,{value:t?n.args:a("adapterConfig","args",k$(r.args)),onCommit:i=>t?s({args:i}):o("adapterConfig","args",i?C$(i):void 0),immediate:!0,className:Th,placeholder:"e.g. script.js, --flag"})})]})}function I$(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function _$(t){const n={};return t.cwd&&(n.cwd=t.cwd),n.timeoutSec=0,n.graceSec=15,t.command&&(n.command=t.command),t.args&&(n.args=I$(t.args)),n}const Y0={type:"process",label:"Shell Process",parseStdoutLine:N$,ConfigFields:S$,buildAdapterConfig:_$};function A$(t,n){return[{kind:"stdout",ts:n,text:t}]}const E$="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function T$({isCreate:t,values:n,set:s,config:r,eff:a,mark:o}){return e.jsx(ct,{label:"Webhook URL",hint:Rt.webhookUrl,children:e.jsx(nn,{value:t?n.url:a("adapterConfig","url",String(r.url??"")),onCommit:i=>t?s({url:i}):o("adapterConfig","url",i||void 0),immediate:!0,className:E$,placeholder:"https://..."})})}function R$(t){const n={};return t.url&&(n.url=t.url),n.method="POST",n.timeoutMs=15e3,n}const P$={type:"http",label:"HTTP Webhook",parseStdoutLine:A$,ConfigFields:T$,buildAdapterConfig:R$},X0=[MP,GP,CM,FM,ZM,o$,dM,w$,Y0,P$],M$=new Map(X0.map(t=>[t.type,t]));function oo(t){return M$.get(t)??Y0}function $$(){return[...X0]}const D$="*";function Mu(t){const n=t.trim();return n?`${n[0]}${"*".repeat(Math.max(1,Array.from(n).length-1))}`:D$}const O$=[{regex:/\/Users\/([^/\\\s]+)/g,replace:(t,n)=>`/Users/${Mu(n)}`},{regex:/\/home\/([^/\\\s]+)/g,replace:(t,n)=>`/home/${Mu(n)}`},{regex:/([A-Za-z]:\\Users\\)([^\\/\s]+)/g,replace:(t,n,s)=>`${n}${Mu(s)}`}];function L$(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}function Ws(t,n){if((n==null?void 0:n.enabled)===!1)return t;let s=t;for(const r of O$)s=s.replace(r.regex,r.replace);return s}function nd(t,n){if(typeof t=="string")return Ws(t,n);if(Array.isArray(t))return t.map(r=>nd(r,n));if(!L$(t))return t;const s={};for(const[r,a]of Object.entries(t))s[r]=nd(a,n);return s}function Rh(t,n){switch(t.kind){case"assistant":case"thinking":case"user":case"stderr":case"system":case"stdout":return{...t,text:Ws(t.text,n)};case"tool_call":return{...t,name:Ws(t.name,n),input:nd(t.input,n)};case"tool_result":return{...t,content:Ws(t.content,n)};case"init":return{...t,model:Ws(t.model,n),sessionId:Ws(t.sessionId,n)};case"result":return{...t,text:Ws(t.text,n),subtype:Ws(t.subtype,n),errors:t.errors.map(s=>Ws(s,n))};default:return t}}function F$(t,n){if((n.kind==="thinking"||n.kind==="assistant")&&n.delta){const s=t[t.length-1];if(s&&s.kind===n.kind&&s.delta){s.text+=n.text,s.ts=n.ts;return}}t.push(n)}function Ph(t,n){for(const s of n)F$(t,s)}function ew(t,n,s){const r=[];let a="";const o={enabled:(s==null?void 0:s.censorUsernameInLogs)??!1};for(const l of t){if(l.stream==="stderr"){r.push({kind:"stderr",ts:l.ts,text:Ws(l.chunk,o)});continue}if(l.stream==="system"){r.push({kind:"system",ts:l.ts,text:Ws(l.chunk,o)});continue}const d=(a+l.chunk).split(/\r?\n/);a=d.pop()??"";for(const m of d){const p=m.trim();p&&Ph(r,n(p,l.ts).map(x=>Rh(x,o)))}}const i=a.trim();if(i){const l=t.length>0?t[t.length-1].ts:new Date().toISOString();Ph(r,n(i,l).map(u=>Rh(u,o)))}return r}const io={adapterType:"claude_local",cwd:"",instructionsFilePath:"",promptTemplate:"",model:"",thinkingEffort:"",chrome:!1,dangerouslySkipPermissions:!0,search:!1,dangerouslyBypassSandbox:!1,command:"",args:"",extraArgs:"",envVars:"",envBindings:{},url:"",bootstrapPrompt:"",payloadTemplateJson:"",workspaceStrategyType:"project_primary",workspaceBaseRef:"",workspaceBranchTemplate:"",worktreeParentDir:"",runtimeServicesJson:"",maxTurnsPerRun:300,heartbeatEnabled:!1,intervalSec:300};function q$(t){const n=t.trim();if(!n)return{title:"",description:null};const[s,...r]=n.split(/\r?\n/),a=s.trim(),o=r.join(`
|
|
50
|
+
`).trim();return{title:a,description:o.length>0?o:null}}const U$="Onboarding";function Mh(t){const n=t.createdAt instanceof Date?t.createdAt:new Date(t.createdAt);return Number.isNaN(n.getTime())?0:n.getTime()}function $u(t){return[...t].sort((n,s)=>Mh(n)-Mh(s))[0]??null}function B$(t){var a,o,i;const n=t.filter(l=>l.level==="company"),s=n.filter(l=>!l.parentId),r=s.filter(l=>l.status==="active");return((a=$u(r))==null?void 0:a.id)??((o=$u(s))==null?void 0:o.id)??((i=$u(n))==null?void 0:i.id)??null}function K$(t){return{name:U$,status:"in_progress",...t?{goalIds:[t]}:{}}}function z$(t){const n=t.title.trim(),s=t.description.trim();return{title:n,...s?{description:s}:{},assigneeAgentId:t.assigneeAgentId,projectId:t.projectId,...t.goalId?{goalId:t.goalId}:{},status:"todo"}}function tw(t){var s,r;const n=t.split("/").filter(Boolean);return n.length===1?((s=n[0])==null?void 0:s.toLowerCase())==="onboarding":n.length===2?((r=n[1])==null?void 0:r.toLowerCase())==="onboarding":!1}function W$(t){const{pathname:n,companyPrefix:s,companies:r}=t;if(!tw(n))return null;if(!s)return{initialStep:1};const a=r.find(o=>o.issuePrefix.toUpperCase()===s.toUpperCase())??null;return a?{initialStep:2,companyId:a.id}:{initialStep:1}}function nw(t){return!t.hasCompanies&&!tw(t.pathname)}const $h=[" ",".","·","▪","▫","○"],H$=24,V$=1e3/H$,Yl=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function Dh(t){const n=document.createElement("span");n.textContent="M",n.style.cssText="position:absolute;visibility:hidden;white-space:pre;font-size:11px;font-family:monospace;line-height:1;",t.appendChild(n);const s=n.getBoundingClientRect();return t.removeChild(n),{w:s.width,h:s.height}}function Q$(t){let n=0;for(const s of t)n=Math.max(n,s.length);return{width:n,height:t.length}}function sw(){const t=c.useRef(null),n=c.useRef(null);return c.useEffect(()=>{if(!t.current)return;const s=t.current,r=window.matchMedia("(prefers-reduced-motion: reduce)");let a=document.visibilityState!=="hidden",o=!1,i=0,l=0,u=0,d=0,m=7,p=11,x=new Float32Array(0),f=new Float32Array(0),h=new Float32Array(0),j=new Uint16Array(0),b=[],g="";function y(I){const K=Math.max(0,Math.min(.999,I)),T=Math.floor(K*$h.length);return $h[T]??" "}function v(){const I=Math.max(0,Math.ceil(s.clientWidth/Math.max(1,m))),K=Math.max(0,Math.ceil(s.clientHeight/Math.max(1,p)));if(I===u&&K===d)return;u=I,d=K;const T=u*d;x=new Float32Array(T),f=new Float32Array(u),h=new Float32Array(d),j=new Uint16Array(T),b=b.filter(z=>z.x>-z.width-2&&z.x<u+2&&z.y>-z.height-2&&z.y<d+2),g=""}function _(){if(u<=0||d<=0){s.textContent="";return}const I=Array.from({length:d},()=>Array.from({length:u},()=>" "));for(let w=0;w<d;w++)for(let F=0;F<u;F++){const A=(Math.sin(F*.11+w*.04)+Math.cos(w*.08-F*.02))*.18+.22;I[w][F]=y(A)}const K=18,T=13;for(let w=1;w<d-9;w+=T){const F=Math.floor(w/T)%2===0?2:10;for(let A=F;A<u-10;A+=K){const R=Yl[(A+w)%Yl.length];for(let Q=0;Q<R.length;Q++){const H=R[Q];for(let U=0;U<H.length;U++){const Z=H[U]??" ";if(Z===" ")continue;const V=w+Q,W=A+U;V<0||V>=d||W<0||W>=u||(I[V][W]=Z)}}}}const z=I.map(w=>w.join("")).join(`
|
|
51
|
+
`);s.textContent=z,g=z}function E(){const I=Yl[Math.floor(Math.random()*Yl.length)],K=Q$(I),T=Math.random();let z=0,w=0,F=0,A=0;T<.68?(z=Math.random()<.5?-K.width-1:u+1,w=Math.random()*Math.max(1,d-K.height),F=z<0?.04+Math.random()*.05:-(.04+Math.random()*.05),A=(Math.random()-.5)*.014):(z=Math.random()*Math.max(1,u-K.width),w=Math.random()<.5?-K.height-1:d+1,F=(Math.random()-.5)*.014,A=w<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),b.push({x:z,y:w,vx:F,vy:A,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:I,width:K.width,height:K.height})}function S(I,K){const T=Math.round(I.x),z=Math.round(I.y);for(let w=0;w<I.sprite.length;w++){const F=I.sprite[w],A=z+w;if(!(A<0||A>=d))for(let R=0;R<F.length;R++){const Q=F[R]??" ";if(Q===" ")continue;const H=T+R;if(H<0||H>=u)continue;const U=A*u+H,Z=Q==="│"||Q==="─"?.8:.92;x[U]=Math.max(x[U]??0,K*Z),j[U]=Q.charCodeAt(0)}}}function M(I){if(!o||(n.current=requestAnimationFrame(M),I-i<V$||u<=0||d<=0))return;const K=Math.min(2,i===0?1:(I-i)/16.6667);i=I,l+=K;const T=u*d,z=Math.max(3,Math.floor(T/2200));for(;b.length<z;)E();for(let F=0;F<x.length;F++)x[F]*=.92;j.fill(0);for(let F=b.length-1;F>=0;F--){const A=b[F];A.life+=K;const R=Math.sin((A.y+A.drift+l*.12)*.09)*.0018,Q=Math.cos((A.x-A.drift-l*.09)*.08)*.0014;if(A.vx=(A.vx+R)*.998,A.vy=(A.vy+Q)*.998,A.x+=A.vx*K,A.y+=A.vy*K,A.life>=A.maxLife||A.x<-A.width-2||A.x>u+2||A.y<-A.height-2||A.y>d+2){b.splice(F,1);continue}const H=A.life/A.maxLife,U=H<.12?H/.12:H>.88?(1-H)/.12:1;S(A,U)}for(let F=0;F<u;F++)f[F]=Math.sin(F*.08+l*.06);for(let F=0;F<d;F++)h[F]=Math.cos(F*.1-l*.05);let w="";for(let F=0;F<d;F++){for(let A=0;A<u;A++){const R=F*u+A,Q=j[R];if(Q>0){w+=String.fromCharCode(Q);continue}const H=(f[A]+h[F])*.08+.1,U=Math.max(x[R]??0,H*.45);w+=y(U)}F<d-1&&(w+=`
|
|
52
|
+
`)}w!==g&&(s.textContent=w,g=w)}function B(){const I=u>0&&d>0;if(r.matches){o&&(o=!1,n.current!==null&&cancelAnimationFrame(n.current),n.current=null),I&&_();return}if(!a||!I){o&&(o=!1,n.current!==null&&cancelAnimationFrame(n.current),n.current=null);return}o||(o=!0,i=0,n.current=requestAnimationFrame(M))}const k=new ResizeObserver(()=>{const I=Dh(s);m=I.w,p=I.h,v(),B()});k.observe(s);const L=()=>{a=document.visibilityState!=="hidden",B()};document.addEventListener("visibilitychange",L);const $=()=>{B()};r.addEventListener("change",$);const C=Dh(s);return m=C.w,p=C.h,v(),B(),()=>{o=!1,n.current!==null&&cancelAnimationFrame(n.current),k.disconnect(),document.removeEventListener("visibilitychange",L),r.removeEventListener("change",$)}},[]),e.jsx("pre",{ref:t,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"11px",fontFamily:"monospace"},"aria-hidden":"true"})}const Oh=`You are the CEO. You set the direction for the company.
|
|
53
|
+
|
|
54
|
+
- hire a founding engineer
|
|
55
|
+
- write a hiring plan
|
|
56
|
+
- break the roadmap into concrete tasks and start delegating work`;function G$(){const{onboardingOpen:t,onboardingOptions:n,closeOnboarding:s}=In(),{companies:r,setSelectedCompanyId:a,loading:o}=et(),i=at(),l=Sn(),u=fn(),{companyPrefix:d}=Xn(),[m,p]=c.useState(!1),x=d&&o?null:W$({pathname:u.pathname,companyPrefix:d,companies:r}),f=t||x!==null&&!m,h=t?n:x??{},j=h.initialStep??1,b=h.companyId,[g,y]=c.useState(j),[v,_]=c.useState(!1),[E,S]=c.useState(null),[M,B]=c.useState(!1),[k,L]=c.useState(""),[$,C]=c.useState(""),[I,K]=c.useState(""),[T,z]=c.useState("CEO"),[w,F]=c.useState("claude_local"),[A,R]=c.useState(""),[Q,H]=c.useState(""),[U,Z]=c.useState(""),[V,W]=c.useState(""),[J,Y]=c.useState(null),[de,fe]=c.useState(null),[Ce,le]=c.useState(!1),[Re,Pe]=c.useState(!1),[Fe,pe]=c.useState(!1),[Le,q]=c.useState(!1),[D,ie]=c.useState("Hire your first engineer and create a hiring plan"),[Ie,ue]=c.useState(Oh),Be=c.useRef(null),be=c.useCallback(()=>{const Ne=Be.current;Ne&&(Ne.style.height="auto",Ne.style.height=Ne.scrollHeight+"px")},[]),[he,Se]=c.useState(b??null),[we,ee]=c.useState(null),[me,ye]=c.useState(null),[Ke,qe]=c.useState(null),[se,ce]=c.useState(null),[Te,ae]=c.useState(null);c.useEffect(()=>{p(!1)},[u.pathname]),c.useEffect(()=>{if(!f)return;const Ne=h.companyId??null;y(h.initialStep??1),Se(Ne),ee(null),ye(null),ce(null),qe(null),ae(null)},[f,h.companyId,h.initialStep]),c.useEffect(()=>{if(!f||!he||we)return;const Ne=r.find(te=>te.id===he);Ne&&ee(Ne.issuePrefix)},[f,he,we,r]),c.useEffect(()=>{g===3&&be()},[g,Ie,be]);const{data:je,error:ke,isLoading:Xe,isFetching:lt}=oe({queryKey:he?N.agents.adapterModels(he,w):["agents","none","adapter-models",w],queryFn:()=>We.adapterModels(he,w),enabled:!!he&&f&&g===2}),It=w==="claude_local"||w==="codex_local"||w==="gemini_local"||w==="hermes_local"||w==="opencode_local"||w==="pi_local"||w==="cursor",Ue=Q.trim()||(w==="codex_local"?"codex":w==="gemini_local"?"gemini":w==="hermes_local"?"hermes":w==="pi_local"?"pi":w==="cursor"?"agent":w==="opencode_local"?"opencode":"claude");c.useEffect(()=>{g===2&&(Y(null),fe(null))},[g,w,A,Q,U,V]);const pt=(je??[]).find(Ne=>Ne.id===A),ht=(J==null?void 0:J.checks.some(Ne=>Ne.code==="claude_anthropic_api_key_overrides_subscription"))??!1,ln=w==="claude_local"&&(J==null?void 0:J.status)==="fail"&&ht,yt=c.useMemo(()=>{const Ne=k.trim().toLowerCase();return(je??[]).filter(te=>{if(!Ne)return!0;const Ae=Vi(te.id,"");return te.id.toLowerCase().includes(Ne)||te.label.toLowerCase().includes(Ne)||Ae.toLowerCase().includes(Ne)})},[je,k]),hn=c.useMemo(()=>{if(w!=="opencode_local")return[{provider:"models",entries:[...yt].sort((te,Ae)=>te.id.localeCompare(Ae.id))}];const Ne=new Map;for(const te of yt){const Ae=Vi(te.id),Je=Ne.get(Ae)??[];Je.push(te),Ne.set(Ae,Je)}return Array.from(Ne.entries()).sort(([te],[Ae])=>te.localeCompare(Ae)).map(([te,Ae])=>({provider:te,entries:[...Ae].sort((Je,ft)=>Je.id.localeCompare(ft.id))}))},[yt,w]);function pn(){y(1),_(!1),S(null),C(""),K(""),z("CEO"),F("claude_local"),R(""),H(""),Z(""),W(""),Y(null),fe(null),le(!1),Pe(!1),pe(!1),ie("Hire your first engineer and create a hiring plan"),ue(Oh),Se(null),ee(null),ye(null),qe(null),ce(null),ae(null)}function re(){pn(),s()}function $e(){const te=oo(w).buildAdapterConfig({...io,adapterType:w,model:w==="codex_local"?A||ii:w==="gemini_local"?A||ci:w==="cursor"?A||li:A,command:Q,args:U,url:V,dangerouslySkipPermissions:w==="claude_local"||w==="opencode_local",dangerouslyBypassSandbox:w==="codex_local"?fl:io.dangerouslyBypassSandbox});if(w==="claude_local"&&Re){const Ae=typeof te.env=="object"&&te.env!==null&&!Array.isArray(te.env)?{...te.env}:{};Ae.ANTHROPIC_API_KEY={type:"plain",value:""},te.env=Ae}return te}async function Ee(Ne){if(!he)return fe("Create or select a company before testing adapter environment."),null;le(!0),fe(null);try{const te=await We.testEnvironment(he,w,{adapterConfig:Ne??$e()});return Y(te),te}catch(te){return fe(te instanceof Error?te.message:"Adapter environment test failed"),null}finally{le(!1)}}async function He(){_(!0),S(null);try{const Ne=await ls.create({name:$.trim()});if(Se(Ne.id),ee(Ne.issuePrefix),a(Ne.id),i.invalidateQueries({queryKey:N.companies.all}),I.trim()){const te=q$(I),Ae=await Zs.create(Ne.id,{title:te.title,...te.description?{description:te.description}:{},level:"company",status:"active"});ye(Ae.id),i.invalidateQueries({queryKey:N.goals.list(Ne.id)})}else ye(null);y(2)}catch(Ne){S(Ne instanceof Error?Ne.message:"Failed to create company")}finally{_(!1)}}async function rt(){if(he){_(!0),S(null);try{if(w==="opencode_local"){const te=A.trim();if(!te){S("OpenCode requires an explicit model in provider/model format.");return}if(ke){S(ke instanceof Error?ke.message:"Failed to load OpenCode models.");return}if(Xe||lt){S("OpenCode models are still loading. Please wait and try again.");return}const Ae=je??[];if(!Ae.some(Je=>Je.id===te)){S(Ae.length===0?"No OpenCode models discovered. Run `opencode models` and authenticate providers.":`Configured OpenCode model is unavailable: ${te}`);return}}if(It&&!(J??await Ee()))return;const Ne=await We.create(he,{name:T.trim(),role:"ceo",adapterType:w,adapterConfig:$e(),runtimeConfig:{heartbeat:{enabled:!0,intervalSec:3600,wakeOnDemand:!0,cooldownSec:10,maxConcurrentRuns:1}}});qe(Ne.id),i.invalidateQueries({queryKey:N.agents.list(he)}),y(3)}catch(Ne){S(Ne instanceof Error?Ne.message:"Failed to create agent")}finally{_(!1)}}}async function xt(){if(!he||Fe)return;pe(!0),S(null),fe(null),Pe(!0);const Ne=(()=>{const te=$e(),Ae=typeof te.env=="object"&&te.env!==null&&!Array.isArray(te.env)?{...te.env}:{};return Ae.ANTHROPIC_API_KEY={type:"plain",value:""},te.env=Ae,te})();try{Ke&&(await We.update(Ke,{adapterConfig:Ne},he),i.invalidateQueries({queryKey:N.agents.list(he)}));const te=await Ee(Ne);(te==null?void 0:te.status)==="fail"&&S("Retried with ANTHROPIC_API_KEY unset in adapter config, but the environment test is still failing.")}catch(te){S(te instanceof Error?te.message:"Failed to unset ANTHROPIC_API_KEY and retry.")}finally{pe(!1)}}async function Pt(){!he||!Ke||(S(null),y(4))}async function gn(){if(!(!he||!Ke)){_(!0),S(null);try{let Ne=me;if(!Ne){const Je=await Zs.list(he);Ne=B$(Je),ye(Ne)}let te=se;te||(te=(await en.create(he,K$(Ne))).id,ce(te),i.invalidateQueries({queryKey:N.projects.list(he)}));let Ae=Te;if(!Ae){const Je=await nt.create(he,z$({title:D,description:Ie,assigneeAgentId:Ke,projectId:te,goalId:Ne}));Ae=Je.identifier??Je.id,ae(Ae),i.invalidateQueries({queryKey:N.issues.list(he)})}a(he),pn(),s(),l(we?`/${we}/issues/${Ae}`:`/issues/${Ae}`)}catch(Ne){S(Ne instanceof Error?Ne.message:"Failed to create task")}finally{_(!1)}}}function $n(Ne){Ne.key==="Enter"&&(Ne.metaKey||Ne.ctrlKey)&&(Ne.preventDefault(),g===1&&$.trim()?He():g===2&&T.trim()?rt():g===3&&D.trim()?Pt():g===4&&gn())}return f?e.jsx(Cs,{open:f,onOpenChange:Ne=>{Ne||(p(!0),re())},children:e.jsxs(I0,{children:[e.jsx("div",{className:"fixed inset-0 z-50 bg-background"}),e.jsxs("div",{className:"fixed inset-0 z-50 flex",onKeyDown:$n,children:[e.jsxs("button",{onClick:re,className:"absolute top-4 left-4 z-10 rounded-sm p-1.5 text-muted-foreground/60 hover:text-foreground transition-colors",children:[e.jsx(zt,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx("div",{className:O("w-full flex flex-col overflow-y-auto transition-[width] duration-500 ease-in-out",g===1?"md:w-1/2":"md:w-full"),children:e.jsxs("div",{className:"w-full max-w-md mx-auto my-auto px-8 py-12 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-0 mb-8 border-b border-border",children:[{step:1,label:"Company",icon:xc},{step:2,label:"Agent",icon:ss},{step:3,label:"Task",icon:Ki},{step:4,label:"Launch",icon:hm}].map(({step:Ne,label:te,icon:Ae})=>e.jsxs("button",{type:"button",onClick:()=>y(Ne),className:O("flex items-center gap-1.5 px-3 py-2 text-xs font-medium border-b-2 -mb-px transition-colors cursor-pointer",Ne===g?"border-foreground text-foreground":"border-transparent text-muted-foreground hover:text-foreground/70 hover:border-border"),children:[e.jsx(Ae,{className:"h-3.5 w-3.5"}),te]},Ne))}),g===1&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[e.jsx("div",{className:"bg-muted/50 p-2",children:e.jsx(xc,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Name your company"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is the organization your agents will work for."})]})]}),e.jsxs("div",{className:"mt-3 group",children:[e.jsx("label",{className:O("text-xs mb-1 block transition-colors",$.trim()?"text-foreground":"text-muted-foreground group-focus-within:text-foreground"),children:"Company name"}),e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",placeholder:"Acme Corp",value:$,onChange:Ne=>C(Ne.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"group",children:[e.jsx("label",{className:O("text-xs mb-1 block transition-colors",I.trim()?"text-foreground":"text-muted-foreground group-focus-within:text-foreground"),children:"Mission / goal (optional)"}),e.jsx("textarea",{className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50 resize-none min-h-[60px]",placeholder:"What is this company trying to achieve?",value:I,onChange:Ne=>K(Ne.target.value)})]})]}),g===2&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[e.jsx("div",{className:"bg-muted/50 p-2",children:e.jsx(ss,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Create your first agent"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose how this agent will run tasks."})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Agent name"}),e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",placeholder:"CEO",value:T,onChange:Ne=>z(Ne.target.value),autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-2 block",children:"Adapter type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"claude_local",label:"Claude Code",icon:xo,desc:"Local Claude agent",recommended:!0},{value:"codex_local",label:"Codex",icon:_p,desc:"Local Codex agent",recommended:!0}].map(Ne=>e.jsxs("button",{className:O("flex flex-col items-center gap-1.5 rounded-md border p-3 text-xs transition-colors relative",w===Ne.value?"border-foreground bg-accent":"border-border hover:bg-accent/50"),onClick:()=>{const te=Ne.value;F(te),te==="codex_local"&&!A&&R(ii),te!=="codex_local"&&R("")},children:[Ne.recommended&&e.jsx("span",{className:"absolute -top-1.5 right-1.5 bg-green-500 text-white text-[9px] font-semibold px-1.5 py-0.5 rounded-full leading-none",children:"Recommended"}),e.jsx(Ne.icon,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:Ne.label}),e.jsx("span",{className:"text-muted-foreground text-[10px]",children:Ne.desc})]},Ne.value))}),e.jsxs("button",{className:"flex items-center gap-1.5 mt-3 text-xs text-muted-foreground hover:text-foreground transition-colors",onClick:()=>q(Ne=>!Ne),children:[e.jsx(rn,{className:O("h-3 w-3 transition-transform",Le?"rotate-0":"-rotate-90")}),"More Agent Adapter Types"]}),Le&&e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[{value:"gemini_local",label:"Gemini CLI",icon:Sp,desc:"Local Gemini agent"},{value:"opencode_local",label:"OpenCode",icon:Yc,desc:"Local multi-provider agent"},{value:"pi_local",label:"Pi",icon:kd,desc:"Local Pi agent"},{value:"cursor",label:"Cursor",icon:Zb,desc:"Local Cursor agent"},{value:"hermes_local",label:"Hermes Agent",icon:q0,desc:"Local multi-provider agent"},{value:"openclaw_gateway",label:"OpenClaw Gateway",icon:ss,desc:"Invoke OpenClaw via gateway protocol",comingSoon:!0,disabledLabel:"Configure OpenClaw within the App"}].map(Ne=>e.jsxs("button",{disabled:!!Ne.comingSoon,className:O("flex flex-col items-center gap-1.5 rounded-md border p-3 text-xs transition-colors relative",Ne.comingSoon?"border-border opacity-40 cursor-not-allowed":w===Ne.value?"border-foreground bg-accent":"border-border hover:bg-accent/50"),onClick:()=>{if(Ne.comingSoon)return;const te=Ne.value;if(F(te),te==="gemini_local"&&!A){R(ci);return}if(te==="cursor"&&!A){R(li);return}if(te==="opencode_local"){A.includes("/")||R("");return}R("")},children:[e.jsx(Ne.icon,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:Ne.label}),e.jsx("span",{className:"text-muted-foreground text-[10px]",children:Ne.comingSoon?Ne.disabledLabel??"Coming soon":Ne.desc})]},Ne.value))})]}),(w==="claude_local"||w==="codex_local"||w==="gemini_local"||w==="hermes_local"||w==="opencode_local"||w==="pi_local"||w==="cursor")&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Model"}),e.jsxs(Ht,{open:M,onOpenChange:Ne=>{B(Ne),Ne||L("")},children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[e.jsx("span",{className:O(!A&&"text-muted-foreground"),children:pt?pt.label:A||(w==="opencode_local"?"Select model (required)":"Default")}),e.jsx(rn,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(Qt,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:[e.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search models...",value:k,onChange:Ne=>L(Ne.target.value),autoFocus:!0}),w!=="opencode_local"&&e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!A&&"bg-accent"),onClick:()=>{R(""),B(!1)},children:"Default"}),e.jsx("div",{className:"max-h-[240px] overflow-y-auto",children:hn.map(Ne=>e.jsxs("div",{className:"mb-1 last:mb-0",children:[w==="opencode_local"&&e.jsxs("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:[Ne.provider," (",Ne.entries.length,")"]}),Ne.entries.map(te=>e.jsx("button",{className:O("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",te.id===A&&"bg-accent"),onClick:()=>{R(te.id),B(!1)},children:e.jsx("span",{className:"block w-full text-left truncate",title:te.id,children:w==="opencode_local"?M0(te.id):te.label})},te.id))]},Ne.provider))}),yt.length===0&&e.jsx("p",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No models discovered."})]})]})]})}),It&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Adapter environment check"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Runs a live probe that asks the adapter CLI to respond with hello."})]}),e.jsx(G,{size:"sm",variant:"outline",className:"h-7 px-2.5 text-xs",disabled:Ce,onClick:()=>void Ee(),children:Ce?"Testing...":"Test now"})]}),de&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-[11px] text-destructive",children:de}),J&&J.status==="pass"?e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10 px-3 py-2 text-xs text-green-700 dark:text-green-300 animate-in fade-in slide-in-from-bottom-1 duration-300",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"font-medium",children:"Passed"})]}):J?e.jsx(J$,{result:J}):null,ln&&e.jsxs("div",{className:"rounded-md border border-amber-300/60 bg-amber-50/40 px-2.5 py-2 space-y-2",children:[e.jsxs("p",{className:"text-[11px] text-amber-900/90 leading-relaxed",children:["Claude failed while"," ",e.jsx("span",{className:"font-mono",children:"ANTHROPIC_API_KEY"})," ","is set. You can clear it in this CEO adapter config and retry the probe."]}),e.jsx(G,{size:"sm",variant:"outline",className:"h-7 px-2.5 text-xs",disabled:Ce||Fe,onClick:()=>void xt(),children:Fe?"Retrying...":"Unset ANTHROPIC_API_KEY"})]}),J&&J.status==="fail"&&e.jsxs("div",{className:"rounded-md border border-border/70 bg-muted/20 px-2.5 py-2 text-[11px] space-y-1.5",children:[e.jsx("p",{className:"font-medium",children:"Manual debug"}),e.jsx("p",{className:"text-muted-foreground font-mono break-all",children:w==="cursor"?`${Ue} -p --mode ask --output-format json "Respond with hello."`:w==="codex_local"?`${Ue} exec --json -`:w==="gemini_local"?`${Ue} --output-format json "Respond with hello."`:w==="opencode_local"?`${Ue} run --format json "Respond with hello."`:`${Ue} --print - --output-format stream-json --verbose`}),e.jsxs("p",{className:"text-muted-foreground",children:["Prompt:"," ",e.jsx("span",{className:"font-mono",children:"Respond with hello."})]}),w==="cursor"||w==="codex_local"||w==="gemini_local"||w==="opencode_local"?e.jsxs("p",{className:"text-muted-foreground",children:["If auth fails, set"," ",e.jsx("span",{className:"font-mono",children:w==="cursor"?"CURSOR_API_KEY":w==="gemini_local"?"GEMINI_API_KEY":"OPENAI_API_KEY"})," ","in env or run"," ",e.jsx("span",{className:"font-mono",children:w==="cursor"?"agent login":w==="codex_local"?"codex login":w==="gemini_local"?"gemini auth":"opencode auth login"}),"."]}):e.jsxs("p",{className:"text-muted-foreground",children:["If login is required, run"," ",e.jsx("span",{className:"font-mono",children:"claude login"})," ","and retry."]})]})]}),(w==="http"||w==="openclaw_gateway")&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:w==="openclaw_gateway"?"Gateway URL":"Webhook URL"}),e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",placeholder:w==="openclaw_gateway"?"ws://127.0.0.1:18789":"https://...",value:V,onChange:Ne=>W(Ne.target.value)})]})]}),g===3&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[e.jsx("div",{className:"bg-muted/50 p-2",children:e.jsx(Ki,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Give it something to do"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Give your agent a small task to start with — a bug fix, a research question, writing a script."})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Task title"}),e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",placeholder:"e.g. Research competitor pricing",value:D,onChange:Ne=>ie(Ne.target.value),autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Description (optional)"}),e.jsx("textarea",{ref:Be,className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50 resize-none min-h-[120px] max-h-[300px] overflow-y-auto",placeholder:"Add more detail about what the agent should do...",value:Ie,onChange:Ne=>ue(Ne.target.value)})]})]}),g===4&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[e.jsx("div",{className:"bg-muted/50 p-2",children:e.jsx(hm,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Ready to launch"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Everything is set up. Launching now will create the starter task, wake the agent, and open the issue."})]})]}),e.jsxs("div",{className:"border border-border divide-y divide-border",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5",children:[e.jsx(xc,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:$}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Company"})]}),e.jsx(Nn,{className:"h-4 w-4 text-green-500 shrink-0"})]}),e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5",children:[e.jsx(ss,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:T}),e.jsx("p",{className:"text-xs text-muted-foreground",children:oo(w).label})]}),e.jsx(Nn,{className:"h-4 w-4 text-green-500 shrink-0"})]}),e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5",children:[e.jsx(Ki,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:D}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Task"})]}),e.jsx(Nn,{className:"h-4 w-4 text-green-500 shrink-0"})]})]})]}),E&&e.jsx("div",{className:"mt-3",children:e.jsx("p",{className:"text-xs text-destructive",children:E})}),e.jsxs("div",{className:"flex items-center justify-between mt-8",children:[e.jsx("div",{children:g>1&&g>(n.initialStep??1)&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>y(g-1),disabled:v,children:[e.jsx(fo,{className:"h-3.5 w-3.5 mr-1"}),"Back"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[g===1&&e.jsxs(G,{size:"sm",disabled:!$.trim()||v,onClick:He,children:[v?e.jsx(kn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Fo,{className:"h-3.5 w-3.5 mr-1"}),v?"Creating...":"Next"]}),g===2&&e.jsxs(G,{size:"sm",disabled:!T.trim()||v||Ce,onClick:rt,children:[v?e.jsx(kn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Fo,{className:"h-3.5 w-3.5 mr-1"}),v?"Creating...":"Next"]}),g===3&&e.jsxs(G,{size:"sm",disabled:!D.trim()||v,onClick:Pt,children:[v?e.jsx(kn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Fo,{className:"h-3.5 w-3.5 mr-1"}),v?"Creating...":"Next"]}),g===4&&e.jsxs(G,{size:"sm",disabled:v,onClick:gn,children:[v?e.jsx(kn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Fo,{className:"h-3.5 w-3.5 mr-1"}),v?"Creating...":"Create & Open Issue"]})]})]})]})}),e.jsx("div",{className:O("hidden md:block overflow-hidden bg-[#1d1d1d] transition-[width,opacity] duration-500 ease-in-out",g===1?"w-1/2 opacity-100":"w-0 opacity-0"),children:e.jsx(sw,{})})]})]})}):null}function J$({result:t}){const n=t.status==="pass"?"Passed":t.status==="warn"?"Warnings":"Failed",s=t.status==="pass"?"text-green-700 dark:text-green-300 border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10":t.status==="warn"?"text-amber-700 dark:text-amber-300 border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10":"text-red-700 dark:text-red-300 border-red-300 dark:border-red-500/40 bg-red-50 dark:bg-red-500/10";return e.jsxs("div",{className:`rounded-md border px-2.5 py-2 text-[11px] ${s}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:n}),e.jsx("span",{className:"opacity-80",children:new Date(t.testedAt).toLocaleTimeString()})]}),e.jsx("div",{className:"mt-1.5 space-y-1",children:t.checks.map((r,a)=>e.jsxs("div",{className:"leading-relaxed break-words",children:[e.jsx("span",{className:"font-medium uppercase tracking-wide opacity-80",children:r.level}),e.jsx("span",{className:"mx-1 opacity-60",children:"·"}),e.jsx("span",{children:r.message}),r.detail&&e.jsxs("span",{className:"block opacity-75 break-all",children:["(",r.detail,")"]}),r.hint&&e.jsxs("span",{className:"block opacity-90 break-words",children:["Hint: ",r.hint]})]},`${r.code}-${a}`))})]})}const ya={list:(t,n)=>{const s=new URLSearchParams;n!=null&&n.entityType&&s.set("entityType",n.entityType),n!=null&&n.entityId&&s.set("entityId",n.entityId),n!=null&&n.agentId&&s.set("agentId",n.agentId);const r=s.toString();return ne.get(`/companies/${t}/activity${r?`?${r}`:""}`)},forIssue:t=>ne.get(`/issues/${t}/activity`),runsForIssue:t=>ne.get(`/issues/${t}/runs`),issuesForRun:t=>ne.get(`/heartbeat-runs/${t}/issues`)};function ma({icon:t,value:n,label:s,description:r,to:a,onClick:o}){const i=!!(a||o),l=e.jsx("div",{className:`h-full px-4 py-4 sm:px-5 sm:py-5 rounded-lg transition-colors${i?" hover:bg-accent/50 cursor-pointer":""}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-2xl sm:text-3xl font-semibold tracking-tight tabular-nums",children:n}),e.jsx("p",{className:"text-xs sm:text-sm font-medium text-muted-foreground mt-1",children:s}),r&&e.jsx("div",{className:"text-xs text-muted-foreground/70 mt-1.5 hidden sm:block",children:r})]}),e.jsx(t,{className:"h-4 w-4 text-muted-foreground/50 shrink-0 mt-1.5"})]})});return a?e.jsx(Oe,{to:a,className:"no-underline text-inherit h-full",onClick:o,children:l}):o?e.jsx("div",{className:"h-full",onClick:o,children:l}):l}function tn({icon:t,message:n,action:s,onAction:r}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"bg-muted/50 p-4 mb-4",children:e.jsx(t,{className:"h-10 w-10 text-muted-foreground/50"})}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:n}),s&&r&&e.jsxs(G,{onClick:r,children:[e.jsx(Ot,{className:"h-4 w-4 mr-1.5"}),s]})]})}const Z$=["backlog","todo","in_progress","in_review","done","cancelled","blocked"];function Du(t){return t.replace(/_/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function Pn({status:t,onChange:n,className:s,showLabel:r}){const[a,o]=c.useState(!1),i=i3[t]??l3,l=t==="done",u=e.jsx("span",{className:O("relative inline-flex h-4 w-4 rounded-full border-2 shrink-0",i,n&&!r&&"cursor-pointer",s),children:l&&e.jsx("span",{className:"absolute inset-0 m-auto h-2 w-2 rounded-full bg-current"})});if(!n)return r?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[u,e.jsx("span",{className:"text-sm",children:Du(t)})]}):u;const d=r?e.jsxs("button",{className:"inline-flex items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",children:[u,e.jsx("span",{className:"text-sm",children:Du(t)})]}):u;return e.jsxs(Ht,{open:a,onOpenChange:o,children:[e.jsx(Vt,{asChild:!0,children:d}),e.jsx(Qt,{className:"w-40 p-1",align:"start",children:Z$.map(m=>e.jsxs(G,{variant:"ghost",size:"sm",className:O("w-full justify-start gap-2 text-xs",m===t&&"bg-accent"),onClick:()=>{n(m),o(!1)},children:[e.jsx(Pn,{status:m}),Du(m)]},m))})]})}const Xm=60,ep=60*Xm,sd=24*ep,Lh=7*sd,Fh=30*sd;function as(t){const n=Date.now(),s=new Date(t).getTime(),r=Math.round((n-s)/1e3);return r<Xm?"just now":r<ep?`${Math.floor(r/Xm)}m ago`:r<sd?`${Math.floor(r/ep)}h ago`:r<Lh?`${Math.floor(r/sd)}d ago`:r<Fh?`${Math.floor(r/Lh)}w ago`:`${Math.floor(r/Fh)}mo ago`}const Y$={"issue.created":"created","issue.updated":"updated","issue.checked_out":"checked out","issue.released":"released","issue.comment_added":"commented on","issue.attachment_added":"attached file to","issue.attachment_removed":"removed attachment from","issue.document_created":"created document for","issue.document_updated":"updated document on","issue.document_deleted":"deleted document from","issue.commented":"commented on","issue.deleted":"deleted","agent.created":"created","agent.updated":"updated","agent.paused":"paused","agent.resumed":"resumed","agent.terminated":"terminated","agent.key_created":"created API key for","agent.budget_updated":"updated budget for","agent.runtime_session_reset":"reset session for","heartbeat.invoked":"invoked heartbeat for","heartbeat.cancelled":"cancelled heartbeat for","approval.created":"requested approval","approval.approved":"approved","approval.rejected":"rejected","project.created":"created","project.updated":"updated","project.deleted":"deleted","goal.created":"created","goal.updated":"updated","goal.deleted":"deleted","cost.reported":"reported cost for","cost.recorded":"recorded cost for","company.created":"created company","company.updated":"updated company","company.archived":"archived","company.budget_updated":"updated budget for"};function Co(t){return typeof t!="string"?String(t??"none"):t.replace(/_/g," ")}function X$(t,n){if(t==="issue.updated"&&n){const s=n._previous??{};if(n.status!==void 0){const r=s.status;return r?`changed status from ${Co(r)} to ${Co(n.status)} on`:`changed status to ${Co(n.status)} on`}if(n.priority!==void 0){const r=s.priority;return r?`changed priority from ${Co(r)} to ${Co(n.priority)} on`:`changed priority to ${Co(n.priority)} on`}}return Y$[t]??t.replace(/[._]/g," ")}function e4(t,n,s){switch(t){case"issue":return`/issues/${s??n}`;case"agent":return`/agents/${n}`;case"project":return`/projects/${mx(s,n)}`;case"goal":return`/goals/${n}`;case"approval":return`/approvals/${n}`;default:return null}}function rw({event:t,agentMap:n,entityNameMap:s,entityTitleMap:r,className:a}){var j;const o=X$(t.action,t.details),i=t.entityType==="heartbeat_run",l=i?(j=t.details)==null?void 0:j.agentId:void 0,u=i?l?s.get(`agent:${l}`):null:s.get(`${t.entityType}:${t.entityId}`),d=r==null?void 0:r.get(`${t.entityType}:${t.entityId}`),m=i&&l?`/agents/${l}/runs/${t.entityId}`:e4(t.entityType,t.entityId,u),p=t.actorType==="agent"?n.get(t.actorId):null,x=(p==null?void 0:p.name)??(t.actorType==="system"?"System":t.actorType==="user"?"Board":t.actorId||"Unknown"),f=e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("p",{className:"flex-1 min-w-0 truncate",children:[e.jsx(Ut,{name:x,size:"xs",className:"align-baseline"}),e.jsxs("span",{className:"text-muted-foreground ml-1",children:[o," "]}),u&&e.jsx("span",{className:"font-medium",children:u}),d&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["— ",d]})]}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0 pt-0.5",children:as(t.createdAt)})]}),h=O("px-4 py-2 text-sm",m&&"cursor-pointer hover:bg-accent/50 transition-colors",a);return m?e.jsx(Oe,{to:m,className:O(h,"no-underline text-inherit block"),children:f}):e.jsx("div",{className:h,children:f})}function t4(t,n){const s={};return(t[t.length-1]===""?[...t,""]:t).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const n4=/[ \t\n\f\r]/g;function s4(t){return typeof t=="object"?t.type==="text"?qh(t.value):!1:qh(t)}function qh(t){return t.replace(n4,"")===""}class Ll{constructor(n,s,r){this.normal=s,this.property=n,r&&(this.space=r)}}Ll.prototype.normal={};Ll.prototype.property={};Ll.prototype.space=void 0;function aw(t,n){const s={},r={};for(const a of t)Object.assign(s,a.property),Object.assign(r,a.normal);return new Ll(s,r,n)}function tp(t){return t.toLowerCase()}class Es{constructor(n,s){this.attribute=s,this.property=n}}Es.prototype.attribute="";Es.prototype.booleanish=!1;Es.prototype.boolean=!1;Es.prototype.commaOrSpaceSeparated=!1;Es.prototype.commaSeparated=!1;Es.prototype.defined=!1;Es.prototype.mustUseProperty=!1;Es.prototype.number=!1;Es.prototype.overloadedBoolean=!1;Es.prototype.property="";Es.prototype.spaceSeparated=!1;Es.prototype.space=void 0;let r4=0;const vt=vo(),Tn=vo(),np=vo(),De=vo(),cn=vo(),Qo=vo(),Ms=vo();function vo(){return 2**++r4}const sp=Object.freeze(Object.defineProperty({__proto__:null,boolean:vt,booleanish:Tn,commaOrSpaceSeparated:Ms,commaSeparated:Qo,number:De,overloadedBoolean:np,spaceSeparated:cn},Symbol.toStringTag,{value:"Module"})),Ou=Object.keys(sp);class zx extends Es{constructor(n,s,r,a){let o=-1;if(super(n,s),Uh(this,"space",a),typeof r=="number")for(;++o<Ou.length;){const i=Ou[o];Uh(this,Ou[o],(r&sp[i])===sp[i])}}}zx.prototype.defined=!0;function Uh(t,n,s){s&&(t[n]=s)}function wi(t){const n={},s={};for(const[r,a]of Object.entries(t.properties)){const o=new zx(r,t.transform(t.attributes||{},r),a,t.space);t.mustUseProperty&&t.mustUseProperty.includes(r)&&(o.mustUseProperty=!0),n[r]=o,s[tp(r)]=r,s[tp(o.attribute)]=r}return new Ll(n,s,t.space)}const ow=wi({properties:{ariaActiveDescendant:null,ariaAtomic:Tn,ariaAutoComplete:null,ariaBusy:Tn,ariaChecked:Tn,ariaColCount:De,ariaColIndex:De,ariaColSpan:De,ariaControls:cn,ariaCurrent:null,ariaDescribedBy:cn,ariaDetails:null,ariaDisabled:Tn,ariaDropEffect:cn,ariaErrorMessage:null,ariaExpanded:Tn,ariaFlowTo:cn,ariaGrabbed:Tn,ariaHasPopup:null,ariaHidden:Tn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:cn,ariaLevel:De,ariaLive:null,ariaModal:Tn,ariaMultiLine:Tn,ariaMultiSelectable:Tn,ariaOrientation:null,ariaOwns:cn,ariaPlaceholder:null,ariaPosInSet:De,ariaPressed:Tn,ariaReadOnly:Tn,ariaRelevant:null,ariaRequired:Tn,ariaRoleDescription:cn,ariaRowCount:De,ariaRowIndex:De,ariaRowSpan:De,ariaSelected:Tn,ariaSetSize:De,ariaSort:null,ariaValueMax:De,ariaValueMin:De,ariaValueNow:De,ariaValueText:null,role:null},transform(t,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function iw(t,n){return n in t?t[n]:n}function lw(t,n){return iw(t,n.toLowerCase())}const a4=wi({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Qo,acceptCharset:cn,accessKey:cn,action:null,allow:null,allowFullScreen:vt,allowPaymentRequest:vt,allowUserMedia:vt,alt:null,as:null,async:vt,autoCapitalize:null,autoComplete:cn,autoFocus:vt,autoPlay:vt,blocking:cn,capture:null,charSet:null,checked:vt,cite:null,className:cn,cols:De,colSpan:null,content:null,contentEditable:Tn,controls:vt,controlsList:cn,coords:De|Qo,crossOrigin:null,data:null,dateTime:null,decoding:null,default:vt,defer:vt,dir:null,dirName:null,disabled:vt,download:np,draggable:Tn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:vt,formTarget:null,headers:cn,height:De,hidden:np,high:De,href:null,hrefLang:null,htmlFor:cn,httpEquiv:cn,id:null,imageSizes:null,imageSrcSet:null,inert:vt,inputMode:null,integrity:null,is:null,isMap:vt,itemId:null,itemProp:cn,itemRef:cn,itemScope:vt,itemType:cn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:vt,low:De,manifest:null,max:null,maxLength:De,media:null,method:null,min:null,minLength:De,multiple:vt,muted:vt,name:null,nonce:null,noModule:vt,noValidate:vt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:vt,optimum:De,pattern:null,ping:cn,placeholder:null,playsInline:vt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:vt,referrerPolicy:null,rel:cn,required:vt,reversed:vt,rows:De,rowSpan:De,sandbox:cn,scope:null,scoped:vt,seamless:vt,selected:vt,shadowRootClonable:vt,shadowRootDelegatesFocus:vt,shadowRootMode:null,shape:null,size:De,sizes:null,slot:null,span:De,spellCheck:Tn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:De,step:null,style:null,tabIndex:De,target:null,title:null,translate:null,type:null,typeMustMatch:vt,useMap:null,value:Tn,width:De,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:cn,axis:null,background:null,bgColor:null,border:De,borderColor:null,bottomMargin:De,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:vt,declare:vt,event:null,face:null,frame:null,frameBorder:null,hSpace:De,leftMargin:De,link:null,longDesc:null,lowSrc:null,marginHeight:De,marginWidth:De,noResize:vt,noHref:vt,noShade:vt,noWrap:vt,object:null,profile:null,prompt:null,rev:null,rightMargin:De,rules:null,scheme:null,scrolling:Tn,standby:null,summary:null,text:null,topMargin:De,valueType:null,version:null,vAlign:null,vLink:null,vSpace:De,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:vt,disableRemotePlayback:vt,prefix:null,property:null,results:De,security:null,unselectable:null},space:"html",transform:lw}),o4=wi({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ms,accentHeight:De,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:De,amplitude:De,arabicForm:null,ascent:De,attributeName:null,attributeType:null,azimuth:De,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:De,by:null,calcMode:null,capHeight:De,className:cn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:De,diffuseConstant:De,direction:null,display:null,dur:null,divisor:De,dominantBaseline:null,download:vt,dx:null,dy:null,edgeMode:null,editable:null,elevation:De,enableBackground:null,end:null,event:null,exponent:De,externalResourcesRequired:null,fill:null,fillOpacity:De,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Qo,g2:Qo,glyphName:Qo,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:De,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:De,horizOriginX:De,horizOriginY:De,id:null,ideographic:De,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:De,k:De,k1:De,k2:De,k3:De,k4:De,kernelMatrix:Ms,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:De,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:De,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:De,overlineThickness:De,paintOrder:null,panose1:null,path:null,pathLength:De,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:cn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:De,pointsAtY:De,pointsAtZ:De,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ms,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ms,rev:Ms,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ms,requiredFeatures:Ms,requiredFonts:Ms,requiredFormats:Ms,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:De,specularExponent:De,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:De,strikethroughThickness:De,string:null,stroke:null,strokeDashArray:Ms,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:De,strokeOpacity:De,strokeWidth:null,style:null,surfaceScale:De,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ms,tabIndex:De,tableValues:null,target:null,targetX:De,targetY:De,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ms,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:De,underlineThickness:De,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:De,values:null,vAlphabetic:De,vMathematical:De,vectorEffect:null,vHanging:De,vIdeographic:De,version:null,vertAdvY:De,vertOriginX:De,vertOriginY:De,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:De,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:iw}),cw=wi({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,n){return"xlink:"+n.slice(5).toLowerCase()}}),dw=wi({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:lw}),uw=wi({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,n){return"xml:"+n.slice(3).toLowerCase()}}),i4={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},l4=/[A-Z]/g,Bh=/-[a-z]/g,c4=/^data[-\w.:]+$/i;function d4(t,n){const s=tp(n);let r=n,a=Es;if(s in t.normal)return t.property[t.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&c4.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Bh,m4);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Bh.test(o)){let i=o.replace(l4,u4);i.charAt(0)!=="-"&&(i="-"+i),n="data"+i}}a=zx}return new a(r,n)}function u4(t){return"-"+t.toLowerCase()}function m4(t){return t.charAt(1).toUpperCase()}const p4=aw([ow,a4,cw,dw,uw],"html"),Wx=aw([ow,o4,cw,dw,uw],"svg");function x4(t){return t.join(" ").trim()}var So={},Lu,Kh;function f4(){if(Kh)return Lu;Kh=1;var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,i=/^[;\s]*/,l=/^\s+|\s+$/g,u=`
|
|
57
|
+
`,d="/",m="*",p="",x="comment",f="declaration";function h(b,g){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];g=g||{};var y=1,v=1;function _(K){var T=K.match(n);T&&(y+=T.length);var z=K.lastIndexOf(u);v=~z?K.length-z:v+K.length}function E(){var K={line:y,column:v};return function(T){return T.position=new S(K),k(),T}}function S(K){this.start=K,this.end={line:y,column:v},this.source=g.source}S.prototype.content=b;function M(K){var T=new Error(g.source+":"+y+":"+v+": "+K);if(T.reason=K,T.filename=g.source,T.line=y,T.column=v,T.source=b,!g.silent)throw T}function B(K){var T=K.exec(b);if(T){var z=T[0];return _(z),b=b.slice(z.length),T}}function k(){B(s)}function L(K){var T;for(K=K||[];T=$();)T!==!1&&K.push(T);return K}function $(){var K=E();if(!(d!=b.charAt(0)||m!=b.charAt(1))){for(var T=2;p!=b.charAt(T)&&(m!=b.charAt(T)||d!=b.charAt(T+1));)++T;if(T+=2,p===b.charAt(T-1))return M("End of comment missing");var z=b.slice(2,T-2);return v+=2,_(z),b=b.slice(T),v+=2,K({type:x,comment:z})}}function C(){var K=E(),T=B(r);if(T){if($(),!B(a))return M("property missing ':'");var z=B(o),w=K({type:f,property:j(T[0].replace(t,p)),value:z?j(z[0].replace(t,p)):p});return B(i),w}}function I(){var K=[];L(K);for(var T;T=C();)T!==!1&&(K.push(T),L(K));return K}return k(),I()}function j(b){return b?b.replace(l,p):p}return Lu=h,Lu}var zh;function h4(){if(zh)return So;zh=1;var t=So&&So.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(So,"__esModule",{value:!0}),So.default=s;const n=t(f4());function s(r,a){let o=null;if(!r||typeof r!="string")return o;const i=(0,n.default)(r),l=typeof a=="function";return i.forEach(u=>{if(u.type!=="declaration")return;const{property:d,value:m}=u;l?a(d,m,u):m&&(o=o||{},o[d]=m)}),o}return So}var Ti={},Wh;function g4(){if(Wh)return Ti;Wh=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(d){return!d||s.test(d)||t.test(d)},i=function(d,m){return m.toUpperCase()},l=function(d,m){return"".concat(m,"-")},u=function(d,m){return m===void 0&&(m={}),o(d)?d:(d=d.toLowerCase(),m.reactCompat?d=d.replace(a,l):d=d.replace(r,l),d.replace(n,i))};return Ti.camelCase=u,Ti}var Ri,Hh;function b4(){if(Hh)return Ri;Hh=1;var t=Ri&&Ri.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},n=t(h4()),s=g4();function r(a,o){var i={};return!a||typeof a!="string"||(0,n.default)(a,function(l,u){l&&u&&(i[(0,s.camelCase)(l,o)]=u)}),i}return r.default=r,Ri=r,Ri}var y4=b4();const v4=Pb(y4),mw=pw("end"),Hx=pw("start");function pw(t){return n;function n(s){const r=s&&s.position&&s.position[t]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function j4(t){const n=Hx(t),s=mw(t);if(n&&s)return{start:n,end:s}}const Vx={}.hasOwnProperty,w4=new Map,N4=/[A-Z]/g,k4=new Set(["table","tbody","thead","tfoot","tr"]),C4=new Set(["td","th"]),xw="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function S4(t,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let r;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=M4(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=P4(s,n.jsx,n.jsxs)}const a={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:r,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Wx:p4,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=fw(a,t,void 0);return o&&typeof o!="string"?o:a.create(t,a.Fragment,{children:o||void 0},void 0)}function fw(t,n,s){if(n.type==="element")return I4(t,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return _4(t,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return E4(t,n,s);if(n.type==="mdxjsEsm")return A4(t,n);if(n.type==="root")return T4(t,n,s);if(n.type==="text")return R4(t,n)}function I4(t,n,s){const r=t.schema;let a=r;n.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=Wx,t.schema=a),t.ancestors.push(n);const o=gw(t,n.tagName,!1),i=$4(t,n);let l=Gx(t,n);return k4.has(n.tagName)&&(l=l.filter(function(u){return typeof u=="string"?!s4(u):!0})),hw(t,i,o,n),Qx(i,l),t.ancestors.pop(),t.schema=r,t.create(n,o,i,s)}function _4(t,n){if(n.data&&n.data.estree&&t.evaluater){const r=n.data.estree.body[0];return da(r.type==="ExpressionStatement"),t.evaluater.evaluateExpression(r.expression)}hl(t,n.position)}function A4(t,n){if(n.data&&n.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(n.data.estree);hl(t,n.position)}function E4(t,n,s){const r=t.schema;let a=r;n.name==="svg"&&r.space==="html"&&(a=Wx,t.schema=a),t.ancestors.push(n);const o=n.name===null?t.Fragment:gw(t,n.name,!0),i=D4(t,n),l=Gx(t,n);return hw(t,i,o,n),Qx(i,l),t.ancestors.pop(),t.schema=r,t.create(n,o,i,s)}function T4(t,n,s){const r={};return Qx(r,Gx(t,n)),t.create(n,t.Fragment,r,s)}function R4(t,n){return n.value}function hw(t,n,s,r){typeof s!="string"&&s!==t.Fragment&&t.passNode&&(n.node=r)}function Qx(t,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(t.children=s)}}function P4(t,n,s){return r;function r(a,o,i,l){const d=Array.isArray(i.children)?s:n;return l?d(o,i,l):d(o,i)}}function M4(t,n){return s;function s(r,a,o,i){const l=Array.isArray(o.children),u=Hx(r);return n(a,o,i,l,{columnNumber:u?u.column-1:void 0,fileName:t,lineNumber:u?u.line:void 0},void 0)}}function $4(t,n){const s={};let r,a;for(a in n.properties)if(a!=="children"&&Vx.call(n.properties,a)){const o=O4(t,a,n.properties[a]);if(o){const[i,l]=o;t.tableCellAlignToStyle&&i==="align"&&typeof l=="string"&&C4.has(n.tagName)?r=l:s[i]=l}}if(r){const o=s.style||(s.style={});o[t.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return s}function D4(t,n){const s={};for(const r of n.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&t.evaluater){const o=r.data.estree.body[0];da(o.type==="ExpressionStatement");const i=o.expression;da(i.type==="ObjectExpression");const l=i.properties[0];da(l.type==="SpreadElement"),Object.assign(s,t.evaluater.evaluateExpression(l.argument))}else hl(t,n.position);else{const a=r.name;let o;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&t.evaluater){const l=r.value.data.estree.body[0];da(l.type==="ExpressionStatement"),o=t.evaluater.evaluateExpression(l.expression)}else hl(t,n.position);else o=r.value===null?!0:r.value;s[a]=o}return s}function Gx(t,n){const s=[];let r=-1;const a=t.passKeys?new Map:w4;for(;++r<n.children.length;){const o=n.children[r];let i;if(t.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const d=a.get(u)||0;i=u+"-"+d,a.set(u,d+1)}}const l=fw(t,o,i);l!==void 0&&s.push(l)}return s}function O4(t,n,s){const r=d4(t.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=r.commaSeparated?t4(s):x4(s)),r.property==="style"){let a=typeof s=="object"?s:L4(t,String(s));return t.stylePropertyNameCase==="css"&&(a=F4(a)),["style",a]}return[t.elementAttributeNameCase==="react"&&r.space?i4[r.property]||r.property:r.attribute,s]}}function L4(t,n){try{return v4(n,{reactCompat:!0})}catch(s){if(t.ignoreInvalidStyle)return{};const r=s,a=new wp("Cannot parse `style` attribute",{ancestors:t.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=t.filePath||void 0,a.url=xw+"#cannot-parse-style-attribute",a}}function gw(t,n,s){let r;if(!s)r={type:"Literal",value:n};else if(n.includes(".")){const a=n.split(".");let o=-1,i;for(;++o<a.length;){const l=yf(a[o])?{type:"Identifier",name:a[o]}:{type:"Literal",value:a[o]};i=i?{type:"MemberExpression",object:i,property:l,computed:!!(o&&l.type==="Literal"),optional:!1}:l}r=i}else r=yf(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(r.type==="Literal"){const a=r.value;return Vx.call(t.components,a)?t.components[a]:a}if(t.evaluater)return t.evaluater.evaluateExpression(r);hl(t)}function hl(t,n){const s=new wp("Cannot handle MDX estrees without `createEvaluater`",{ancestors:t.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=t.filePath||void 0,s.url=xw+"#cannot-handle-mdx-estrees-without-createevaluater",s}function F4(t){const n={};let s;for(s in t)Vx.call(t,s)&&(n[q4(s)]=t[s]);return n}function q4(t){let n=t.replace(N4,U4);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function U4(t){return"-"+t.toLowerCase()}const Fu={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]};function B4(t){const n=this;n.parser=s;function s(r){return hC(r,{...n.data("settings"),...t,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function K4(t,n){const s={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(n),!0)};return t.patch(n,s),t.applyData(n,s)}function z4(t,n){const s={type:"element",tagName:"br",properties:{},children:[]};return t.patch(n,s),[t.applyData(n,s),{type:"text",value:`
|
|
58
|
+
`}]}function W4(t,n){const s=n.value?n.value+`
|
|
59
|
+
`:"",r={},a=n.lang?n.lang.split(/\s+/):[];a.length>0&&(r.className=["language-"+a[0]]);let o={type:"element",tagName:"code",properties:r,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),t.patch(n,o),o=t.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},t.patch(n,o),o}function H4(t,n){const s={type:"element",tagName:"del",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function V4(t,n){const s={type:"element",tagName:"em",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function Q4(t,n){const s=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",r=String(n.identifier).toUpperCase(),a=mi(r.toLowerCase()),o=t.footnoteOrder.indexOf(r);let i,l=t.footnoteCounts.get(r);l===void 0?(l=0,t.footnoteOrder.push(r),i=t.footnoteOrder.length):i=o+1,l+=1,t.footnoteCounts.set(r,l);const u={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+a,id:s+"fnref-"+a+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(i)}]};t.patch(n,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return t.patch(n,d),t.applyData(n,d)}function G4(t,n){const s={type:"element",tagName:"h"+n.depth,properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function J4(t,n){if(t.options.allowDangerousHtml){const s={type:"raw",value:n.value};return t.patch(n,s),t.applyData(n,s)}}function bw(t,n){const s=n.referenceType;let r="]";if(s==="collapsed"?r+="[]":s==="full"&&(r+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+r}];const a=t.all(n),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const i=a[a.length-1];return i&&i.type==="text"?i.value+=r:a.push({type:"text",value:r}),a}function Z4(t,n){const s=String(n.identifier).toUpperCase(),r=t.definitionById.get(s);if(!r)return bw(t,n);const a={src:mi(r.url||""),alt:n.alt};r.title!==null&&r.title!==void 0&&(a.title=r.title);const o={type:"element",tagName:"img",properties:a,children:[]};return t.patch(n,o),t.applyData(n,o)}function Y4(t,n){const s={src:mi(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const r={type:"element",tagName:"img",properties:s,children:[]};return t.patch(n,r),t.applyData(n,r)}function X4(t,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};t.patch(n,s);const r={type:"element",tagName:"code",properties:{},children:[s]};return t.patch(n,r),t.applyData(n,r)}function eD(t,n){const s=String(n.identifier).toUpperCase(),r=t.definitionById.get(s);if(!r)return bw(t,n);const a={href:mi(r.url||"")};r.title!==null&&r.title!==void 0&&(a.title=r.title);const o={type:"element",tagName:"a",properties:a,children:t.all(n)};return t.patch(n,o),t.applyData(n,o)}function tD(t,n){const s={href:mi(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const r={type:"element",tagName:"a",properties:s,children:t.all(n)};return t.patch(n,r),t.applyData(n,r)}function nD(t,n,s){const r=t.all(n),a=s?sD(s):yw(n),o={},i=[];if(typeof n.checked=="boolean"){const m=r[0];let p;m&&m.type==="element"&&m.tagName==="p"?p=m:(p={type:"element",tagName:"p",properties:{},children:[]},r.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let l=-1;for(;++l<r.length;){const m=r[l];(a||l!==0||m.type!=="element"||m.tagName!=="p")&&i.push({type:"text",value:`
|
|
60
|
+
`}),m.type==="element"&&m.tagName==="p"&&!a?i.push(...m.children):i.push(m)}const u=r[r.length-1];u&&(a||u.type!=="element"||u.tagName!=="p")&&i.push({type:"text",value:`
|
|
61
|
+
`});const d={type:"element",tagName:"li",properties:o,children:i};return t.patch(n,d),t.applyData(n,d)}function sD(t){let n=!1;if(t.type==="list"){n=t.spread||!1;const s=t.children;let r=-1;for(;!n&&++r<s.length;)n=yw(s[r])}return n}function yw(t){const n=t.spread;return n??t.children.length>1}function rD(t,n){const s={},r=t.all(n);let a=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++a<r.length;){const i=r[a];if(i.type==="element"&&i.tagName==="li"&&i.properties&&Array.isArray(i.properties.className)&&i.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const o={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:t.wrap(r,!0)};return t.patch(n,o),t.applyData(n,o)}function aD(t,n){const s={type:"element",tagName:"p",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function oD(t,n){const s={type:"root",children:t.wrap(t.all(n))};return t.patch(n,s),t.applyData(n,s)}function iD(t,n){const s={type:"element",tagName:"strong",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function lD(t,n){const s=t.all(n),r=s.shift(),a=[];if(r){const i={type:"element",tagName:"thead",properties:{},children:t.wrap([r],!0)};t.patch(n.children[0],i),a.push(i)}if(s.length>0){const i={type:"element",tagName:"tbody",properties:{},children:t.wrap(s,!0)},l=Hx(n.children[1]),u=mw(n.children[n.children.length-1]);l&&u&&(i.position={start:l,end:u}),a.push(i)}const o={type:"element",tagName:"table",properties:{},children:t.wrap(a,!0)};return t.patch(n,o),t.applyData(n,o)}function cD(t,n,s){const r=s?s.children:void 0,o=(r?r.indexOf(n):1)===0?"th":"td",i=s&&s.type==="table"?s.align:void 0,l=i?i.length:n.children.length;let u=-1;const d=[];for(;++u<l;){const p=n.children[u],x={},f=i?i[u]:void 0;f&&(x.align=f);let h={type:"element",tagName:o,properties:x,children:[]};p&&(h.children=t.all(p),t.patch(p,h),h=t.applyData(p,h)),d.push(h)}const m={type:"element",tagName:"tr",properties:{},children:t.wrap(d,!0)};return t.patch(n,m),t.applyData(n,m)}function dD(t,n){const s={type:"element",tagName:"td",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}const Vh=9,Qh=32;function uD(t){const n=String(t),s=/\r?\n|\r/g;let r=s.exec(n),a=0;const o=[];for(;r;)o.push(Gh(n.slice(a,r.index),a>0,!0),r[0]),a=r.index+r[0].length,r=s.exec(n);return o.push(Gh(n.slice(a),a>0,!1)),o.join("")}function Gh(t,n,s){let r=0,a=t.length;if(n){let o=t.codePointAt(r);for(;o===Vh||o===Qh;)r++,o=t.codePointAt(r)}if(s){let o=t.codePointAt(a-1);for(;o===Vh||o===Qh;)a--,o=t.codePointAt(a-1)}return a>r?t.slice(r,a):""}function mD(t,n){const s={type:"text",value:uD(String(n.value))};return t.patch(n,s),t.applyData(n,s)}function pD(t,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(n,s),t.applyData(n,s)}const xD={blockquote:K4,break:z4,code:W4,delete:H4,emphasis:V4,footnoteReference:Q4,heading:G4,html:J4,imageReference:Z4,image:Y4,inlineCode:X4,linkReference:eD,link:tD,listItem:nD,list:rD,paragraph:aD,root:oD,strong:iD,table:lD,tableCell:dD,tableRow:cD,text:mD,thematicBreak:pD,toml:Xl,yaml:Xl,definition:Xl,footnoteDefinition:Xl};function Xl(){}const vw=-1,nu=0,Qi=1,rd=2,Jx=3,Zx=4,Yx=5,Xx=6,jw=7,ww=8,Jh=typeof self=="object"?self:globalThis,fD=(t,n)=>{const s=(a,o)=>(t.set(o,a),a),r=a=>{if(t.has(a))return t.get(a);const[o,i]=n[a];switch(o){case nu:case vw:return s(i,a);case Qi:{const l=s([],a);for(const u of i)l.push(r(u));return l}case rd:{const l=s({},a);for(const[u,d]of i)l[r(u)]=r(d);return l}case Jx:return s(new Date(i),a);case Zx:{const{source:l,flags:u}=i;return s(new RegExp(l,u),a)}case Yx:{const l=s(new Map,a);for(const[u,d]of i)l.set(r(u),r(d));return l}case Xx:{const l=s(new Set,a);for(const u of i)l.add(r(u));return l}case jw:{const{name:l,message:u}=i;return s(new Jh[l](u),a)}case ww:return s(BigInt(i),a);case"BigInt":return s(Object(BigInt(i)),a);case"ArrayBuffer":return s(new Uint8Array(i).buffer,i);case"DataView":{const{buffer:l}=new Uint8Array(i);return s(new DataView(l),i)}}return s(new Jh[o](i),a)};return r},Zh=t=>fD(new Map,t)(0),Io="",{toString:hD}={},{keys:gD}=Object,Pi=t=>{const n=typeof t;if(n!=="object"||!t)return[nu,n];const s=hD.call(t).slice(8,-1);switch(s){case"Array":return[Qi,Io];case"Object":return[rd,Io];case"Date":return[Jx,Io];case"RegExp":return[Zx,Io];case"Map":return[Yx,Io];case"Set":return[Xx,Io];case"DataView":return[Qi,s]}return s.includes("Array")?[Qi,s]:s.includes("Error")?[jw,s]:[rd,s]},ec=([t,n])=>t===nu&&(n==="function"||n==="symbol"),bD=(t,n,s,r)=>{const a=(i,l)=>{const u=r.push(i)-1;return s.set(l,u),u},o=i=>{if(s.has(i))return s.get(i);let[l,u]=Pi(i);switch(l){case nu:{let m=i;switch(u){case"bigint":l=ww,m=i.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return a([vw],i)}return a([l,m],i)}case Qi:{if(u){let x=i;return u==="DataView"?x=new Uint8Array(i.buffer):u==="ArrayBuffer"&&(x=new Uint8Array(i)),a([u,[...x]],i)}const m=[],p=a([l,m],i);for(const x of i)m.push(o(x));return p}case rd:{if(u)switch(u){case"BigInt":return a([u,i.toString()],i);case"Boolean":case"Number":case"String":return a([u,i.valueOf()],i)}if(n&&"toJSON"in i)return o(i.toJSON());const m=[],p=a([l,m],i);for(const x of gD(i))(t||!ec(Pi(i[x])))&&m.push([o(x),o(i[x])]);return p}case Jx:return a([l,i.toISOString()],i);case Zx:{const{source:m,flags:p}=i;return a([l,{source:m,flags:p}],i)}case Yx:{const m=[],p=a([l,m],i);for(const[x,f]of i)(t||!(ec(Pi(x))||ec(Pi(f))))&&m.push([o(x),o(f)]);return p}case Xx:{const m=[],p=a([l,m],i);for(const x of i)(t||!ec(Pi(x)))&&m.push(o(x));return p}}const{message:d}=i;return a([l,{name:u,message:d}],i)};return o},Yh=(t,{json:n,lossy:s}={})=>{const r=[];return bD(!(n||s),!!n,new Map,r)(t),r},ad=typeof structuredClone=="function"?(t,n)=>n&&("json"in n||"lossy"in n)?Zh(Yh(t,n)):structuredClone(t):(t,n)=>Zh(Yh(t,n));function yD(t,n){const s=[{type:"text",value:"↩"}];return n>1&&s.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(n)}]}),s}function vD(t,n){return"Back to reference "+(t+1)+(n>1?"-"+n:"")}function jD(t){const n=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",s=t.options.footnoteBackContent||yD,r=t.options.footnoteBackLabel||vD,a=t.options.footnoteLabel||"Footnotes",o=t.options.footnoteLabelTagName||"h2",i=t.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let u=-1;for(;++u<t.footnoteOrder.length;){const d=t.footnoteById.get(t.footnoteOrder[u]);if(!d)continue;const m=t.all(d),p=String(d.identifier).toUpperCase(),x=mi(p.toLowerCase());let f=0;const h=[],j=t.footnoteCounts.get(p);for(;j!==void 0&&++f<=j;){h.length>0&&h.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,f);typeof y=="string"&&(y={type:"text",value:y}),h.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+x+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(u,f),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const b=m[m.length-1];if(b&&b.type==="element"&&b.tagName==="p"){const y=b.children[b.children.length-1];y&&y.type==="text"?y.value+=" ":b.children.push({type:"text",value:" "}),b.children.push(...h)}else m.push(...h);const g={type:"element",tagName:"li",properties:{id:n+"fn-"+x},children:t.wrap(m,!0)};t.patch(d,g),l.push(g)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...ad(i),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:`
|
|
62
|
+
`},{type:"element",tagName:"ol",properties:{},children:t.wrap(l,!0)},{type:"text",value:`
|
|
63
|
+
`}]}}const rp={}.hasOwnProperty,wD={};function ND(t,n){const s=n||wD,r=new Map,a=new Map,o=new Map,i={...xD,...s.handlers},l={all:d,applyData:CD,definitionById:r,footnoteById:a,footnoteCounts:o,footnoteOrder:[],handlers:i,one:u,options:s,patch:kD,wrap:ID};return Ub(t,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const p=m.type==="definition"?r:a,x=String(m.identifier).toUpperCase();p.has(x)||p.set(x,m)}}),l;function u(m,p){const x=m.type,f=l.handlers[x];if(rp.call(l.handlers,x)&&f)return f(l,m,p);if(l.options.passThrough&&l.options.passThrough.includes(x)){if("children"in m){const{children:j,...b}=m,g=ad(b);return g.children=l.all(m),g}return ad(m)}return(l.options.unknownHandler||SD)(l,m,p)}function d(m){const p=[];if("children"in m){const x=m.children;let f=-1;for(;++f<x.length;){const h=l.one(x[f],m);if(h){if(f&&x[f-1].type==="break"&&(!Array.isArray(h)&&h.type==="text"&&(h.value=Xh(h.value)),!Array.isArray(h)&&h.type==="element")){const j=h.children[0];j&&j.type==="text"&&(j.value=Xh(j.value))}Array.isArray(h)?p.push(...h):p.push(h)}}}return p}}function kD(t,n){t.position&&(n.position=j4(t))}function CD(t,n){let s=n;if(t&&t.data){const r=t.data.hName,a=t.data.hChildren,o=t.data.hProperties;if(typeof r=="string")if(s.type==="element")s.tagName=r;else{const i="children"in s?s.children:[s];s={type:"element",tagName:r,properties:{},children:i}}s.type==="element"&&o&&Object.assign(s.properties,ad(o)),"children"in s&&s.children&&a!==null&&a!==void 0&&(s.children=a)}return s}function SD(t,n){const s=n.data||{},r="value"in n&&!(rp.call(s,"hProperties")||rp.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:t.all(n)};return t.patch(n,r),t.applyData(n,r)}function ID(t,n){const s=[];let r=-1;for(n&&s.push({type:"text",value:`
|
|
64
|
+
`});++r<t.length;)r&&s.push({type:"text",value:`
|
|
65
|
+
`}),s.push(t[r]);return n&&t.length>0&&s.push({type:"text",value:`
|
|
66
|
+
`}),s}function Xh(t){let n=0,s=t.charCodeAt(n);for(;s===9||s===32;)n++,s=t.charCodeAt(n);return t.slice(n)}function eg(t,n){const s=ND(t,n),r=s.one(t,void 0),a=jD(s),o=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&o.children.push({type:"text",value:`
|
|
67
|
+
`},a),o}function _D(t,n){return t&&"run"in t?async function(s,r){const a=eg(s,{file:r,...n});await t.run(a,r)}:function(s,r){return eg(s,{file:r,...t||n})}}function tg(t){if(t)throw t}var qu,ng;function AD(){if(ng)return qu;ng=1;var t=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=t.call(d,"constructor"),p=d.constructor&&d.constructor.prototype&&t.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!p)return!1;var x;for(x in d);return typeof x>"u"||t.call(d,x)},i=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},l=function(d,m){if(m==="__proto__")if(t.call(d,m)){if(r)return r(d,m).value}else return;return d[m]};return qu=function u(){var d,m,p,x,f,h,j=arguments[0],b=1,g=arguments.length,y=!1;for(typeof j=="boolean"&&(y=j,j=arguments[1]||{},b=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});b<g;++b)if(d=arguments[b],d!=null)for(m in d)p=l(j,m),x=l(d,m),j!==x&&(y&&x&&(o(x)||(f=a(x)))?(f?(f=!1,h=p&&a(p)?p:[]):h=p&&o(p)?p:{},i(j,{name:m,newValue:u(y,h,x)})):typeof x<"u"&&i(j,{name:m,newValue:x}));return j},qu}var ED=AD();const Uu=Pb(ED);function ap(t){if(typeof t!="object"||t===null)return!1;const n=Object.getPrototypeOf(t);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function TD(){const t=[],n={run:s,use:r};return n;function s(...a){let o=-1;const i=a.pop();if(typeof i!="function")throw new TypeError("Expected function as last argument, not "+i);l(null,...a);function l(u,...d){const m=t[++o];let p=-1;if(u){i(u);return}for(;++p<a.length;)(d[p]===null||d[p]===void 0)&&(d[p]=a[p]);a=d,m?RD(m,l)(...d):i(null,...d)}}function r(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return t.push(a),n}}function RD(t,n){let s;return r;function r(...i){const l=t.length>i.length;let u;l&&i.push(a);try{u=t.apply(this,i)}catch(d){const m=d;if(l&&s)throw m;return a(m)}l||(u&&u.then&&typeof u.then=="function"?u.then(o,a):u instanceof Error?a(u):o(u))}function a(i,...l){s||(s=!0,n(i,...l))}function o(i){a(null,i)}}const hr={basename:PD,dirname:MD,extname:$D,join:DD,sep:"/"};function PD(t,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Fl(t);let s=0,r=-1,a=t.length,o;if(n===void 0||n.length===0||n.length>t.length){for(;a--;)if(t.codePointAt(a)===47){if(o){s=a+1;break}}else r<0&&(o=!0,r=a+1);return r<0?"":t.slice(s,r)}if(n===t)return"";let i=-1,l=n.length-1;for(;a--;)if(t.codePointAt(a)===47){if(o){s=a+1;break}}else i<0&&(o=!0,i=a+1),l>-1&&(t.codePointAt(a)===n.codePointAt(l--)?l<0&&(r=a):(l=-1,r=i));return s===r?r=i:r<0&&(r=t.length),t.slice(s,r)}function MD(t){if(Fl(t),t.length===0)return".";let n=-1,s=t.length,r;for(;--s;)if(t.codePointAt(s)===47){if(r){n=s;break}}else r||(r=!0);return n<0?t.codePointAt(0)===47?"/":".":n===1&&t.codePointAt(0)===47?"//":t.slice(0,n)}function $D(t){Fl(t);let n=t.length,s=-1,r=0,a=-1,o=0,i;for(;n--;){const l=t.codePointAt(n);if(l===47){if(i){r=n+1;break}continue}s<0&&(i=!0,s=n+1),l===46?a<0?a=n:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||s<0||o===0||o===1&&a===s-1&&a===r+1?"":t.slice(a,s)}function DD(...t){let n=-1,s;for(;++n<t.length;)Fl(t[n]),t[n]&&(s=s===void 0?t[n]:s+"/"+t[n]);return s===void 0?".":OD(s)}function OD(t){Fl(t);const n=t.codePointAt(0)===47;let s=LD(t,!n);return s.length===0&&!n&&(s="."),s.length>0&&t.codePointAt(t.length-1)===47&&(s+="/"),n?"/"+s:s}function LD(t,n){let s="",r=0,a=-1,o=0,i=-1,l,u;for(;++i<=t.length;){if(i<t.length)l=t.codePointAt(i);else{if(l===47)break;l=47}if(l===47){if(!(a===i-1||o===1))if(a!==i-1&&o===2){if(s.length<2||r!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(u=s.lastIndexOf("/"),u!==s.length-1){u<0?(s="",r=0):(s=s.slice(0,u),r=s.length-1-s.lastIndexOf("/")),a=i,o=0;continue}}else if(s.length>0){s="",r=0,a=i,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",r=2)}else s.length>0?s+="/"+t.slice(a+1,i):s=t.slice(a+1,i),r=i-a-1;a=i,o=0}else l===46&&o>-1?o++:o=-1}return s}function Fl(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const FD={cwd:qD};function qD(){return"/"}function op(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function UD(t){if(typeof t=="string")t=new URL(t);else if(!op(t)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(t.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return BD(t)}function BD(t){if(t.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const n=t.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const r=n.codePointAt(s+2);if(r===70||r===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(n)}const Bu=["history","path","basename","stem","extname","dirname"];class Nw{constructor(n){let s;n?op(n)?s={path:n}:typeof n=="string"||KD(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":FD.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Bu.length;){const o=Bu[r];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let a;for(a in s)Bu.includes(a)||(this[a]=s[a])}get basename(){return typeof this.path=="string"?hr.basename(this.path):void 0}set basename(n){zu(n,"basename"),Ku(n,"basename"),this.path=hr.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?hr.dirname(this.path):void 0}set dirname(n){sg(this.basename,"dirname"),this.path=hr.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?hr.extname(this.path):void 0}set extname(n){if(Ku(n,"extname"),sg(this.dirname,"extname"),n){if(n.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(n.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=hr.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){op(n)&&(n=UD(n)),zu(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?hr.basename(this.path,this.extname):void 0}set stem(n){zu(n,"stem"),Ku(n,"stem"),this.path=hr.join(this.dirname||"",n+(this.extname||""))}fail(n,s,r){const a=this.message(n,s,r);throw a.fatal=!0,a}info(n,s,r){const a=this.message(n,s,r);return a.fatal=void 0,a}message(n,s,r){const a=new wp(n,s,r);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function Ku(t,n){if(t&&t.includes(hr.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+hr.sep+"`")}function zu(t,n){if(!t)throw new Error("`"+n+"` cannot be empty")}function sg(t,n){if(!t)throw new Error("Setting `"+n+"` requires `path` to be set too")}function KD(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const zD=(function(t){const r=this.constructor.prototype,a=r[t],o=function(){return a.apply(o,arguments)};return Object.setPrototypeOf(o,r),o}),WD={}.hasOwnProperty;class ef extends zD{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=TD()}copy(){const n=new ef;let s=-1;for(;++s<this.attachers.length;){const r=this.attachers[s];n.use(...r)}return n.data(Uu(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Vu("data",this.frozen),this.namespace[n]=s,this):WD.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Vu("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[s,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const a=s.call(n,...r);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=tc(n),r=this.parser||this.Parser;return Wu("parse",r),r(String(s),s)}process(n,s){const r=this;return this.freeze(),Wu("process",this.parser||this.Parser),Hu("process",this.compiler||this.Compiler),s?a(void 0,s):new Promise(a);function a(o,i){const l=tc(n),u=r.parse(l);r.run(u,l,function(m,p,x){if(m||!p||!x)return d(m);const f=p,h=r.stringify(f,x);QD(h)?x.value=h:x.result=h,d(m,x)});function d(m,p){m||!p?i(m):o?o(p):s(void 0,p)}}}processSync(n){let s=!1,r;return this.freeze(),Wu("processSync",this.parser||this.Parser),Hu("processSync",this.compiler||this.Compiler),this.process(n,a),ag("processSync","process",s),r;function a(o,i){s=!0,tg(o),r=i}}run(n,s,r){rg(n),this.freeze();const a=this.transformers;return!r&&typeof s=="function"&&(r=s,s=void 0),r?o(void 0,r):new Promise(o);function o(i,l){const u=tc(s);a.run(n,u,d);function d(m,p,x){const f=p||n;m?l(m):i?i(f):r(void 0,f,x)}}}runSync(n,s){let r=!1,a;return this.run(n,s,o),ag("runSync","run",r),a;function o(i,l){tg(i),a=l,r=!0}}stringify(n,s){this.freeze();const r=tc(s),a=this.compiler||this.Compiler;return Hu("stringify",a),rg(n),a(n,r)}use(n,...s){const r=this.attachers,a=this.namespace;if(Vu("use",this.frozen),n!=null)if(typeof n=="function")u(n,s);else if(typeof n=="object")Array.isArray(n)?l(n):i(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(d){if(typeof d=="function")u(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[m,...p]=d;u(m,p)}else i(d);else throw new TypeError("Expected usable value, not `"+d+"`")}function i(d){if(!("plugins"in d)&&!("settings"in d))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(d.plugins),d.settings&&(a.settings=Uu(!0,a.settings,d.settings))}function l(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const p=d[m];o(p)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let p=-1,x=-1;for(;++p<r.length;)if(r[p][0]===d){x=p;break}if(x===-1)r.push([d,...m]);else if(m.length>0){let[f,...h]=m;const j=r[x][1];ap(j)&&ap(f)&&(f=Uu(!0,j,f)),r[x]=[d,f,...h]}}}}const HD=new ef().freeze();function Wu(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Hu(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Vu(t,n){if(n)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function rg(t){if(!ap(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function ag(t,n,s){if(!s)throw new Error("`"+t+"` finished async. Use `"+n+"` instead")}function tc(t){return VD(t)?t:new Nw(t)}function VD(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function QD(t){return typeof t=="string"||GD(t)}function GD(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const JD="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",og=[],ig={allowDangerousHtml:!0},ZD=/^(https?|ircs?|mailto|xmpp)$/i,YD=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function XD(t){const n=eO(t),s=tO(t);return nO(n.runSync(n.parse(s),s),t)}function eO(t){const n=t.rehypePlugins||og,s=t.remarkPlugins||og,r=t.remarkRehypeOptions?{...t.remarkRehypeOptions,...ig}:ig;return HD().use(B4).use(s).use(_D,r).use(n)}function tO(t){const n=t.children||"",s=new Nw;return typeof n=="string"&&(s.value=n),s}function nO(t,n){const s=n.allowedElements,r=n.allowElement,a=n.components,o=n.disallowedElements,i=n.skipHtml,l=n.unwrapDisallowed,u=n.urlTransform||sO;for(const m of YD)Object.hasOwn(n,m.from)&&gC("Unexpected `"+m.from+"` prop, "+(m.to?"use `"+m.to+"` instead":"remove it")+" (see <"+JD+"#"+m.id+"> for more info)");return Ub(t,d),S4(t,{Fragment:e.Fragment,components:a,ignoreInvalidStyle:!0,jsx:e.jsx,jsxs:e.jsxs,passKeys:!0,passNode:!0});function d(m,p,x){if(m.type==="raw"&&x&&typeof p=="number")return i?x.children.splice(p,1):x.children[p]={type:"text",value:m.value},p;if(m.type==="element"){let f;for(f in Fu)if(Object.hasOwn(Fu,f)&&Object.hasOwn(m.properties,f)){const h=m.properties[f],j=Fu[f];(j===null||j.includes(m.tagName))&&(m.properties[f]=u(String(h||""),f,m))}}if(m.type==="element"){let f=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!f&&r&&typeof p=="number"&&(f=!r(m,p,x)),f&&x&&typeof p=="number")return l&&m.children?x.children.splice(p,1,...m.children):x.children.splice(p,1),p}}}function sO(t){const n=t.indexOf(":"),s=t.indexOf("?"),r=t.indexOf("#"),a=t.indexOf("/");return n===-1||a!==-1&&n>a||s!==-1&&n>s||r!==-1&&n>r||ZD.test(t.slice(0,n))?t:""}function rO(t,n,s){const a=bC((s||{}).ignore||[]),o=aO(n);let i=-1;for(;++i<o.length;)yC(t,"text",l);function l(d,m){let p=-1,x;for(;++p<m.length;){const f=m[p],h=x?x.children:void 0;if(a(f,h?h.indexOf(f):void 0,x))return;x=f}if(x)return u(d,m)}function u(d,m){const p=m[m.length-1],x=o[i][0],f=o[i][1];let h=0;const b=p.children.indexOf(d);let g=!1,y=[];x.lastIndex=0;let v=x.exec(d.value);for(;v;){const _=v.index,E={index:v.index,input:v.input,stack:[...m,d]};let S=f(...v,E);if(typeof S=="string"&&(S=S.length>0?{type:"text",value:S}:void 0),S===!1?x.lastIndex=_+1:(h!==_&&y.push({type:"text",value:d.value.slice(h,_)}),Array.isArray(S)?y.push(...S):S&&y.push(S),h=_+v[0].length,g=!0),!x.global)break;v=x.exec(d.value)}return g?(h<d.value.length&&y.push({type:"text",value:d.value.slice(h)}),p.children.splice(b,1,...y)):y=[d],b+y.length}}function aO(t){const n=[];if(!Array.isArray(t))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!t[0]||Array.isArray(t[0])?t:[t];let r=-1;for(;++r<s.length;){const a=s[r];n.push([oO(a[0]),iO(a[1])])}return n}function oO(t){return typeof t=="string"?new RegExp(vC(t),"g"):t}function iO(t){return typeof t=="function"?t:function(){return t}}const Qu="phrasing",Gu=["autolink","link","image","label"];function lO(){return{transforms:[fO],enter:{literalAutolink:dO,literalAutolinkEmail:Ju,literalAutolinkHttp:Ju,literalAutolinkWww:Ju},exit:{literalAutolink:xO,literalAutolinkEmail:pO,literalAutolinkHttp:uO,literalAutolinkWww:mO}}}function cO(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Qu,notInConstruct:Gu},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Qu,notInConstruct:Gu},{character:":",before:"[ps]",after:"\\/",inConstruct:Qu,notInConstruct:Gu}]}}function dO(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function Ju(t){this.config.enter.autolinkProtocol.call(this,t)}function uO(t){this.config.exit.autolinkProtocol.call(this,t)}function mO(t){this.config.exit.data.call(this,t);const n=this.stack[this.stack.length-1];da(n.type==="link"),n.url="http://"+this.sliceSerialize(t)}function pO(t){this.config.exit.autolinkEmail.call(this,t)}function xO(t){this.exit(t)}function fO(t){rO(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,hO],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),gO]],{ignore:["link","linkReference"]})}function hO(t,n,s,r,a){let o="";if(!kw(a)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!bO(s)))return!1;const i=yO(s+r);if(!i[0])return!1;const l={type:"link",title:null,url:o+n+i[0],children:[{type:"text",value:n+i[0]}]};return i[1]?[l,{type:"text",value:i[1]}]:l}function gO(t,n,s,r){return!kw(r,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function bO(t){const n=t.split(".");return!(n.length<2||n[n.length-1]&&(/_/.test(n[n.length-1])||!/[a-zA-Z\d]/.test(n[n.length-1]))||n[n.length-2]&&(/_/.test(n[n.length-2])||!/[a-zA-Z\d]/.test(n[n.length-2])))}function yO(t){const n=/[!"&'),.:;<>?\]}]+$/.exec(t);if(!n)return[t,void 0];t=t.slice(0,n.index);let s=n[0],r=s.indexOf(")");const a=vf(t,"(");let o=vf(t,")");for(;r!==-1&&a>o;)t+=s.slice(0,r+1),s=s.slice(r+1),r=s.indexOf(")"),o++;return[t,s]}function kw(t,n){const s=t.input.charCodeAt(t.index-1);return(t.index===0||Zo(s)||Np(s))&&(!n||s!==47)}Cw.peek=_O;function vO(){this.buffer()}function jO(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function wO(){this.buffer()}function NO(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function kO(t){const n=this.resume(),s=this.stack[this.stack.length-1];da(s.type==="footnoteReference"),s.identifier=wl(this.sliceSerialize(t)).toLowerCase(),s.label=n}function CO(t){this.exit(t)}function SO(t){const n=this.resume(),s=this.stack[this.stack.length-1];da(s.type==="footnoteDefinition"),s.identifier=wl(this.sliceSerialize(t)).toLowerCase(),s.label=n}function IO(t){this.exit(t)}function _O(){return"["}function Cw(t,n,s,r){const a=s.createTracker(r);let o=a.move("[^");const i=s.enter("footnoteReference"),l=s.enter("reference");return o+=a.move(s.safe(s.associationId(t),{after:"]",before:o})),l(),i(),o+=a.move("]"),o}function AO(){return{enter:{gfmFootnoteCallString:vO,gfmFootnoteCall:jO,gfmFootnoteDefinitionLabelString:wO,gfmFootnoteDefinition:NO},exit:{gfmFootnoteCallString:kO,gfmFootnoteCall:CO,gfmFootnoteDefinitionLabelString:SO,gfmFootnoteDefinition:IO}}}function EO(t){let n=!1;return t&&t.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Cw},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(r,a,o,i){const l=o.createTracker(i);let u=l.move("[^");const d=o.enter("footnoteDefinition"),m=o.enter("label");return u+=l.move(o.safe(o.associationId(r),{before:u,after:"]"})),m(),u+=l.move("]:"),r.children&&r.children.length>0&&(l.shift(4),u+=l.move((n?`
|
|
68
|
+
`:" ")+o.indentLines(o.containerFlow(r,l.current()),n?Sw:TO))),d(),u}}function TO(t,n,s){return n===0?t:Sw(t,n,s)}function Sw(t,n,s){return(s?"":" ")+t}function RO(){return[lO(),AO(),jC(),wC(),NC()]}function PO(t){return{extensions:[cO(),EO(t),kC(),CC(t),SC()]}}const MO={tokenize:qO,partial:!0},Iw={tokenize:UO,partial:!0},_w={tokenize:BO,partial:!0},Aw={tokenize:KO,partial:!0},$O={tokenize:zO,partial:!0},Ew={name:"wwwAutolink",tokenize:LO,previous:Rw},Tw={name:"protocolAutolink",tokenize:FO,previous:Pw},Gr={name:"emailAutolink",tokenize:OO,previous:Mw},$r={};function DO(){return{text:$r}}let Ta=48;for(;Ta<123;)$r[Ta]=Gr,Ta++,Ta===58?Ta=65:Ta===91&&(Ta=97);$r[43]=Gr;$r[45]=Gr;$r[46]=Gr;$r[95]=Gr;$r[72]=[Gr,Tw];$r[104]=[Gr,Tw];$r[87]=[Gr,Ew];$r[119]=[Gr,Ew];function OO(t,n,s){const r=this;let a,o;return i;function i(p){return!ip(p)||!Mw.call(r,r.previous)||tf(r.events)?s(p):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),l(p))}function l(p){return ip(p)?(t.consume(p),l):p===64?(t.consume(p),u):s(p)}function u(p){return p===46?t.check($O,m,d)(p):p===45||p===95||kp(p)?(o=!0,t.consume(p),u):m(p)}function d(p){return t.consume(p),a=!0,u}function m(p){return o&&a&&Xi(r.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),n(p)):s(p)}}function LO(t,n,s){const r=this;return a;function a(i){return i!==87&&i!==119||!Rw.call(r,r.previous)||tf(r.events)?s(i):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(MO,t.attempt(Iw,t.attempt(_w,o),s),s)(i))}function o(i){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),n(i)}}function FO(t,n,s){const r=this;let a="",o=!1;return i;function i(p){return(p===72||p===104)&&Pw.call(r,r.previous)&&!tf(r.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),a+=String.fromCodePoint(p),t.consume(p),l):s(p)}function l(p){if(Xi(p)&&a.length<5)return a+=String.fromCodePoint(p),t.consume(p),l;if(p===58){const x=a.toLowerCase();if(x==="http"||x==="https")return t.consume(p),u}return s(p)}function u(p){return p===47?(t.consume(p),o?d:(o=!0,u)):s(p)}function d(p){return p===null||IC(p)||Cr(p)||Zo(p)||Np(p)?s(p):t.attempt(Iw,t.attempt(_w,m),s)(p)}function m(p){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),n(p)}}function qO(t,n,s){let r=0;return a;function a(i){return(i===87||i===119)&&r<3?(r++,t.consume(i),a):i===46&&r===3?(t.consume(i),o):s(i)}function o(i){return i===null?s(i):n(i)}}function UO(t,n,s){let r,a,o;return i;function i(d){return d===46||d===95?t.check(Aw,u,l)(d):d===null||Cr(d)||Zo(d)||d!==45&&Np(d)?u(d):(o=!0,t.consume(d),i)}function l(d){return d===95?r=!0:(a=r,r=void 0),t.consume(d),i}function u(d){return a||r||!o?s(d):n(d)}}function BO(t,n){let s=0,r=0;return a;function a(i){return i===40?(s++,t.consume(i),a):i===41&&r<s?o(i):i===33||i===34||i===38||i===39||i===41||i===42||i===44||i===46||i===58||i===59||i===60||i===63||i===93||i===95||i===126?t.check(Aw,n,o)(i):i===null||Cr(i)||Zo(i)?n(i):(t.consume(i),a)}function o(i){return i===41&&r++,t.consume(i),a}}function KO(t,n,s){return r;function r(l){return l===33||l===34||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===63||l===95||l===126?(t.consume(l),r):l===38?(t.consume(l),o):l===93?(t.consume(l),a):l===60||l===null||Cr(l)||Zo(l)?n(l):s(l)}function a(l){return l===null||l===40||l===91||Cr(l)||Zo(l)?n(l):r(l)}function o(l){return Xi(l)?i(l):s(l)}function i(l){return l===59?(t.consume(l),r):Xi(l)?(t.consume(l),i):s(l)}}function zO(t,n,s){return r;function r(o){return t.consume(o),a}function a(o){return kp(o)?s(o):n(o)}}function Rw(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Cr(t)}function Pw(t){return!Xi(t)}function Mw(t){return!(t===47||ip(t))}function ip(t){return t===43||t===45||t===46||t===95||kp(t)}function tf(t){let n=t.length,s=!1;for(;n--;){const r=t[n][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){s=!0;break}if(r._gfmAutolinkLiteralWalkedInto){s=!1;break}}return t.length>0&&!s&&(t[t.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const WO={tokenize:XO,partial:!0};function HO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:JO,continuation:{tokenize:ZO},exit:YO}},text:{91:{name:"gfmFootnoteCall",tokenize:GO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:VO,resolveTo:QO}}}}function VO(t,n,s){const r=this;let a=r.events.length;const o=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i;for(;a--;){const u=r.events[a][1];if(u.type==="labelImage"){i=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return l;function l(u){if(!i||!i._balanced)return s(u);const d=wl(r.sliceSerialize({start:i.end,end:r.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?s(u):(t.enter("gfmFootnoteCallLabelMarker"),t.consume(u),t.exit("gfmFootnoteCallLabelMarker"),n(u))}}function QO(t,n){let s=t.length;for(;s--;)if(t[s][1].type==="labelImage"&&t[s][0]==="enter"){t[s][1];break}t[s+1][1].type="data",t[s+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},t[s+3][1].start),end:Object.assign({},t[t.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},t[s+3][1].end),end:Object.assign({},t[s+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},t[t.length-1][1].start)},i={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},l=[t[s+1],t[s+2],["enter",r,n],t[s+3],t[s+4],["enter",a,n],["exit",a,n],["enter",o,n],["enter",i,n],["exit",i,n],["exit",o,n],t[t.length-2],t[t.length-1],["exit",r,n]];return t.splice(s,t.length-s+1,...l),t}function GO(t,n,s){const r=this,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o=0,i;return l;function l(p){return t.enter("gfmFootnoteCall"),t.enter("gfmFootnoteCallLabelMarker"),t.consume(p),t.exit("gfmFootnoteCallLabelMarker"),u}function u(p){return p!==94?s(p):(t.enter("gfmFootnoteCallMarker"),t.consume(p),t.exit("gfmFootnoteCallMarker"),t.enter("gfmFootnoteCallString"),t.enter("chunkString").contentType="string",d)}function d(p){if(o>999||p===93&&!i||p===null||p===91||Cr(p))return s(p);if(p===93){t.exit("chunkString");const x=t.exit("gfmFootnoteCallString");return a.includes(wl(r.sliceSerialize(x)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(p),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),n):s(p)}return Cr(p)||(i=!0),o++,t.consume(p),p===92?m:d}function m(p){return p===91||p===92||p===93?(t.consume(p),o++,d):d(p)}}function JO(t,n,s){const r=this,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o,i=0,l;return u;function u(h){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(h){return h===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",m):s(h)}function m(h){if(i>999||h===93&&!l||h===null||h===91||Cr(h))return s(h);if(h===93){t.exit("chunkString");const j=t.exit("gfmFootnoteDefinitionLabelString");return o=wl(r.sliceSerialize(j)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),x}return Cr(h)||(l=!0),i++,t.consume(h),h===92?p:m}function p(h){return h===91||h===92||h===93?(t.consume(h),i++,m):m(h)}function x(h){return h===58?(t.enter("definitionMarker"),t.consume(h),t.exit("definitionMarker"),a.includes(o)||a.push(o),Bb(t,f,"gfmFootnoteDefinitionWhitespace")):s(h)}function f(h){return n(h)}}function ZO(t,n,s){return t.check(_C,n,t.attempt(WO,n,s))}function YO(t){t.exit("gfmFootnoteDefinition")}function XO(t,n,s){const r=this;return Bb(t,a,"gfmFootnoteDefinitionIndent",5);function a(o){const i=r.events[r.events.length-1];return i&&i[1].type==="gfmFootnoteDefinitionIndent"&&i[2].sliceSerialize(i[1],!0).length===4?n(o):s(o)}}function eL(t){return AC([DO(),HO(),EC(t),TC(),RC()])}const tL={};function nL(t){const n=this,s=t||tL,r=n.data(),a=r.micromarkExtensions||(r.micromarkExtensions=[]),o=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),i=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);a.push(eL(s)),o.push(RO()),i.push(PO(s))}let Zu=null;function sL(){return Zu||(Zu=Kb(()=>import("./mermaid.core-Cma2jq_8.js").then(t=>t.bC),__vite__mapDeps([0,1,2,3])).then(t=>t.default)),Zu}function $w(t){return t==null?"":typeof t=="string"||typeof t=="number"?String(t):Array.isArray(t)?t.map(n=>$w(n)).join(""):""}function rL(t){if(!c.isValidElement(t))return null;const n=t.props;return typeof n.className!="string"||!/\blanguage-mermaid\b/i.test(n.className)?null:$w(n.children).replace(/\n$/,"")}function aL({source:t,darkMode:n}){const s=c.useId().replace(/[^a-zA-Z0-9_-]/g,""),[r,a]=c.useState(null),[o,i]=c.useState(null);return c.useEffect(()=>{let l=!0;return a(null),i(null),sL().then(async u=>{u.initialize({startOnLoad:!1,securityLevel:"strict",theme:n?"dark":"default",fontFamily:"inherit",suppressErrorRendering:!0});const d=await u.render(`crewspace-mermaid-${s}`,t);l&&a(d.svg)}).catch(u=>{if(!l)return;const d=u instanceof Error&&u.message?u.message:"Failed to render Mermaid diagram.";i(d)}),()=>{l=!1}},[n,s,t]),e.jsx("div",{className:"crewspace-mermaid",children:r?e.jsx("div",{dangerouslySetInnerHTML:{__html:r}}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:O("crewspace-mermaid-status",o&&"crewspace-mermaid-status-error"),children:o?`Unable to render Mermaid diagram: ${o}`:"Rendering Mermaid diagram..."}),e.jsx("pre",{className:"crewspace-mermaid-source",children:e.jsx("code",{className:"language-mermaid",children:t})})]})})}function Xs({children:t,className:n,resolveImageSrc:s}){const{theme:r}=B0(),a={pre:({node:o,children:i,...l})=>{const u=rL(i);return u?e.jsx(aL,{source:u,darkMode:r==="dark"}):e.jsx("pre",{...l,children:i})},a:({href:o,children:i})=>{const l=o?Ux(o):null;if(l){const u=l.kind==="project"?`/projects/${l.projectId}`:`/agents/${l.agentId}`;return e.jsx("a",{href:u,className:O("crewspace-mention-chip",`crewspace-mention-chip--${l.kind}`,l.kind==="project"&&"crewspace-project-mention-chip"),"data-mention-kind":l.kind,style:O0(l),children:i})}return e.jsx("a",{href:o,rel:"noreferrer",children:i})}};return s&&(a.img=({node:o,src:i,alt:l,...u})=>{const d=i?s(i):null;return e.jsx("img",{...u,src:d??i,alt:l??""})}),e.jsx("div",{className:O("crewspace-markdown prose prose-sm max-w-none break-words overflow-hidden",r==="dark"&&"prose-invert",n),children:e.jsx(XD,{remarkPlugins:[nL],components:a,urlTransform:o=>o,children:t})})}function nf(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Pr(t){return t.replace(/\s+/g," ").trim()}function rr(t,n){return t.length>n?`${t.slice(0,Math.max(0,n-1))}…`:t}function od(t){return t.replace(/[_-]+/g," ").trim().replace(/\b\w/g,n=>n.toUpperCase())}function lg(t){const n=Pr(t),s=n.match(/^(?:(?:\/bin\/)?(?:zsh|bash|sh)|cmd(?:\.exe)?(?:\s+\/d)?(?:\s+\/s)?(?:\s+\/c)?)\s+(?:-lc|\/c)\s+(.+)$/i),r=(s==null?void 0:s[1])??n,a=r.match(/^(['"])([\s\S]*)\1$/);return Pr((a==null?void 0:a[2])??r)}function Dw(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}function lo(t){if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return Dw(t)}function oL(t){const n=nf(t);if(!n)return;const s=[n.toolUseId,n.tool_use_id,n.callId,n.call_id,n.id];for(const r of s)if(typeof r=="string"&&r.trim())return r}function cg(t,n){for(const s of n){const r=t[s];if(typeof r=="string"&&r.trim())return rr(Pr(r),120)}return null}function id(t,n,s){const r=s==="compact"?72:120;if(typeof n=="string"){const u=di(t,n)?lg(n):Pr(n);return rr(u,r)}const a=nf(n);if(!a){const u=Pr(Dw(n));return u?rr(u,r):`Inspect ${t} input`}const o=typeof a.command=="string"?a.command:typeof a.cmd=="string"?a.cmd:null;if(o&&di(t,a))return rr(lg(o),r);const i=cg(a,["command","cmd","path","filePath","file_path","query","url","prompt","message"])??cg(a,["pattern","name","title","target","tool"])??null;if(i)return rr(i,r);if(Array.isArray(a.paths)&&a.paths.length>0){const u=a.paths.find(d=>typeof d=="string"&&d.trim().length>0);if(u)return rr(`${a.paths.length} paths, starting with ${u}`,r)}const l=Object.keys(a);return l.length===0?`No ${t} input`:l.length===1?rr(`${l[0]} payload`,r):rr(`${l.length} fields: ${l.slice(0,3).join(", ")}`,r)}function Ow(t){var o;if(!t)return null;const n=t.split(/\r?\n/),s=new Map;let r=n.findIndex(i=>i.trim()==="");r===-1&&(r=n.length);for(let i=0;i<r;i+=1){const l=(o=n[i])==null?void 0:o.match(/^([a-z_]+):\s*(.+)$/i);l&&s.set(l[1].toLowerCase(),Pr(l[2]))}const a=n.slice(Math.min(r+1,n.length)).map(i=>Pr(i)).filter(Boolean).join(`
|
|
69
|
+
`);return{command:s.get("command")??null,status:s.get("status")??null,exitCode:s.get("exit_code")??null,body:a}}function di(t,n){if(t==="command_execution"||t==="shell"||t==="shellToolCall"||t==="bash")return!0;if(typeof n=="string")return/\b(?:bash|zsh|sh|cmd|powershell)\b/i.test(n);const s=nf(n);return!!(s&&(typeof s.command=="string"||typeof s.cmd=="string"))}function iL(t,n){return di(t,n)?"Executing command":od(t)}function lL(t,n,s){if(!t)return n?"Tool failed":"Waiting for result";const r=Ow(t);if(r){if(r.body)return rr(r.body.split(`
|
|
70
|
+
`)[0]??r.body,s==="compact"?84:140);if(r.status==="completed")return"Completed";if(r.status==="failed"||r.status==="error")return r.exitCode?`Failed with exit code ${r.exitCode}`:"Failed"}const o=t.split(/\r?\n/).map(i=>Pr(i)).filter(Boolean)[0]??t;return rr(o,s==="compact"?84:140)}function cL(t){const n=t.match(/^item (started|completed):\s*([a-z0-9_-]+)(?:\s+\(id=([^)]+)\))?$/i);return n?{status:n[1].toLowerCase()==="started"?"running":"completed",name:od(n[2]??"Activity"),activityId:n[3]||void 0}:null}function dL(t){return Pr(t).toLowerCase().startsWith("[crewspace] skipping saved session resume")}function uL(t){const n=[];let s=[],r=null,a;const o=()=>{s.length===0||!r||(n.push({type:"command_group",ts:r,endTs:a,items:s}),s=[],r=null,a=void 0)};for(const i of t){if(i.type==="tool"&&di(i.name,i.input)){r||(r=i.ts),a=i.endTs??i.ts,s.push({ts:i.ts,endTs:i.endTs,input:i.input,result:i.result,isError:i.isError,status:i.status});continue}o(),n.push(i)}return o(),n}function mL(t){const n=[];let s=[],r=null,a;const o=()=>{s.length===0||!r||(n.push({type:"tool_group",ts:r,endTs:a,items:s}),s=[],r=null,a=void 0)};for(const i of t){if(i.type==="tool"&&!di(i.name,i.input)){r||(r=i.ts),a=i.endTs??i.ts,s.push({ts:i.ts,endTs:i.endTs,name:i.name,input:i.input,result:i.result,isError:i.isError,status:i.status});continue}o(),n.push(i)}return o(),n}function pL(t,n){const s=[],r=new Map,a=new Map;for(const o of t){const i=s[s.length-1];if(o.kind==="assistant"||o.kind==="user"){const u=n&&o.kind==="assistant"&&o.delta===!0;(i==null?void 0:i.type)==="message"&&i.role===o.kind?(i.text+=i.text.endsWith(`
|
|
71
|
+
`)||o.text.startsWith(`
|
|
72
|
+
`)?o.text:`
|
|
73
|
+
${o.text}`,i.ts=o.ts,i.streaming=i.streaming||u):s.push({type:"message",role:o.kind,ts:o.ts,text:o.text,streaming:u});continue}if(o.kind==="thinking"){const u=n&&o.delta===!0;(i==null?void 0:i.type)==="thinking"?(i.text+=i.text.endsWith(`
|
|
74
|
+
`)||o.text.startsWith(`
|
|
75
|
+
`)?o.text:`
|
|
76
|
+
${o.text}`,i.ts=o.ts,i.streaming=i.streaming||u):s.push({type:"thinking",ts:o.ts,text:o.text,streaming:u});continue}if(o.kind==="tool_call"){const u={type:"tool",ts:o.ts,name:iL(o.name,o.input),toolUseId:o.toolUseId??oL(o.input),input:o.input,status:"running"};s.push(u),u.toolUseId&&r.set(u.toolUseId,u);continue}if(o.kind==="tool_result"){const u=r.get(o.toolUseId)??[...s].reverse().find(d=>d.type==="tool"&&d.status==="running");u?(u.result=o.content,u.isError=o.isError,u.status=o.isError?"error":"completed",u.endTs=o.ts,r.delete(o.toolUseId)):s.push({type:"tool",ts:o.ts,endTs:o.ts,name:o.toolName??"tool",toolUseId:o.toolUseId,input:null,result:o.content,isError:o.isError,status:o.isError?"error":"completed"});continue}if(o.kind==="init"){s.push({type:"event",ts:o.ts,label:"init",tone:"info",text:`model ${o.model}${o.sessionId?` • session ${o.sessionId}`:""}`});continue}if(o.kind==="result"){s.push({type:"event",ts:o.ts,label:"result",tone:o.isError?"error":"info",text:o.text.trim()||o.errors[0]||(o.isError?"Run failed":"Completed")});continue}if(o.kind==="stderr"){if(dL(o.text))continue;const u=s[s.length-1];u&&u.type==="stderr_group"?(u.lines.push({ts:o.ts,text:o.text}),u.endTs=o.ts):s.push({type:"stderr_group",ts:o.ts,endTs:o.ts,lines:[{ts:o.ts,text:o.text}]});continue}if(o.kind==="system"){if(Pr(o.text).toLowerCase()==="turn started")continue;const u=cL(o.text);if(u){const d=u.activityId?a.get(u.activityId):void 0;if(d)d.status=u.status,d.ts=o.ts,u.status==="completed"&&u.activityId&&a.delete(u.activityId);else{const m={type:"activity",ts:o.ts,activityId:u.activityId,name:u.name,status:u.status};s.push(m),u.status==="running"&&u.activityId&&a.set(u.activityId,m)}continue}s.push({type:"event",ts:o.ts,label:"system",tone:"warn",text:o.text});continue}const l=[...s].reverse().find(u=>u.type==="tool"&&u.status==="running"&&di(u.name,u.input));if(l){l.result=l.result?`${l.result}${l.result.endsWith(`
|
|
77
|
+
`)||o.text.startsWith(`
|
|
78
|
+
`)?o.text:`
|
|
79
|
+
${o.text}`}`:o.text;continue}(i==null?void 0:i.type)==="stdout"?(i.text+=i.text.endsWith(`
|
|
80
|
+
`)||o.text.startsWith(`
|
|
81
|
+
`)?o.text:`
|
|
82
|
+
${o.text}`,i.ts=o.ts):s.push({type:"stdout",ts:o.ts,text:o.text})}return mL(uL(s))}function xL({block:t,density:n}){const s=t.role==="assistant",r=n==="compact";return e.jsxs("div",{children:[!s&&e.jsxs("div",{className:"mb-1.5 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:[e.jsx(Ns,{className:r?"h-3.5 w-3.5":"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx(Xs,{className:O("[&>*:first-child]:mt-0 [&>*:last-child]:mb-0",r?"text-xs leading-5 text-foreground/85":"text-sm"),children:t.text}),t.streaming&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1 text-[10px] font-medium italic text-muted-foreground",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-70"}),e.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-current"})]}),"Streaming"]})]})}function fL({block:t,density:n,className:s}){return e.jsx(Xs,{className:O("italic text-foreground/70 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",n==="compact"?"text-[11px] leading-5":"text-sm leading-6",s),children:t.text})}function hL({block:t,density:n}){const[s,r]=c.useState(t.status==="error"),a=n==="compact",o=Ow(t.result),i=t.status==="running"?"Running":t.status==="error"?"Errored":"Completed",l=t.status==="running"?"text-cyan-700 dark:text-cyan-300":t.status==="error"?"text-red-700 dark:text-red-300":"text-emerald-700 dark:text-emerald-300",u=O("space-y-3",t.status==="error"&&"rounded-xl border border-red-500/20 bg-red-500/[0.06] p-3"),d=O("mt-0.5 h-3.5 w-3.5 shrink-0",t.status==="error"?"text-red-600 dark:text-red-300":t.status==="completed"?"text-emerald-600 dark:text-emerald-300":"text-cyan-600 dark:text-cyan-300"),m=t.status==="running"?id(t.name,t.input,n):t.status==="completed"&&(o!=null&&o.body)?rr(o.body.split(`
|
|
83
|
+
`)[0]??o.body,a?84:140):lL(t.result,t.isError,n);return e.jsxs("div",{className:O(t.status==="error"&&"rounded-xl border border-red-500/20 bg-red-500/[0.04] p-3"),children:[e.jsxs("div",{className:"flex items-start gap-2",children:[t.status==="error"?e.jsx(_d,{className:d}):t.status==="completed"?e.jsx(Nn,{className:d}):e.jsx(tl,{className:d}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:t.name}),e.jsx("span",{className:O("text-[10px] font-semibold uppercase tracking-[0.14em]",l),children:i})]}),e.jsx("div",{className:O("mt-1 break-words text-foreground/80",a?"text-xs":"text-sm"),children:m})]}),e.jsx("button",{type:"button",className:"mt-0.5 inline-flex h-5 w-5 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",onClick:()=>r(p=>!p),"aria-label":s?"Collapse tool details":"Expand tool details",children:s?e.jsx(rn,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})})]}),s&&e.jsx("div",{className:"mt-3",children:e.jsx("div",{className:u,children:e.jsxs("div",{className:O("grid gap-3",a?"grid-cols-1":"lg:grid-cols-2"),children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Input"}),e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px] text-foreground/80",children:lo(t.input)||"<empty>"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Result"}),e.jsx("pre",{className:O("overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px]",t.status==="error"?"text-red-700 dark:text-red-300":"text-foreground/80"),children:t.result?lo(t.result):"Waiting for result..."})]})]})})})]})}function Lw(){var t;return typeof window>"u"?!1:(((t=window.getSelection())==null?void 0:t.toString().length)??0)>0}function gL({block:t,density:n}){const[s,r]=c.useState(!1),a=n==="compact",o=[...t.items].reverse().find(f=>f.status==="running"),i=t.items[t.items.length-1]??null,l=t.items.some(f=>f.status==="error"),u=!!o,d=s&&l,m=u?"Executing command":t.items.length===1?"Executed command":`Executed ${t.items.length} commands`,p=o?id("command_execution",o.input,n):null,x=u?"text-cyan-700 dark:text-cyan-300":"text-foreground/70";return e.jsxs("div",{className:O(d&&"rounded-xl border border-red-500/20 bg-red-500/[0.04] p-3"),children:[e.jsxs("div",{role:"button",tabIndex:0,className:O("flex cursor-pointer gap-2",p?"items-start":"items-center"),onClick:()=>{Lw()||r(f=>!f)},onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r(h=>!h))},children:[e.jsx("div",{className:O("flex shrink-0 items-center",p&&"mt-0.5"),children:t.items.slice(0,Math.min(t.items.length,3)).map((f,h)=>e.jsx("span",{className:O("inline-flex h-6 w-6 items-center justify-center rounded-full border shadow-sm",h>0&&"-ml-1.5",u?"border-cyan-500/25 bg-cyan-500/[0.08] text-cyan-600 dark:text-cyan-300":"border-border/70 bg-background text-foreground/55",u&&"animate-pulse"),children:e.jsx(vm,{className:"h-3.5 w-3.5"})},h))}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase leading-none tracking-[0.1em] text-muted-foreground/70",children:m}),p&&e.jsx("div",{className:O("mt-1 break-words font-mono text-foreground/85",a?"text-xs":"text-sm"),children:p}),!p&&(i==null?void 0:i.status)==="error"&&s&&e.jsx("div",{className:O("mt-1",a?"text-xs":"text-sm",x),children:"Command failed"})]}),e.jsx("button",{type:"button",className:O("inline-flex h-5 w-5 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",p&&"mt-0.5"),onClick:f=>{f.stopPropagation(),r(h=>!h)},"aria-label":s?"Collapse command details":"Expand command details",children:s?e.jsx(rn,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})})]}),s&&e.jsx("div",{className:O("mt-3 space-y-3",l&&"rounded-xl border border-red-500/20 bg-red-500/[0.06] p-3"),children:t.items.map((f,h)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:O("inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border",f.status==="error"?"border-red-500/25 bg-red-500/[0.08] text-red-600 dark:text-red-300":f.status==="running"?"border-cyan-500/25 bg-cyan-500/[0.08] text-cyan-600 dark:text-cyan-300":"border-border/70 bg-background text-foreground/55"),children:e.jsx(vm,{className:"h-3 w-3"})}),e.jsx("span",{className:O("font-mono break-all",a?"text-[11px]":"text-xs"),children:id("command_execution",f.input,n)})]}),f.result&&e.jsx("pre",{className:O("overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px]",f.status==="error"?"text-red-700 dark:text-red-300":"text-foreground/80"),children:lo(f.result)})]},`${f.ts}-${h}`))})]})}function bL({block:t,density:n}){const[s,r]=c.useState(!1),a=n==="compact",o=[...t.items].reverse().find(x=>x.status==="running"),i=t.items.some(x=>x.status==="error"),l=!!o,u=[...new Set(t.items.map(x=>x.name))],d=u.length===1?od(u[0]):`${u.length} tools`,m=l?`Using ${d}`:t.items.length===1?`Used ${d}`:`Used ${d} (${t.items.length} calls)`,p=o?id(o.name,o.input,n):null;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-muted/[0.25]",children:[e.jsxs("div",{role:"button",tabIndex:0,className:O("flex cursor-pointer gap-2 px-3 py-2.5",p?"items-start":"items-center"),onClick:()=>{Lw()||r(x=>!x)},onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),r(f=>!f))},children:[e.jsx("div",{className:O("flex shrink-0 items-center",p&&"mt-0.5"),children:t.items.slice(0,Math.min(t.items.length,3)).map((x,f)=>{const h=x.status==="running",j=x.status==="error";return e.jsx("span",{className:O("inline-flex h-6 w-6 items-center justify-center rounded-full border shadow-sm",f>0&&"-ml-1.5",h?"border-cyan-500/25 bg-cyan-500/[0.08] text-cyan-600 dark:text-cyan-300":j?"border-red-500/25 bg-red-500/[0.08] text-red-600 dark:text-red-300":"border-border/70 bg-background text-foreground/55",h&&"animate-pulse"),children:e.jsx(tl,{className:"h-3.5 w-3.5"})},`${x.ts}-${f}`)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:O("font-semibold uppercase leading-none tracking-[0.1em]",a?"text-[10px]":"text-[11px]","text-muted-foreground/70"),children:m}),p&&e.jsx("div",{className:O("mt-1 break-words font-mono text-foreground/85",a?"text-xs":"text-sm"),children:p})]}),e.jsx("button",{type:"button",className:O("inline-flex h-5 w-5 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",p&&"mt-0.5"),onClick:x=>{x.stopPropagation(),r(f=>!f)},"aria-label":s?"Collapse tool details":"Expand tool details",children:s?e.jsx(rn,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})})]}),s&&e.jsx("div",{className:O("space-y-2 border-t border-border/30 px-3 py-3",i&&"rounded-b-xl"),children:t.items.map((x,f)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:O("inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border",x.status==="error"?"border-red-500/25 bg-red-500/[0.08] text-red-600 dark:text-red-300":x.status==="running"?"border-cyan-500/25 bg-cyan-500/[0.08] text-cyan-600 dark:text-cyan-300":"border-border/70 bg-background text-foreground/55"),children:e.jsx(tl,{className:"h-3 w-3"})}),e.jsx("span",{className:O("text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground"),children:od(x.name)}),e.jsx("span",{className:O("text-[10px] font-semibold uppercase tracking-[0.14em]",x.status==="running"?"text-cyan-700 dark:text-cyan-300":x.status==="error"?"text-red-700 dark:text-red-300":"text-emerald-700 dark:text-emerald-300"),children:x.status==="running"?"Running":x.status==="error"?"Errored":"Completed"})]}),e.jsxs("div",{className:O("grid gap-2 pl-7",a?"grid-cols-1":"lg:grid-cols-2"),children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-0.5 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Input"}),e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px] text-foreground/80",children:lo(x.input)||"<empty>"})]}),x.result&&e.jsxs("div",{children:[e.jsx("div",{className:"mb-0.5 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Result"}),e.jsx("pre",{className:O("overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px]",x.status==="error"?"text-red-700 dark:text-red-300":"text-foreground/80"),children:lo(x.result)})]})]})]},`${x.ts}-${f}`))})]})}function yL({block:t,density:n}){return e.jsxs("div",{className:"flex items-start gap-2",children:[t.status==="completed"?e.jsx(Nn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-300"}):e.jsxs("span",{className:"relative mt-1 flex h-2.5 w-2.5 shrink-0",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-cyan-400 opacity-70"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-cyan-500"})]}),e.jsx("div",{className:O("break-words text-foreground/80",n==="compact"?"text-xs leading-5":"text-sm leading-6"),children:t.name})]})}function vL({block:t,density:n}){const s=n==="compact",r=t.tone==="error"?"rounded-xl border border-red-500/20 bg-red-500/[0.06] p-3 text-red-700 dark:text-red-300":t.tone==="warn"?"text-amber-700 dark:text-amber-300":t.tone==="info"?"text-sky-700 dark:text-sky-300":"text-foreground/75";return e.jsx("div",{className:r,children:e.jsxs("div",{className:"flex items-start gap-2",children:[t.tone==="error"?e.jsx(_d,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):t.tone==="warn"?e.jsx(vm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):e.jsx("span",{className:"mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-current/50"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[t.label==="result"&&t.tone!=="error"?e.jsx("div",{className:O("whitespace-pre-wrap break-words text-sky-700 dark:text-sky-300",s?"text-[11px]":"text-xs"),children:t.text}):e.jsxs("div",{className:O("whitespace-pre-wrap break-words",s?"text-[11px]":"text-xs"),children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.1em] text-muted-foreground/70",children:t.label}),t.text?e.jsx("span",{className:"ml-2",children:t.text}):null]}),t.detail&&e.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px] text-foreground/75",children:t.detail})]})]})})}function jL({block:t,density:n}){const[s,r]=c.useState(!1);return e.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.06] p-2 text-amber-700 dark:text-amber-300",children:[e.jsxs("div",{role:"button",tabIndex:0,className:"flex cursor-pointer items-center gap-2",onClick:()=>r(a=>!a),onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r(o=>!o))},children:[e.jsxs("span",{className:O("text-[10px] font-semibold uppercase tracking-[0.14em]"),children:[t.lines.length," log ",t.lines.length===1?"line":"lines"]}),s?e.jsx(rn,{className:"h-3.5 w-3.5"}):e.jsx(sn,{className:"h-3.5 w-3.5"})]}),s&&e.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px] text-amber-700/80 dark:text-amber-300/80 pl-5",children:t.lines.map((a,o)=>e.jsxs("span",{children:[e.jsx("span",{className:"select-none text-amber-500/50 dark:text-amber-400/40",children:o>0?`
|
|
84
|
+
`:""}),a.text]},`${a.ts}-${o}`))})]})}function wL({block:t,density:n,collapseByDefault:s}){const[r,a]=c.useState(!s);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"stdout"}),e.jsx("button",{type:"button",className:"inline-flex h-5 w-5 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",onClick:()=>a(o=>!o),"aria-label":r?"Collapse stdout":"Expand stdout",children:r?e.jsx(rn,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})})]}),r&&e.jsx("pre",{className:O("mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-foreground/80",n==="compact"?"text-[11px]":"text-xs"),children:t.text})]})}function NL({entries:t,density:n}){const s=n==="compact";return e.jsx("div",{className:O("font-mono",s?"space-y-1 text-[11px]":"space-y-1.5 text-xs"),children:t.map((r,a)=>e.jsxs("div",{className:O("grid gap-x-3","grid-cols-[auto_1fr]"),children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.18em] text-muted-foreground",children:r.kind}),e.jsx("pre",{className:"min-w-0 whitespace-pre-wrap break-words text-foreground/80",children:r.kind==="tool_call"?`${r.name}
|
|
85
|
+
${lo(r.input)}`:r.kind==="tool_result"?lo(r.content):r.kind==="result"?`${r.text}
|
|
86
|
+
${Et(r.inputTokens)} / ${Et(r.outputTokens)} / $${r.costUsd.toFixed(6)}`:r.kind==="init"?`model=${r.model}${r.sessionId?` session=${r.sessionId}`:""}`:r.text})]},`${r.kind}-${r.ts}-${a}`))})}function Ni({entries:t,mode:n="nice",density:s="comfortable",limit:r,streaming:a=!1,collapseStdout:o=!1,emptyMessage:i="No transcript yet.",className:l,thinkingClassName:u}){const d=c.useMemo(()=>pL(t,a),[t,a]),m=r?d.slice(-r):d,p=r?t.slice(-r):t;return t.length===0?e.jsx("div",{className:O("rounded-2xl border border-dashed border-border/70 bg-background/40 p-4 text-sm text-muted-foreground",l),children:i}):n==="raw"?e.jsx("div",{className:l,children:e.jsx(NL,{entries:p,density:s})}):e.jsx("div",{className:O("space-y-3",l),children:m.map((x,f)=>e.jsxs("div",{className:O(f===m.length-1&&a&&"animate-in fade-in slide-in-from-bottom-1 duration-300"),children:[x.type==="message"&&e.jsx(xL,{block:x,density:s}),x.type==="thinking"&&e.jsx(fL,{block:x,density:s,className:u}),x.type==="tool"&&e.jsx(hL,{block:x,density:s}),x.type==="command_group"&&e.jsx(gL,{block:x,density:s}),x.type==="tool_group"&&e.jsx(bL,{block:x,density:s}),x.type==="stderr_group"&&e.jsx(jL,{block:x,density:s}),x.type==="stdout"&&e.jsx(wL,{block:x,density:s,collapseByDefault:o}),x.type==="activity"&&e.jsx(yL,{block:x,density:s}),x.type==="event"&&e.jsx(vL,{block:x,density:s})]},`${x.type}-${x.ts}-${f}`))})}const kL=2e3,CL=256e3;function Or(t){return typeof t=="string"&&t.trim().length>0?t:null}function dg(t){return t==="failed"||t==="timed_out"||t==="cancelled"||t==="succeeded"}function SL(t,n,s){if(!n)return[];const r=`${t}:records`,o=`${s.get(r)??""}${n}`.split(`
|
|
87
|
+
`);s.set(r,o.pop()??"");const i=[];for(const l of o){const u=l.trim();if(u)try{const d=JSON.parse(u),m=d.stream==="stderr"||d.stream==="system"?d.stream:"stdout",p=typeof d.chunk=="string"?d.chunk:"",x=typeof d.ts=="string"?d.ts:new Date().toISOString();if(!p)continue;i.push({ts:x,stream:m,chunk:p,dedupeKey:`log:${t}:${x}:${m}:${p}`})}catch{}}return i}function Fw({runs:t,companyId:n,maxChunksPerRun:s=200}){const[r,a]=c.useState(new Map),o=c.useRef(new Set),i=c.useRef(new Map),l=c.useRef(new Map),{data:u}=oe({queryKey:N.instance.generalSettings,queryFn:()=>Rr.getGeneral()}),d=c.useMemo(()=>new Map(t.map(h=>[h.id,h])),[t]),m=c.useMemo(()=>new Set(t.filter(h=>!dg(h.status)).map(h=>h.id)),[t]),p=c.useMemo(()=>t.map(h=>h.id).sort((h,j)=>h.localeCompare(j)).join(","),[t]),x=(h,j)=>{j.length!==0&&a(b=>{const g=new Map(b),y=[...g.get(h)??[]];let v=!1;for(const _ of j)o.current.has(_.dedupeKey)||(o.current.add(_.dedupeKey),y.push({ts:_.ts,stream:_.stream,chunk:_.chunk}),v=!0);return v?(o.current.size>12e3&&o.current.clear(),g.set(h,y.slice(-s)),g):b})};return c.useEffect(()=>{const h=new Set(t.map(j=>j.id));a(j=>{const b=new Map;for(const[g,y]of j)h.has(g)&&b.set(g,y);return b.size===j.size?j:b});for(const j of i.current.keys()){const b=j.replace(/:records$/,"");h.has(b)||i.current.delete(j)}for(const j of l.current.keys())h.has(j)||l.current.delete(j)},[t]),c.useEffect(()=>{if(t.length===0)return;let h=!1;const j=async y=>{const v=l.current.get(y.id)??0;try{const _=await Yt.log(y.id,v,CL);if(h)return;if(x(y.id,SL(y.id,_.content,i.current)),_.nextOffset!==void 0){l.current.set(y.id,_.nextOffset);return}_.content.length>0&&l.current.set(y.id,v+_.content.length)}catch{}},b=async()=>{await Promise.all(t.map(y=>j(y)))};b();const g=window.setInterval(()=>{b()},kL);return()=>{h=!0,window.clearInterval(g)}},[p,t]),c.useEffect(()=>{if(!n||m.size===0)return;let h=!1,j=null,b=null;const g=()=>{h||(j=window.setTimeout(y,1500))},y=()=>{if(h)return;const _=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/companies/${encodeURIComponent(n)}/events/ws`;b=new WebSocket(_),b.onmessage=E=>{const S=typeof E.data=="string"?E.data:"";if(!S)return;let M;try{M=JSON.parse(S)}catch{return}if(M.companyId!==n)return;const B=M.payload??{},k=Or(B.runId);if(!(!k||!m.has(k))&&d.has(k)){if(M.type==="heartbeat.run.log"){const L=Or(B.chunk);if(!L)return;const $=Or(B.ts)??M.createdAt,C=Or(B.stream)==="stderr"?"stderr":Or(B.stream)==="system"?"system":"stdout";x(k,[{ts:$,stream:C,chunk:L,dedupeKey:`log:${k}:${$}:${C}:${L}`}]);return}if(M.type==="heartbeat.run.event"){const L=typeof B.seq=="number"?B.seq:null,$=Or(B.eventType)??"event",C=Or(B.message)??$;x(k,[{ts:M.createdAt,stream:$==="error"?"stderr":"system",chunk:C,dedupeKey:`socket:event:${k}:${L??`${$}:${C}:${M.createdAt}`}`}]);return}if(M.type==="heartbeat.run.status"){const L=Or(B.status)??"updated";x(k,[{ts:M.createdAt,stream:dg(L)&&L!=="succeeded"?"stderr":"system",chunk:`run ${L}`,dedupeKey:`socket:status:${k}:${L}:${Or(B.finishedAt)??""}`}])}}},b.onerror=()=>{b==null||b.close()},b.onclose=()=>{g()}};return y(),()=>{h=!0,j!==null&&window.clearTimeout(j),b&&(b.onmessage=null,b.onerror=null,b.onclose=null,b.close(1e3,"live_run_transcripts_unmount"))}},[m,n,d]),{transcriptByRun:c.useMemo(()=>{const h=new Map,j=(u==null?void 0:u.censorUsernameInLogs)===!0;for(const b of t){const g=oo(b.adapterType);h.set(b.id,ew(r.get(b.id)??[],g.parseStdoutLine,{censorUsernameInLogs:j}))}return h},[r,u==null?void 0:u.censorUsernameInLogs,t]),hasOutputForRun(h){var j;return(((j=r.get(h))==null?void 0:j.length)??0)>0}}}const IL=4;function _L(t){return t.status==="queued"||t.status==="running"}function AL({companyId:t}){const{data:n}=oe({queryKey:[...N.liveRuns(t),"dashboard"],queryFn:()=>Yt.liveRunsForCompany(t,IL)}),s=n??[],{data:r}=oe({queryKey:N.issues.list(t),queryFn:()=>nt.list(t),enabled:s.length>0}),a=c.useMemo(()=>{const l=new Map;for(const u of r??[])l.set(u.id,u);return l},[r]),{transcriptByRun:o,hasOutputForRun:i}=Fw({runs:s,companyId:t,maxChunksPerRun:120});return e.jsxs("div",{children:[e.jsx("h3",{className:"mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Agents"}),s.length===0?e.jsx("div",{className:"rounded-xl border border-border p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recent agent runs."})}):e.jsx("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2 sm:gap-4 xl:grid-cols-4",children:s.map(l=>e.jsx(EL,{run:l,issue:l.issueId?a.get(l.issueId):void 0,transcript:o.get(l.id)??[],hasOutput:i(l.id),isActive:_L(l)},l.id))})]})}function EL({run:t,issue:n,transcript:s,hasOutput:r,isActive:a}){return e.jsxs("div",{className:O("flex h-[320px] flex-col overflow-hidden rounded-xl border shadow-sm",a?"border-cyan-500/25 bg-cyan-500/[0.04] shadow-[0_16px_40px_rgba(6,182,212,0.08)]":"border-border bg-background/70"),children:[e.jsxs("div",{className:"border-b border-border/60 px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsxs("span",{className:"relative flex h-2.5 w-2.5 shrink-0",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-cyan-400 opacity-70"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-cyan-500"})]}):e.jsx("span",{className:"inline-flex h-2.5 w-2.5 rounded-full bg-muted-foreground/35"}),e.jsx(Ut,{name:t.agentName,size:"sm",className:"[&>span:last-child]:!text-[11px]"})]}),e.jsx("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-muted-foreground",children:e.jsx("span",{children:a?"Live now":t.finishedAt?`Finished ${os(t.finishedAt)}`:`Started ${os(t.createdAt)}`})})]}),e.jsx(Oe,{to:`/agents/${t.agentId}/runs/${t.id}`,className:"inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2 py-1 text-[10px] text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(Is,{className:"h-2.5 w-2.5"})})]}),t.issueId&&e.jsx("div",{className:"mt-3 rounded-lg border border-border/60 bg-background/60 px-2.5 py-2 text-xs",children:e.jsxs(Oe,{to:`/issues/${(n==null?void 0:n.identifier)??t.issueId}`,className:O("line-clamp-2 hover:underline",a?"text-cyan-700 dark:text-cyan-300":"text-muted-foreground hover:text-foreground"),title:n!=null&&n.title?`${(n==null?void 0:n.identifier)??t.issueId.slice(0,8)} - ${n.title}`:(n==null?void 0:n.identifier)??t.issueId.slice(0,8),children:[(n==null?void 0:n.identifier)??t.issueId.slice(0,8),n!=null&&n.title?` - ${n.title}`:""]})})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-3",children:e.jsx(Ni,{entries:s,density:"compact",limit:5,streaming:a,collapseStdout:!0,thinkingClassName:"!text-[10px] !leading-4",emptyMessage:r?"Waiting for transcript parsing...":a?"Waiting for output...":"No transcript captured."})})]})}function su(){return Array.from({length:14},(t,n)=>{const s=new Date;return s.setDate(s.getDate()-(13-n)),s.toISOString().slice(0,10)})}function TL(t){const n=new Date(t+"T12:00:00");return`${n.getMonth()+1}/${n.getDate()}`}function ru({days:t}){return e.jsx("div",{className:"flex gap-[3px] mt-1.5",children:t.map((n,s)=>e.jsx("div",{className:"flex-1 text-center",children:s===0||s===6||s===13?e.jsx("span",{className:"text-[9px] text-muted-foreground tabular-nums",children:TL(n)}):null},n))})}function qw({items:t}){return e.jsx("div",{className:"flex flex-wrap gap-x-2.5 gap-y-0.5 mt-2",children:t.map(n=>e.jsxs("span",{className:"flex items-center gap-1 text-[9px] text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full shrink-0",style:{backgroundColor:n.color}}),n.label]},n.label))})}function pa({title:t,subtitle:n,children:s}){return e.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-medium text-muted-foreground",children:t}),n&&e.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:n})]}),s]})}function Uw({runs:t}){const n=su(),s=new Map;for(const o of n)s.set(o,{succeeded:0,failed:0,other:0});for(const o of t){const i=new Date(o.createdAt).toISOString().slice(0,10),l=s.get(i);l&&(o.status==="succeeded"?l.succeeded++:o.status==="failed"||o.status==="timed_out"?l.failed++:l.other++)}const r=Math.max(...Array.from(s.values()).map(o=>o.succeeded+o.failed+o.other),1);return Array.from(s.values()).some(o=>o.succeeded+o.failed+o.other>0)?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-end gap-[3px] h-20",children:n.map(o=>{const i=s.get(o),l=i.succeeded+i.failed+i.other,u=l/r*100;return e.jsx("div",{className:"flex-1 h-full flex flex-col justify-end",title:`${o}: ${l} runs`,children:l>0?e.jsxs("div",{className:"flex flex-col-reverse gap-px overflow-hidden",style:{height:`${u}%`,minHeight:2},children:[i.succeeded>0&&e.jsx("div",{className:"bg-emerald-500",style:{flex:i.succeeded}}),i.failed>0&&e.jsx("div",{className:"bg-red-500",style:{flex:i.failed}}),i.other>0&&e.jsx("div",{className:"bg-neutral-500",style:{flex:i.other}})]}):e.jsx("div",{className:"bg-muted/30 rounded-sm",style:{height:2}})},o)})}),e.jsx(ru,{days:n})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No runs yet"})}const ug={critical:"#ef4444",high:"#f97316",medium:"#eab308",low:"#6b7280"},mg=["critical","high","medium","low"];function Bw({issues:t}){const n=su(),s=new Map;for(const o of n)s.set(o,{critical:0,high:0,medium:0,low:0});for(const o of t){const i=new Date(o.createdAt).toISOString().slice(0,10),l=s.get(i);l&&o.priority in l&&l[o.priority]++}const r=Math.max(...Array.from(s.values()).map(o=>Object.values(o).reduce((i,l)=>i+l,0)),1);return Array.from(s.values()).some(o=>Object.values(o).reduce((i,l)=>i+l,0)>0)?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-end gap-[3px] h-20",children:n.map(o=>{const i=s.get(o),l=Object.values(i).reduce((d,m)=>d+m,0),u=l/r*100;return e.jsx("div",{className:"flex-1 h-full flex flex-col justify-end",title:`${o}: ${l} issues`,children:l>0?e.jsx("div",{className:"flex flex-col-reverse gap-px overflow-hidden",style:{height:`${u}%`,minHeight:2},children:mg.map(d=>i[d]>0?e.jsx("div",{style:{flex:i[d],backgroundColor:ug[d]}},d):null)}):e.jsx("div",{className:"bg-muted/30 rounded-sm",style:{height:2}})},o)})}),e.jsx(ru,{days:n}),e.jsx(qw,{items:mg.map(o=>({color:ug[o],label:o.charAt(0).toUpperCase()+o.slice(1)}))})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No issues"})}const pg={todo:"#3b82f6",in_progress:"#8b5cf6",in_review:"#a855f7",done:"#10b981",blocked:"#ef4444",cancelled:"#6b7280",backlog:"#64748b"},RL={todo:"To Do",in_progress:"In Progress",in_review:"In Review",done:"Done",blocked:"Blocked",cancelled:"Cancelled",backlog:"Backlog"};function Kw({issues:t}){const n=su(),s=new Set,r=new Map;for(const l of n)r.set(l,{});for(const l of t){const u=new Date(l.createdAt).toISOString().slice(0,10),d=r.get(u);d&&(d[l.status]=(d[l.status]??0)+1,s.add(l.status))}const a=["todo","in_progress","in_review","done","blocked","cancelled","backlog"].filter(l=>s.has(l)),o=Math.max(...Array.from(r.values()).map(l=>Object.values(l).reduce((u,d)=>u+d,0)),1);return s.size>0?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-end gap-[3px] h-20",children:n.map(l=>{const u=r.get(l),d=Object.values(u).reduce((p,x)=>p+x,0),m=d/o*100;return e.jsx("div",{className:"flex-1 h-full flex flex-col justify-end",title:`${l}: ${d} issues`,children:d>0?e.jsx("div",{className:"flex flex-col-reverse gap-px overflow-hidden",style:{height:`${m}%`,minHeight:2},children:a.map(p=>(u[p]??0)>0?e.jsx("div",{style:{flex:u[p],backgroundColor:pg[p]??"#6b7280"}},p):null)}):e.jsx("div",{className:"bg-muted/30 rounded-sm",style:{height:2}})},l)})}),e.jsx(ru,{days:n}),e.jsx(qw,{items:a.map(l=>({color:pg[l]??"#6b7280",label:RL[l]??l}))})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No issues"})}function zw({runs:t}){const n=su(),s=new Map;for(const a of n)s.set(a,{succeeded:0,total:0});for(const a of t){const o=new Date(a.createdAt).toISOString().slice(0,10),i=s.get(o);i&&(i.total++,a.status==="succeeded"&&i.succeeded++)}return Array.from(s.values()).some(a=>a.total>0)?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-end gap-[3px] h-20",children:n.map(a=>{const o=s.get(a),i=o.total>0?o.succeeded/o.total:0,l=o.total===0?void 0:i>=.8?"#10b981":i>=.5?"#eab308":"#ef4444";return e.jsx("div",{className:"flex-1 h-full flex flex-col justify-end",title:`${a}: ${o.total>0?Math.round(i*100):0}% (${o.succeeded}/${o.total})`,children:o.total>0?e.jsx("div",{style:{height:`${i*100}%`,minHeight:2,backgroundColor:l}}):e.jsx("div",{className:"bg-muted/30 rounded-sm",style:{height:2}})},a)})}),e.jsx(ru,{days:n})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No runs yet"})}function Ze({className:t,...n}){return e.jsx("div",{"data-slot":"skeleton",className:O("bg-accent/75 rounded-md",t),...n})}function mn({variant:t="list"}){return t==="dashboard"?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ze,{className:"h-32 w-full border border-border"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 xl:grid-cols-4",children:Array.from({length:4}).map((n,s)=>e.jsx(Ze,{className:"h-24 w-full"},s))}),e.jsx("div",{className:"grid grid-cols-2 gap-4 lg:grid-cols-4",children:Array.from({length:4}).map((n,s)=>e.jsx(Ze,{className:"h-44 w-full"},s))}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ze,{className:"h-72 w-full"}),e.jsx(Ze,{className:"h-72 w-full"})]})]}):t==="approvals"?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Ze,{className:"h-9 w-44"})}),e.jsx("div",{className:"grid gap-3",children:Array.from({length:3}).map((n,s)=>e.jsx(Ze,{className:"h-36 w-full"},s))})]}):t==="costs"?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:Array.from({length:6}).map((n,s)=>e.jsx(Ze,{className:"h-9 w-28"},s))}),e.jsx(Ze,{className:"h-40 w-full"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ze,{className:"h-72 w-full"}),e.jsx(Ze,{className:"h-72 w-full"})]})]}):t==="inbox"?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ze,{className:"h-9 w-56"}),e.jsx(Ze,{className:"h-8 w-40"})]}),e.jsx("div",{className:"space-y-5",children:Array.from({length:3}).map((n,s)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{className:"h-4 w-40"}),e.jsx("div",{className:"space-y-1 border border-border",children:Array.from({length:3}).map((r,a)=>e.jsx(Ze,{className:"h-14 w-full rounded-none"},a))})]},s))})]}):t==="org-chart"?e.jsx("div",{className:"space-y-4",children:e.jsx(Ze,{className:"h-[calc(100vh-4rem)] w-full rounded-lg border border-border"})}):t==="detail"?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ze,{className:"h-3 w-64"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-6 w-6"}),e.jsx(Ze,{className:"h-6 w-6"}),e.jsx(Ze,{className:"h-7 w-48"})]}),e.jsx(Ze,{className:"h-4 w-40"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ze,{className:"h-10 w-full"}),e.jsx(Ze,{className:"h-32 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-8 w-24"}),e.jsx(Ze,{className:"h-8 w-24"}),e.jsx(Ze,{className:"h-8 w-24"})]}),e.jsx(Ze,{className:"h-24 w-full"}),e.jsx(Ze,{className:"h-24 w-full"})]})]}):t==="issues-list"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(Ze,{className:"h-9 w-64"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-8 w-16"}),e.jsx(Ze,{className:"h-8 w-16"}),e.jsx(Ze,{className:"h-8 w-16"}),e.jsx(Ze,{className:"h-8 w-24"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{className:"h-4 w-40"}),e.jsx("div",{className:"space-y-1",children:Array.from({length:8}).map((n,s)=>e.jsx(Ze,{className:"h-11 w-full rounded-none"},s))})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(Ze,{className:"h-9 w-44"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-8 w-20"}),e.jsx(Ze,{className:"h-8 w-24"})]})]}),e.jsx("div",{className:"space-y-1",children:Array.from({length:7}).map((n,s)=>e.jsx(Ze,{className:"h-11 w-full rounded-none"},s))})]})}function PL(t){return[...t].sort((n,s)=>new Date(s.updatedAt).getTime()-new Date(n.updatedAt).getTime())}const ML={hire_agent:"Hire Agent",approve_ceo_strategy:"CEO Strategy",budget_override_required:"Budget Override"},lp={running:"#3b82f6",succeeded:"#22c55e",failed:"#ef4444",cancelled:"#94a3b8",timed_out:"#f59e0b",queued:"#8b5cf6"};function Yu(t,n){const s=Date.now(),r=1440*60*1e3,a=s-r,o=new Map(n.map(u=>[u.id,u])),i=[...new Set(t.map(u=>u.agentId))];return{filtered:t.filter(u=>(u.startedAt?new Date(u.startedAt).getTime():new Date(u.createdAt).getTime())>=a),agentOrder:i,agentMap:o,windowStart:a,windowEnd:s}}function $L({runs:t,agents:n}){const s=c.useRef(null),r=c.useRef(null),[a,o]=c.useState({w:800,h:200}),[i,l]=c.useState(null);c.useEffect(()=>{const d=r.current;if(!d)return;const m=new ResizeObserver(([p])=>o({w:p.contentRect.width,h:p.contentRect.height}));return m.observe(d),o({w:d.clientWidth,h:d.clientHeight}),()=>m.disconnect()},[]),c.useEffect(()=>{const d=s.current;if(!d)return;const m=d.getContext("2d");if(!m)return;const{w:p,h:x}=a,{filtered:f,agentOrder:h,agentMap:j,windowStart:b,windowEnd:g}=Yu(t,n);m.clearRect(0,0,p,x);const y=110,v=16,_=24,E=28,S=p-y-v,M=x-_-E,B=h.length>0?Math.min(28,M/h.length):28,k=Math.max(6,B*.55),L=document.documentElement.classList.contains("dark"),$=L?"rgba(255,255,255,0.5)":"rgba(0,0,0,0.4)",C=L?"rgba(255,255,255,0.06)":"rgba(0,0,0,0.06)",I=L?"rgba(255,255,255,0.75)":"rgba(0,0,0,0.7)",K=T=>y+(T-b)/(g-b)*S;m.font="10px system-ui, sans-serif",m.fillStyle=$;for(let T=0;T<=4;T++){const z=b+T/4*(g-b),w=K(z),F=T===4?"now":`-${Math.round((4-T)*6)}h`;m.fillText(F,w-(T===4?12:8),x-8),m.strokeStyle=C,m.lineWidth=1,m.beginPath(),m.moveTo(w,_),m.lineTo(w,_+M),m.stroke()}h.forEach((T,z)=>{const w=_+z*B,F=j.get(T),A=(F==null?void 0:F.name)??T.slice(0,8);m.font="11px system-ui, sans-serif",m.fillStyle=I,m.fillText(A.length>12?A.slice(0,11)+"…":A,4,w+B/2+4),m.fillStyle=L?"rgba(255,255,255,0.02)":"rgba(0,0,0,0.02)",m.fillRect(y,w+2,S,B-4),f.filter(R=>R.agentId===T).forEach(R=>{const Q=R.startedAt?new Date(R.startedAt).getTime():new Date(R.createdAt).getTime(),H=R.finishedAt?new Date(R.finishedAt).getTime():g,U=Math.max(K(Q),y),Z=Math.min(K(H),y+S),V=Math.max(Z-U,3),W=w+(B-k)/2,J=lp[R.status]??"#94a3b8";m.fillStyle=J,m.globalAlpha=R.status==="running"?.9:.65,m.beginPath(),m.roundRect(U,W,V,k,2),m.fill(),m.globalAlpha=1})})},[t,n,a]);const u=d=>{var C;const m=s.current.getBoundingClientRect(),p=d.clientX-m.left,x=d.clientY-m.top,{w:f,h}=a,{filtered:j,agentOrder:b,agentMap:g,windowStart:y,windowEnd:v}=Yu(t,n),_=110,E=24,S=28,M=f-_-16,B=h-E-S,k=b.length>0?Math.min(28,B/b.length):28,L=Math.max(6,k*.55),$=I=>_+(I-y)/(v-y)*M;for(let I=0;I<b.length;I++){const K=b[I],z=E+I*k+(k-L)/2;if(!(x<z||x>z+L))for(const w of j.filter(F=>F.agentId===K)){const F=w.startedAt?new Date(w.startedAt).getTime():new Date(w.createdAt).getTime(),A=w.finishedAt?new Date(w.finishedAt).getTime():v,R=Math.max($(F),_),Q=Math.min($(A),_+M);if(p>=R&&p<=Math.max(Q,R+6)){l({x:p,y:z,run:w,agentName:((C=g.get(K))==null?void 0:C.name)??K.slice(0,8)});return}}}l(null)};return e.jsxs("div",{ref:r,className:"relative w-full",style:{height:Math.max(120,Math.min(t.length>0?Yu(t,n).agentOrder.length*32+52:120,260))},children:[e.jsx("canvas",{ref:s,width:a.w,height:a.h,className:"absolute inset-0 w-full h-full",onMouseMove:u,onMouseLeave:()=>l(null)}),i&&e.jsxs("div",{className:"absolute z-10 pointer-events-none bg-popover border border-border text-popover-foreground text-xs rounded shadow-lg px-2.5 py-1.5 max-w-[220px]",style:{left:Math.min(i.x+8,a.w-230),top:Math.max(4,i.y-44)},children:[e.jsx("div",{className:"font-medium truncate",children:i.agentName}),e.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full shrink-0",style:{backgroundColor:lp[i.run.status]??"#94a3b8"}}),e.jsx("span",{className:"capitalize",children:i.run.status}),e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:"text-muted-foreground",children:i.run.invocationSource})]}),i.run.startedAt&&e.jsx("div",{className:"text-muted-foreground mt-0.5",children:as(i.run.startedAt)})]})]})}function DL(){const{selectedCompanyId:t,companies:n}=et(),{openOnboarding:s}=In(),{setBreadcrumbs:r}=Ft(),[a,o]=c.useState(new Set),i=c.useRef(new Set),l=c.useRef(!1),u=c.useRef([]),{data:d}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t});c.useEffect(()=>{r([{label:"Dashboard"}])},[r]);const{data:m,isLoading:p,error:x}=oe({queryKey:N.dashboard(t),queryFn:()=>Px.summary(t),enabled:!!t}),{data:f}=oe({queryKey:N.activity(t),queryFn:()=>ya.list(t),enabled:!!t}),{data:h}=oe({queryKey:N.issues.list(t),queryFn:()=>nt.list(t),enabled:!!t}),{data:j}=oe({queryKey:N.projects.list(t),queryFn:()=>en.list(t),enabled:!!t}),{data:b}=oe({queryKey:N.heartbeats(t),queryFn:()=>Yt.list(t),enabled:!!t,refetchInterval:15e3}),{data:g}=oe({queryKey:N.approvals.list(t,"pending"),queryFn:()=>Wn.list(t,"pending"),enabled:!!t,refetchInterval:15e3}),y=at(),v=ge({mutationFn:C=>Wn.approve(C),onSuccess:()=>{y.invalidateQueries({queryKey:N.approvals.list(t,"pending")}),y.invalidateQueries({queryKey:N.dashboard(t)})}}),_=ge({mutationFn:C=>Wn.reject(C),onSuccess:()=>{y.invalidateQueries({queryKey:N.approvals.list(t,"pending")}),y.invalidateQueries({queryKey:N.dashboard(t)})}}),E=h?PL(h):[],S=c.useMemo(()=>(f??[]).slice(0,10),[f]);c.useEffect(()=>{for(const C of u.current)window.clearTimeout(C);u.current=[],i.current=new Set,l.current=!1,o(new Set)},[t]),c.useEffect(()=>{if(S.length===0)return;const C=i.current,I=S.map(z=>z.id);if(!l.current){for(const z of I)C.add(z);l.current=!0;return}const K=I.filter(z=>!C.has(z));if(K.length===0){for(const z of I)C.add(z);return}o(z=>{const w=new Set(z);for(const F of K)w.add(F);return w});for(const z of K)C.add(z);const T=window.setTimeout(()=>{o(z=>{const w=new Set(z);for(const F of K)w.delete(F);return w}),u.current=u.current.filter(z=>z!==T)},980);u.current.push(T)},[S]),c.useEffect(()=>()=>{for(const C of u.current)window.clearTimeout(C)},[]);const M=c.useMemo(()=>{const C=new Map;for(const I of d??[])C.set(I.id,I);return C},[d]),B=c.useMemo(()=>{const C=new Map;for(const I of h??[])C.set(`issue:${I.id}`,I.identifier??I.id.slice(0,8));for(const I of d??[])C.set(`agent:${I.id}`,I.name);for(const I of j??[])C.set(`project:${I.id}`,I.name);return C},[h,d,j]),k=c.useMemo(()=>{const C=new Map;for(const I of h??[])C.set(`issue:${I.id}`,I.title);return C},[h]),L=C=>{var I;return!C||!d?null:((I=d.find(K=>K.id===C))==null?void 0:I.name)??null};if(!t)return n.length===0?e.jsx(tn,{icon:Ka,message:"Welcome to CrewSpace. Set up your first company and agent to get started.",action:"Get Started",onAction:s}):e.jsx(tn,{icon:Ka,message:"Create or select a company to view the dashboard."});if(p)return e.jsx(mn,{variant:"dashboard"});const $=d!==void 0&&d.length===0;return e.jsxs("div",{className:"space-y-6",children:[x&&e.jsx("p",{className:"text-sm text-destructive",children:x.message}),$&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-amber-300 bg-amber-50 px-4 py-3 dark:border-amber-500/25 dark:bg-amber-950/60",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(ss,{className:"h-4 w-4 text-amber-600 dark:text-amber-400 shrink-0"}),e.jsx("p",{className:"text-sm text-amber-900 dark:text-amber-100",children:"You have no agents."})]}),e.jsx("button",{onClick:()=>s({initialStep:2,companyId:t}),className:"text-sm font-medium text-amber-700 hover:text-amber-900 dark:text-amber-300 dark:hover:text-amber-100 underline underline-offset-2 shrink-0",children:"Create one here"})]}),e.jsx(AL,{companyId:t}),m&&e.jsxs(e.Fragment,{children:[m.budgets.activeIncidents>0?e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-xl border border-red-500/20 bg-[linear-gradient(180deg,rgba(255,80,80,0.12),rgba(255,255,255,0.02))] px-4 py-3",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx($p,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-300"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-red-50",children:[m.budgets.activeIncidents," active budget incident",m.budgets.activeIncidents===1?"":"s"]}),e.jsxs("p",{className:"text-xs text-red-100/70",children:[m.budgets.pausedAgents," agents paused · ",m.budgets.pausedProjects," projects paused · ",m.budgets.pendingApprovals," pending budget approvals"]})]})]}),e.jsx(Oe,{to:"/costs",className:"text-sm underline underline-offset-2 text-red-100",children:"Open budgets"})]}):null,e.jsxs("div",{className:"grid grid-cols-2 xl:grid-cols-4 gap-1 sm:gap-2",children:[e.jsx(ma,{icon:ss,value:m.agents.active+m.agents.running+m.agents.paused+m.agents.error,label:"Agents Enabled",to:"/agents",description:e.jsxs("span",{children:[m.agents.running," running",", ",m.agents.paused," paused",", ",m.agents.error," errors"]})}),e.jsx(ma,{icon:rs,value:m.tasks.inProgress,label:"Tasks In Progress",to:"/issues",description:e.jsxs("span",{children:[m.tasks.open," open",", ",m.tasks.blocked," blocked"]})}),e.jsx(ma,{icon:wr,value:ot(m.costs.monthSpendCents),label:"Month Spend",to:"/costs",description:e.jsx("span",{children:m.costs.monthBudgetCents>0?`${m.costs.monthUtilizationPercent}% of ${ot(m.costs.monthBudgetCents)} budget`:"Unlimited budget"})}),e.jsx(ma,{icon:kc,value:m.pendingApprovals+m.budgets.pendingApprovals,label:"Pending Approvals",to:"/approvals",description:e.jsx("span",{children:m.budgets.pendingApprovals>0?`${m.budgets.pendingApprovals} budget overrides awaiting board review`:"Awaiting board review"})})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(pa,{title:"Run Activity",subtitle:"Last 14 days",children:e.jsx(Uw,{runs:b??[]})}),e.jsx(pa,{title:"Issues by Priority",subtitle:"Last 14 days",children:e.jsx(Bw,{issues:h??[]})}),e.jsx(pa,{title:"Issues by Status",subtitle:"Last 14 days",children:e.jsx(Kw,{issues:h??[]})}),e.jsx(pa,{title:"Success Rate",subtitle:"Last 14 days",children:e.jsx(zw,{runs:b??[]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5",children:[e.jsx(Yo,{className:"h-3.5 w-3.5"}),"Workflow Executions",e.jsx("span",{className:"text-xs font-normal normal-case text-muted-foreground/60",children:"· last 24h"})]}),(b??[]).filter(C=>C.status==="running").length>0&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-blue-500 font-medium",children:[e.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-blue-500 animate-pulse"}),(b??[]).filter(C=>C.status==="running").length," live"]})]}),e.jsxs("div",{className:"border border-border rounded-lg p-3 bg-card",children:[b&&b.length>0&&d&&d.length>0?e.jsx($L,{runs:b,agents:d}):e.jsx("div",{className:"h-[80px] flex items-center justify-center text-sm text-muted-foreground",children:"No executions in the last 24 hours"}),e.jsx("div",{className:"flex items-center gap-4 mt-3 pt-3 border-t border-border/50 flex-wrap",children:["running","succeeded","failed","queued","cancelled","timed_out"].map(C=>e.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm",style:{backgroundColor:lp[C]}}),e.jsx("span",{className:"capitalize",children:C.replace("_"," ")}),e.jsxs("span",{className:"text-muted-foreground/50",children:["(",(b??[]).filter(I=>I.status===C).length,")"]})]},C))})]})]}),((g==null?void 0:g.length)??0)>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5",children:[e.jsx(kc,{className:"h-3.5 w-3.5"}),"Pending Approvals",e.jsx("span",{className:"ml-1 inline-flex items-center justify-center rounded-full bg-amber-500/15 text-amber-600 dark:text-amber-400 text-xs font-semibold px-1.5 py-px min-w-[18px]",children:g.length})]}),e.jsx(Oe,{to:"/approvals",className:"text-xs text-muted-foreground hover:text-foreground underline underline-offset-2",children:"View all"})]}),e.jsxs("div",{className:"border border-border rounded-lg divide-y divide-border overflow-hidden",children:[g.slice(0,5).map(C=>{var z;const I=(z=d==null?void 0:d.find(w=>w.id===C.requestedByAgentId))==null?void 0:z.name,K=v.isPending&&v.variables===C.id,T=_.isPending&&_.variables===C.id;return e.jsxs("div",{className:"flex items-start gap-3 px-4 py-3 bg-card hover:bg-accent/30 transition-colors",children:[e.jsx("div",{className:"mt-0.5 flex-shrink-0",children:e.jsx(_r,{className:"h-4 w-4 text-amber-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-xs font-medium px-1.5 py-px rounded bg-muted text-muted-foreground",children:ML[C.type]??C.type}),I&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Xo,{className:"h-3 w-3"}),I]}),C.requestedByUserId&&!I&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ns,{className:"h-3 w-3"}),"User"]})]}),C.payload&&Object.keys(C.payload).length>0&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-1",children:C.payload.reason??C.payload.description??JSON.stringify(C.payload).slice(0,80)}),e.jsx("p",{className:"text-xs text-muted-foreground/60 mt-0.5",children:as(C.createdAt)})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 mt-0.5",children:[e.jsxs("button",{onClick:()=>v.mutate(C.id),disabled:K||T,className:O("flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-md transition-colors","bg-green-500/10 text-green-600 dark:text-green-400 hover:bg-green-500/20",(K||T)&&"opacity-50 pointer-events-none"),children:[e.jsx(ho,{className:"h-3.5 w-3.5"}),K?"…":"Approve"]}),e.jsxs("button",{onClick:()=>_.mutate(C.id),disabled:K||T,className:O("flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-md transition-colors","bg-red-500/10 text-red-600 dark:text-red-400 hover:bg-red-500/20",(K||T)&&"opacity-50 pointer-events-none"),children:[e.jsx(fi,{className:"h-3.5 w-3.5"}),T?"…":"Reject"]})]})]},C.id)}),g.length>5&&e.jsxs(Oe,{to:"/approvals",className:"block px-4 py-2.5 text-xs text-center text-muted-foreground hover:text-foreground hover:bg-accent/30 transition-colors no-underline",children:["+ ",g.length-5," more pending approvals"]})]})]}),e.jsx(Vr,{slotTypes:["dashboardWidget"],context:{companyId:t},className:"grid gap-4 md:grid-cols-2",itemClassName:"rounded-lg border bg-card p-4 shadow-sm"}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[S.length>0&&e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3",children:"Recent Activity"}),e.jsx("div",{className:"border border-border divide-y divide-border overflow-hidden",children:S.map(C=>e.jsx(rw,{event:C,agentMap:M,entityNameMap:B,entityTitleMap:k,className:a.has(C.id)?"activity-row-enter":void 0},C.id))})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3",children:"Recent Tasks"}),E.length===0?e.jsx("div",{className:"border border-border p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No tasks yet."})}):e.jsx("div",{className:"border border-border divide-y divide-border overflow-hidden",children:E.slice(0,10).map(C=>e.jsx(Oe,{to:`/issues/${C.identifier??C.id}`,className:"px-4 py-3 text-sm cursor-pointer hover:bg-accent/50 transition-colors no-underline text-inherit block",children:e.jsxs("div",{className:"flex items-start gap-2 sm:items-center sm:gap-3",children:[e.jsx("span",{className:"shrink-0 sm:hidden",children:e.jsx(Pn,{status:C.status})}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-1 sm:contents",children:[e.jsx("span",{className:"line-clamp-2 text-sm sm:order-2 sm:flex-1 sm:min-w-0 sm:line-clamp-none sm:truncate",children:C.title}),e.jsxs("span",{className:"flex items-center gap-2 sm:order-1 sm:shrink-0",children:[e.jsx("span",{className:"hidden sm:inline-flex",children:e.jsx(Pn,{status:C.status})}),e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:C.identifier??C.id.slice(0,8)}),C.assigneeAgentId&&(()=>{const I=L(C.assigneeAgentId);return I?e.jsx("span",{className:"hidden sm:inline-flex",children:e.jsx(Ut,{name:I,size:"sm"})}):null})(),e.jsx("span",{className:"text-xs text-muted-foreground sm:hidden",children:"·"}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0 sm:order-last",children:as(C.updatedAt)})]})]})]})},C.id))})]})]})]})]})}function gl({...t}){return e.jsx(bI,{"data-slot":"dropdown-menu",...t})}function bl({...t}){return e.jsx(yI,{"data-slot":"dropdown-menu-trigger",...t})}function yl({className:t,sideOffset:n=4,...s}){return e.jsx(vI,{children:e.jsx(jI,{"data-slot":"dropdown-menu-content",sideOffset:n,className:O("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...s})})}function Os({className:t,inset:n,variant:s="default",...r}){return e.jsx(NI,{"data-slot":"dropdown-menu-item","data-inset":n,"data-variant":s,className:O("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function OL({className:t,children:n,checked:s,...r}){return e.jsxs(kI,{"data-slot":"dropdown-menu-checkbox-item",className:O("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),checked:s,...r,children:[e.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:e.jsx(uv,{children:e.jsx(Nn,{className:"size-4"})})}),n]})}function LL({...t}){return e.jsx(CI,{"data-slot":"dropdown-menu-radio-group",...t})}function FL({className:t,children:n,...s}){return e.jsxs(SI,{"data-slot":"dropdown-menu-radio-item",className:O("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s,children:[e.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:e.jsx(uv,{children:e.jsx(Yb,{className:"size-2 fill-current"})})}),n]})}function qL({className:t,inset:n,...s}){return e.jsx(wI,{"data-slot":"dropdown-menu-label","data-inset":n,className:O("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",t),...s})}function au({className:t,...n}){return e.jsx(II,{"data-slot":"dropdown-menu-separator",className:O("bg-border -mx-1 my-1 h-px",t),...n})}function UL({className:t,...n}){return e.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:O("text-muted-foreground ml-auto text-xs tracking-widest",t),...n})}function BL(){const{companies:t,selectedCompanyId:n,setSelectedCompanyId:s,loading:r,error:a}=et(),{openOnboarding:o}=In(),{setBreadcrumbs:i}=Ft(),l=at(),{data:u}=oe({queryKey:N.companies.stats,queryFn:()=>ls.stats()}),[d,m]=c.useState(null),[p,x]=c.useState(""),[f,h]=c.useState(null),j=ge({mutationFn:({id:_,newName:E})=>ls.update(_,{name:E}),onSuccess:()=>{l.invalidateQueries({queryKey:N.companies.all}),m(null)}}),b=ge({mutationFn:_=>ls.remove(_),onSuccess:()=>{l.invalidateQueries({queryKey:N.companies.all}),l.invalidateQueries({queryKey:N.companies.stats}),h(null)}});c.useEffect(()=>{i([{label:"Companies"}])},[i]);function g(_,E){m(_),x(E)}function y(){!d||!p.trim()||j.mutate({id:d,newName:p.trim()})}function v(){m(null),x("")}return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(G,{size:"sm",onClick:()=>o(),children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1.5"}),"New Company"]})}),e.jsxs("div",{className:"h-6",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading companies..."}),a&&e.jsx("p",{className:"text-sm text-destructive",children:a.message})]}),e.jsx("div",{className:"grid gap-4",children:t.map(_=>{const E=_.id===n,S=d===_.id,M=f===_.id,B=u==null?void 0:u[_.id],k=(B==null?void 0:B.agentCount)??0,L=(B==null?void 0:B.issueCount)??0,$=_.budgetMonthlyCents>0?Math.round(_.spentMonthlyCents/_.budgetMonthlyCents*100):0;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>s(_.id),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),s(_.id))},className:`group text-left bg-card border rounded-lg p-5 transition-colors cursor-pointer ${E?"border-primary ring-1 ring-primary":"border-border hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[S?e.jsxs("div",{className:"flex items-center gap-2",onClick:C=>C.stopPropagation(),children:[e.jsx(Xt,{value:p,onChange:C=>x(C.target.value),className:"h-7 text-sm",autoFocus:!0,onKeyDown:C=>{C.key==="Enter"&&y(),C.key==="Escape"&&v()}}),e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:y,disabled:j.isPending,children:e.jsx(Nn,{className:"h-3.5 w-3.5 text-green-500"})}),e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:v,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground"})})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base",children:_.name}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${_.status==="active"?"bg-green-500/10 text-green-600 dark:text-green-400":_.status==="paused"?"bg-yellow-500/10 text-yellow-600 dark:text-yellow-400":"bg-muted text-muted-foreground"}`,children:_.status}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground opacity-0 group-hover:opacity-100",onClick:C=>{C.stopPropagation(),g(_.id,_.name)},children:e.jsx(Cc,{className:"h-3 w-3"})})]}),_.description&&!S&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:_.description})]}),e.jsx("div",{onClick:C=>C.stopPropagation(),children:e.jsxs(gl,{children:[e.jsx(bl,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100",children:e.jsx(xi,{className:"h-4 w-4"})})}),e.jsxs(yl,{align:"end",children:[e.jsxs(Os,{onClick:()=>g(_.id,_.name),children:[e.jsx(Cc,{className:"h-3.5 w-3.5"}),"Rename"]}),e.jsx(au,{}),e.jsxs(Os,{variant:"destructive",onClick:()=>h(_.id),children:[e.jsx(Ls,{className:"h-3.5 w-3.5"}),"Delete Company"]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-3 sm:gap-5 mt-4 text-sm text-muted-foreground flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Mp,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[k," ",k===1?"agent":"agents"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(rs,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[L," ",L===1?"issue":"issues"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 tabular-nums",children:[e.jsx(wr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[ot(_.spentMonthlyCents),_.budgetMonthlyCents>0?e.jsxs(e.Fragment,{children:[" / ",ot(_.budgetMonthlyCents)," ",e.jsxs("span",{className:"text-xs",children:["(",$,"%)"]})]}):e.jsx("span",{className:"text-xs ml-1",children:"Unlimited budget"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[e.jsx(Nc,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:["Created ",os(_.createdAt)]})]})]}),M&&e.jsxs("div",{className:"mt-4 flex items-center justify-between bg-destructive/5 border border-destructive/20 rounded-md px-4 py-3",onClick:C=>C.stopPropagation(),children:[e.jsx("p",{className:"text-sm text-destructive font-medium",children:"Delete this company and all its data? This cannot be undone."}),e.jsxs("div",{className:"flex items-center gap-2 ml-4 shrink-0",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>h(null),disabled:b.isPending,children:"Cancel"}),e.jsx(G,{variant:"destructive",size:"sm",onClick:()=>b.mutate(_.id),disabled:b.isPending,children:b.isPending?"Deleting…":"Delete"})]})]})]},_.id)})})]})}function gr({leading:t,identifier:n,title:s,subtitle:r,trailing:a,selected:o,to:i,onClick:l,className:u}){const m=O("flex items-center gap-3 px-4 py-2 text-sm border-b border-border last:border-b-0 transition-colors",!!(i||l)&&"cursor-pointer hover:bg-accent/50",o&&"bg-accent/30",u),p=e.jsxs(e.Fragment,{children:[t&&e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:t}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx("span",{className:"text-xs text-muted-foreground font-mono shrink-0 relative top-[1px]",children:n}),e.jsx("span",{className:"truncate",children:s})]}),r&&e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:r})]}),a&&e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a})]});return i?e.jsx(Oe,{to:i,className:O(m,"no-underline text-inherit"),onClick:l,children:p}):e.jsx("div",{className:m,onClick:l,children:p})}function Ss({className:t,orientation:n="horizontal",...s}){return e.jsx(HI,{"data-slot":"tabs","data-orientation":n,orientation:n,className:O("group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",t),...s})}const KL=Cp("p-[3px] group-data-[orientation=horizontal]/tabs:h-9 group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function co({className:t,variant:n="default",...s}){return e.jsx(VI,{"data-slot":"tabs-list","data-variant":n,className:O(KL({variant:n}),t),...s})}function An({className:t,...n}){return e.jsx(QI,{"data-slot":"tabs-trigger",className:O("focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow] group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent","data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground","after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",t),...n})}function on({className:t,...n}){return e.jsx(GI,{"data-slot":"tabs-content",className:O("flex-1 outline-none",t),...n})}function Ca({items:t,value:n,onValueChange:s,align:r="center"}){const{isMobile:a}=mr();return a&&n!==void 0&&s?e.jsx("select",{value:n,onChange:o=>s(o.target.value),className:"h-9 rounded-md border border-border bg-background px-2 py-1 text-base focus:outline-none focus:ring-1 focus:ring-ring",children:t.map(o=>e.jsx("option",{value:o.value,children:typeof o.label=="string"?o.label:o.value},o.value))}):e.jsx(co,{variant:"line",className:r==="start"?"justify-start":void 0,children:t.map(o=>e.jsx(An,{value:o.value,children:o.label},o.value))})}const Ww={claude_local:"Claude",codex_local:"Codex",gemini_local:"Gemini",opencode_local:"OpenCode",cursor:"Cursor",hermes_local:"Hermes",openclaw_gateway:"OpenClaw Gateway",process:"Process",http:"HTTP"},Hw=rx;function Vw(t,n,s){return t==="terminated"?s:n==="all"?!0:n==="active"?t==="active"||t==="running"||t==="idle":n==="paused"?t==="paused":n==="error"?t==="error":!0}function zL(t,n,s){return t.filter(r=>Vw(r.status,n,s)).sort((r,a)=>r.name.localeCompare(a.name))}function Qw(t,n,s){return t.reduce((r,a)=>{const o=Qw(a.reports,n,s);return(Vw(a.status,n,s)||o.length>0)&&r.push({...a,reports:o}),r},[]).sort((r,a)=>r.name.localeCompare(a.name))}function nc(){const{selectedCompanyId:t}=et(),{openNewAgent:n}=In(),{setBreadcrumbs:s}=Ft(),r=Sn(),a=fn(),{isMobile:o}=mr(),i=a.pathname.split("/").pop()??"all",l=i==="all"||i==="active"||i==="paused"||i==="error"?i:"all",[u,d]=c.useState("org"),m=o,p=m?"list":u,[x,f]=c.useState(!1),[h,j]=c.useState(!1),{data:b,isLoading:g,error:y}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),{data:v}=oe({queryKey:N.org(t),queryFn:()=>We.org(t),enabled:!!t&&p==="org"}),{data:_}=oe({queryKey:N.heartbeats(t),queryFn:()=>Yt.list(t),enabled:!!t,refetchInterval:15e3}),E=c.useMemo(()=>{const k=new Map;for(const L of _??[]){if(L.status!=="running"&&L.status!=="queued")continue;const $=k.get(L.agentId);if($){$.liveCount+=1;continue}k.set(L.agentId,{runId:L.id,liveCount:1})}return k},[_]),S=c.useMemo(()=>{const k=new Map;for(const L of b??[])k.set(L.id,L);return k},[b]);if(c.useEffect(()=>{s([{label:"Agents"}])},[s]),!t)return e.jsx(tn,{icon:ss,message:"Select a company to view agents."});if(g)return e.jsx(mn,{variant:"list"});const M=zL(b??[],l,x),B=Qw(v??[],l,x);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(Ss,{value:l,onValueChange:k=>r(`/agents/${k}`),children:e.jsx(Ca,{items:[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"paused",label:"Paused"},{value:"error",label:"Error"}],value:l,onValueChange:k=>r(`/agents/${k}`)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsxs("button",{className:O("flex items-center gap-1.5 px-2 py-1.5 text-xs transition-colors border border-border",h||x?"text-foreground bg-accent":"text-muted-foreground hover:bg-accent/50"),onClick:()=>j(!h),children:[e.jsx(rl,{className:"h-3 w-3"}),"Filters",x&&e.jsx("span",{className:"ml-0.5 px-1 bg-foreground/10 rounded text-[10px]",children:"1"})]}),h&&e.jsx("div",{className:"absolute right-0 top-full mt-1 z-50 w-48 border border-border bg-popover shadow-md p-1",children:e.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs text-left hover:bg-accent/50 transition-colors",onClick:()=>f(!x),children:[e.jsx("span",{className:O("flex items-center justify-center h-3.5 w-3.5 border border-border rounded-sm",x&&"bg-foreground"),children:x&&e.jsx("span",{className:"text-background text-[10px] leading-none",children:"✓"})}),"Show terminated"]})})]}),!m&&e.jsxs("div",{className:"flex items-center border border-border",children:[e.jsx("button",{className:O("p-1.5 transition-colors",p==="list"?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:()=>d("list"),children:e.jsx(Xb,{className:"h-3.5 w-3.5"})}),e.jsx("button",{className:O("p-1.5 transition-colors",p==="org"?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:()=>d("org"),children:e.jsx(Yo,{className:"h-3.5 w-3.5"})})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:n,children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1.5"}),"New Agent"]})]})]}),M.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[M.length," agent",M.length!==1?"s":""]}),y&&e.jsx("p",{className:"text-sm text-destructive",children:y.message}),b&&b.length===0&&e.jsx(tn,{icon:ss,message:"Create your first agent to get started.",action:"New Agent",onAction:n}),p==="list"&&M.length>0&&e.jsx("div",{className:"border border-border",children:M.map(k=>e.jsx(gr,{title:k.name,subtitle:`${Hw[k.role]??k.role}${k.title?` - ${k.title}`:""}`,to:Na(k),leading:e.jsx("span",{className:"relative flex h-2.5 w-2.5",children:e.jsx("span",{className:`absolute inline-flex h-full w-full rounded-full ${Fx[k.status]??qx}`})}),trailing:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"sm:hidden",children:E.has(k.id)?e.jsx(ld,{agentRef:so(k),runId:E.get(k.id).runId,liveCount:E.get(k.id).liveCount}):e.jsx(Dt,{status:k.status})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3",children:[E.has(k.id)&&e.jsx(ld,{agentRef:so(k),runId:E.get(k.id).runId,liveCount:E.get(k.id).liveCount}),e.jsx("span",{className:"text-xs text-muted-foreground font-mono w-14 text-right",children:Ww[k.adapterType]??k.adapterType}),e.jsx("span",{className:"text-xs text-muted-foreground w-16 text-right",children:k.lastHeartbeatAt?os(k.lastHeartbeatAt):"—"}),e.jsx("span",{className:"w-20 flex justify-end",children:e.jsx(Dt,{status:k.status})})]})]})},k.id))}),p==="list"&&b&&b.length>0&&M.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No agents match the selected filter."}),p==="org"&&B.length>0&&e.jsx("div",{className:"border border-border py-1",children:B.map(k=>e.jsx(Gw,{node:k,depth:0,agentMap:S,liveRunByAgent:E},k.id))}),p==="org"&&v&&v.length>0&&B.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No agents match the selected filter."}),p==="org"&&v&&v.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No organizational hierarchy defined."})]})}function Gw({node:t,depth:n,agentMap:s,liveRunByAgent:r}){const a=s.get(t.id),o=Fx[t.status]??qx;return e.jsxs("div",{style:{paddingLeft:n*24},children:[e.jsxs(Oe,{to:a?Na(a):`/agents/${t.id}`,className:"flex items-center gap-3 px-3 py-2 hover:bg-accent/30 transition-colors w-full text-left no-underline text-inherit",children:[e.jsx("span",{className:"relative flex h-2.5 w-2.5 shrink-0",children:e.jsx("span",{className:`absolute inline-flex h-full w-full rounded-full ${o}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium",children:t.name}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:[Hw[t.role]??t.role,a!=null&&a.title?` - ${a.title}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx("span",{className:"sm:hidden",children:r.has(t.id)?e.jsx(ld,{agentRef:a?so(a):t.id,runId:r.get(t.id).runId,liveCount:r.get(t.id).liveCount}):e.jsx(Dt,{status:t.status})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3",children:[r.has(t.id)&&e.jsx(ld,{agentRef:a?so(a):t.id,runId:r.get(t.id).runId,liveCount:r.get(t.id).liveCount}),a&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs text-muted-foreground font-mono w-14 text-right",children:Ww[a.adapterType]??a.adapterType}),e.jsx("span",{className:"text-xs text-muted-foreground w-16 text-right",children:a.lastHeartbeatAt?os(a.lastHeartbeatAt):"—"})]}),e.jsx("span",{className:"w-20 flex justify-end",children:e.jsx(Dt,{status:t.status})})]})]})]}),t.reports&&t.reports.length>0&&e.jsx("div",{className:"border-l border-border/50 ml-4",children:t.reports.map(i=>e.jsx(Gw,{node:i,depth:n+1,agentMap:s,liveRunByAgent:r},i.id))})]})}function ld({agentRef:t,runId:n,liveCount:s}){return e.jsxs(Oe,{to:`/agents/${t}/runs/${n}`,className:"flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-blue-500/10 hover:bg-blue-500/20 transition-colors no-underline",onClick:r=>r.stopPropagation(),children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}),e.jsxs("span",{className:"text-[11px] font-medium text-blue-600 dark:text-blue-400",children:["Live",s>1?` (${s})`:""]})]})}const nr={list:t=>ne.get(`/companies/${encodeURIComponent(t)}/skills`),detail:(t,n)=>ne.get(`/companies/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}`),updateStatus:(t,n)=>ne.get(`/companies/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}/update-status`),file:(t,n,s)=>ne.get(`/companies/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}/files?path=${encodeURIComponent(s)}`),updateFile:(t,n,s,r)=>ne.patch(`/companies/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}/files`,{path:s,content:r}),create:(t,n)=>ne.post(`/companies/${encodeURIComponent(t)}/skills`,n),importFromSource:(t,n)=>ne.post(`/companies/${encodeURIComponent(t)}/skills/import`,{source:n}),scanProjects:(t,n={})=>ne.post(`/companies/${encodeURIComponent(t)}/skills/scan-projects`,n),installUpdate:(t,n)=>ne.post(`/companies/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}/install-update`,{})},Wa={overview:t=>ne.get(`/companies/${t}/budgets/overview`),upsertPolicy:(t,n)=>ne.post(`/companies/${t}/budgets/policies`,n),resolveIncident:(t,n,s)=>ne.post(`/companies/${t}/budget-incidents/${encodeURIComponent(n)}/resolve`,s)},xg={list:t=>ne.get(`/companies/${t}/secrets`),providers:t=>ne.get(`/companies/${t}/secret-providers`),create:(t,n)=>ne.post(`/companies/${t}/secrets`,n),rotate:(t,n)=>ne.post(`/secrets/${t}/rotate`,n),update:(t,n)=>ne.patch(`/secrets/${t}`,n),remove:t=>ne.delete(`/secrets/${t}`)};function Jw({agents:t,value:n,onChange:s,disabled:r=!1,excludeAgentIds:a=[],disabledEmptyLabel:o="Reports to: N/A (CEO)",chooseLabel:i="Reports to..."}){const[l,u]=c.useState(!1),d=new Set(a),m=t.filter(h=>h.status!=="terminated"&&!d.has(h.id)),p=n?t.find(h=>h.id===n):null,x=(p==null?void 0:p.status)==="terminated",f=!!(n&&!p);return e.jsxs(Ht,{open:l,onOpenChange:u,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:O("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",x&&"border-amber-600/45 bg-amber-500/5",r&&"opacity-60 cursor-not-allowed"),disabled:r,children:f?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:"Unknown manager (stale ID)"})]}):p?e.jsxs(e.Fragment,{children:[e.jsx(Cn,{icon:p.icon,className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:O("min-w-0 truncate",x&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${x?" (terminated)":""}`})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate",children:r?o:i})]})})}),e.jsxs(Qt,{className:"w-48 p-1",align:"start",children:[e.jsx("button",{type:"button",className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",n===null&&"bg-accent"),onClick:()=>{s(null),u(!1)},children:"No manager"}),x&&e.jsxs("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[e.jsx(Cn,{icon:p.icon,className:"shrink-0 h-3 w-3"}),e.jsxs("span",{className:"min-w-0 truncate",children:["Current: ",p.name," (terminated)"]})]}),f&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:"Saved manager is missing from this company. Choose a new manager or clear."}),m.map(h=>e.jsxs("button",{type:"button",className:O("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",h.id===n&&"bg-accent"),onClick:()=>{s(h.id),u(!1)},children:[e.jsx(Cn,{icon:h.icon,className:"shrink-0 h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate",children:h.name}),e.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:ed[h.role]??h.role})]},h.id))]})]})}function WL(t){if(typeof t!="string")return null;const n=t.trim();return n.length>0?n:null}function HL(t){return WL(t)!==null}function VL(t){var n;return t.isCreate?!1:HL((n=t.adapterConfig)==null?void 0:n.cwd)}const Xu={identity:{},adapterConfig:{},heartbeat:{},runtime:{}},fg={};function QL(t){return Object.keys(t.identity).length>0||t.adapterType!==void 0||Object.keys(t.adapterConfig).length>0||Object.keys(t.heartbeat).length>0||Object.keys(t.runtime).length>0}const Hs="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function GL(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function JL(t){return Array.isArray(t)?t.filter(n=>typeof n=="string").join(", "):typeof t=="string"?t:""}const ZL=[{id:"",label:"Auto"},{id:"minimal",label:"Minimal"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"},{id:"xhigh",label:"X-High"}],YL=[{id:"",label:"Auto"},{id:"minimal",label:"Minimal"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"},{id:"xhigh",label:"X-High"},{id:"max",label:"Max"}],XL=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],eF=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}];function sf(t){const{mode:n,adapterModels:s}=t,r=n==="create",a=t.sectionLayout==="cards",o=t.showAdapterTypeField??!0,i=t.showAdapterTestEnvironmentButton??!0,l=t.showCreateRunPolicySection??!0,u=t.hideInstructionsFile??!1,{selectedCompanyId:d}=et(),m=at(),{data:p=[]}=oe({queryKey:d?N.secrets.list(d):["secrets","none"],queryFn:()=>xg.list(d),enabled:!!d}),x=ge({mutationFn:q=>{if(!d)throw new Error("Select a company to create secrets");return xg.create(d,q)},onSuccess:()=>{d&&m.invalidateQueries({queryKey:N.secrets.list(d)})}}),f=ge({mutationFn:async({file:q,namespace:D})=>{if(!d)throw new Error("Select a company to upload images");return Aa.uploadImage(d,q,D)}}),[h,j]=c.useState(Xu),b=c.useRef(null);c.useEffect(()=>{r||(b.current!==null&&t.agent!==b.current&&j({...Xu}),b.current=t.agent)},[r,r?void 0:t.agent]);const g=!r&&QL(h);function y(q,D,ie){const Ie=h[q];return D in Ie?Ie[D]:ie}function v(q,D,ie){j(Ie=>({...Ie,[q]:{...Ie[q],[D]:ie}}))}const _=c.useCallback(()=>{j({...Xu})},[]),E=c.useCallback(()=>{if(r||!g)return;const q=t.agent,D={};if(Object.keys(h.identity).length>0&&Object.assign(D,h.identity),h.adapterType!==void 0){D.adapterType=h.adapterType;const ie=q.adapterConfig??{},Ie=["env","promptTemplate","instructionsFilePath","cwd","timeoutSec","graceSec","bootstrapPromptTemplate"],ue={};for(const Be of Ie)Be in ie&&(ue[Be]=ie[Be]);D.adapterConfig={...ue,...h.adapterConfig}}else if(Object.keys(h.adapterConfig).length>0){const ie=q.adapterConfig??{};D.adapterConfig={...ie,...h.adapterConfig}}if(Object.keys(h.heartbeat).length>0){const ie=q.runtimeConfig??{},Ie=ie.heartbeat??{};D.runtimeConfig={...ie,heartbeat:{...Ie,...h.heartbeat}}}Object.keys(h.runtime).length>0&&Object.assign(D,h.runtime),t.onSave(D)},[r,g,h,t]);c.useEffect(()=>{var q,D,ie;r||((q=t.onDirtyChange)==null||q.call(t,g),(D=t.onSaveActionChange)==null||D.call(t,E),(ie=t.onCancelActionChange)==null||ie.call(t,_))},[r,g,t.onDirtyChange,t.onSaveActionChange,t.onCancelActionChange,E,_]),c.useEffect(()=>{if(!r)return()=>{var q,D,ie;(q=t.onSaveActionChange)==null||q.call(t,null),(D=t.onCancelActionChange)==null||D.call(t,null),(ie=t.onDirtyChange)==null||ie.call(t,!1)}},[r,t.onDirtyChange,t.onSaveActionChange,t.onCancelActionChange]);const S=r?{}:t.agent.adapterConfig??{},M=r?{}:t.agent.runtimeConfig??{},B=r?{}:M.heartbeat??{},k=r?t.values.adapterType:h.adapterType??t.agent.adapterType,L=k==="claude_local"||k==="codex_local"||k==="gemini_local"||k==="hermes_local"||k==="opencode_local"||k==="pi_local"||k==="cursor",$=k==="hermes_local",C=L&&VL({isCreate:r,adapterConfig:S}),I=c.useMemo(()=>oo(k),[k]),{data:K,error:T}=oe({queryKey:d?N.agents.adapterModels(d,k):["agents","none","adapter-models",k],queryFn:()=>We.adapterModels(d,k),enabled:!!d}),z=K??s??[],{data:w,refetch:F}=oe({queryKey:d?N.agents.detectModel(d,k):["agents","none","detect-model",k],queryFn:()=>{if(!d)throw new Error("Select a company to detect the Hermes model");return We.detectModel(d,k)},enabled:!!(d&&$)}),A=(w==null?void 0:w.model)??null,{data:R=[]}=oe({queryKey:d?N.agents.list(d):["agents","none","list"],queryFn:()=>We.list(d),enabled:!!(!r&&d)}),Q={mode:n,isCreate:r,adapterType:k,values:r?t.values:null,set:r?q=>t.onChange(q):null,config:S,eff:y,mark:v,models:z,hideInstructionsFile:u},[H,U]=c.useState(!1),[Z,V]=c.useState(!1),[W,J]=c.useState(!1),Y=r?t.values:null,de=r?q=>t.onChange(q):null;function fe(){return r?I.buildAdapterConfig(Y):{...S,...h.adapterConfig}}const Ce=ge({mutationFn:async()=>{if(!d)throw new Error("Select a company to test adapter environment");return We.testEnvironment(d,k,{adapterConfig:fe()})}}),le=r?Y.model:y("adapterConfig","model",String(S.model??"")),Re=k==="codex_local"?"modelReasoningEffort":k==="cursor"?"mode":k==="opencode_local"?"variant":"effort",Pe=k==="codex_local"?ZL:k==="cursor"?XL:k==="opencode_local"?YL:eF,Fe=r?Y.thinkingEffort:k==="codex_local"?y("adapterConfig","modelReasoningEffort",String(S.modelReasoningEffort??S.reasoningEffort??"")):k==="cursor"?y("adapterConfig","mode",String(S.mode??"")):k==="opencode_local"?y("adapterConfig","variant",String(S.variant??"")):y("adapterConfig","effort",String(S.effort??"")),pe=k!=="gemini_local",Le=k==="codex_local"?r?!!Y.search:y("adapterConfig","search",!!S.search):!1;return c.useMemo(()=>{if(r)return{heartbeat:{enabled:Y.heartbeatEnabled,intervalSec:Y.intervalSec}};const q={...M.heartbeat&&typeof M.heartbeat=="object"?M.heartbeat:{},...h.heartbeat};return{...M,heartbeat:q}},[r,h.heartbeat,M,Y]),e.jsxs("div",{className:O("relative",a&&"space-y-6"),children:[g&&!t.hideInlineSave&&e.jsx("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),e.jsx(G,{size:"sm",onClick:E,disabled:!r&&t.isSaving,children:!r&&t.isSaving?"Saving...":"Save"})]})}),!r&&e.jsxs("div",{className:O(!a&&"border-b border-border"),children:[a?e.jsx("h3",{className:"text-sm font-medium mb-3",children:"Identity"}):e.jsx("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),e.jsxs("div",{className:O(a?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[e.jsx(ct,{label:"Name",hint:Rt.name,children:e.jsx(nn,{value:y("identity","name",t.agent.name),onCommit:q=>v("identity","name",q),immediate:!0,className:Hs,placeholder:"Agent name"})}),e.jsx(ct,{label:"Title",hint:Rt.title,children:e.jsx(nn,{value:y("identity","title",t.agent.title??""),onCommit:q=>v("identity","title",q||null),immediate:!0,className:Hs,placeholder:"e.g. VP of Engineering"})}),e.jsx(ct,{label:"Reports to",hint:Rt.reportsTo,children:e.jsx(Jw,{agents:R,value:y("identity","reportsTo",t.agent.reportsTo??null),onChange:q=>v("identity","reportsTo",q),excludeAgentIds:[t.agent.id],chooseLabel:"Choose manager…"})}),e.jsx(ct,{label:"Capabilities",hint:Rt.capabilities,children:e.jsx(ps,{value:y("identity","capabilities",t.agent.capabilities??""),onChange:q=>v("identity","capabilities",q||null),placeholder:"Describe what this agent can do...",contentClassName:"min-h-[44px] text-sm font-mono",imageUploadHandler:async q=>(await f.mutateAsync({file:q,namespace:`agents/${t.agent.id}/capabilities`})).contentPath})}),L&&!t.hidePromptTemplate&&e.jsxs(e.Fragment,{children:[e.jsx(ct,{label:"Prompt Template",hint:Rt.promptTemplate,children:e.jsx(ps,{value:y("adapterConfig","promptTemplate",String(S.promptTemplate??"")),onChange:q=>v("adapterConfig","promptTemplate",q??""),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-[88px] text-sm font-mono",imageUploadHandler:async q=>{const D=`agents/${t.agent.id}/prompt-template`;return(await f.mutateAsync({file:q,namespace:D})).contentPath}})}),e.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-100",children:"Prompt template is replayed on every heartbeat. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),e.jsxs("div",{className:O(!a&&(r?"border-t border-border":"border-b border-border")),children:[e.jsxs("div",{className:O(a?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[a?e.jsx("h3",{className:"text-sm font-medium",children:"Adapter"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),i&&e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:()=>Ce.mutate(),disabled:Ce.isPending||!d,children:Ce.isPending?"Testing...":"Test environment"})]}),e.jsxs("div",{className:O(a?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&e.jsx(ct,{label:"Adapter type",hint:Rt.adapterType,children:e.jsx(rF,{value:k,onChange:q=>{if(r){const{adapterType:D,...ie}=io,Ie={...ie,adapterType:q};q==="codex_local"?(Ie.model=ii,Ie.dangerouslyBypassSandbox=fl):q==="gemini_local"?Ie.model=ci:q==="cursor"?Ie.model=li:q==="opencode_local"&&(Ie.model=""),de(Ie)}else j(D=>({...D,adapterType:q,adapterConfig:{model:q==="codex_local"?ii:q==="gemini_local"?ci:q==="cursor"?li:"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...q==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:fl}:{}}}))}})}),Ce.error&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Ce.error instanceof Error?Ce.error.message:"Environment test failed"}),Ce.data&&e.jsx(tF,{result:Ce.data}),C&&e.jsx(ct,{label:"Working directory (deprecated)",hint:Rt.cwd,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[e.jsx(kl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx(nn,{value:r?Y.cwd:y("adapterConfig","cwd",String(S.cwd??"")),onCommit:q=>r?de({cwd:q}):v("adapterConfig","cwd",q||void 0),immediate:!0,className:"w-full bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",placeholder:"/path/to/project"}),e.jsx(pr,{})]})}),L&&r&&e.jsxs(e.Fragment,{children:[e.jsx(ct,{label:"Prompt Template",hint:Rt.promptTemplate,children:e.jsx(ps,{value:Y.promptTemplate,onChange:q=>de({promptTemplate:q}),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-[88px] text-sm font-mono",imageUploadHandler:async q=>(await f.mutateAsync({file:q,namespace:"agents/drafts/prompt-template"})).contentPath})}),e.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-100",children:["Prompt template is replayed on every heartbeat. Prefer small task framing and variables like ",e.jsx("code",{children:"{{ context.* }}"})," or ",e.jsx("code",{children:"{{ run.* }}"}),"; avoid repeating stable instructions here."]})]}),e.jsx(I.ConfigFields,{...Q})]})]}),L&&e.jsxs("div",{className:O(!a&&"border-b border-border"),children:[a?e.jsx("h3",{className:"text-sm font-medium mb-3",children:"Permissions & Configuration"}):e.jsx("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Permissions & Configuration"}),e.jsxs("div",{className:O(a?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[e.jsx(ct,{label:"Command",hint:Rt.localCommand,children:e.jsx(nn,{value:r?Y.command:y("adapterConfig","command",String(S.command??"")),onCommit:q=>r?de({command:q}):v("adapterConfig","command",q||void 0),immediate:!0,className:Hs,placeholder:k==="codex_local"?"codex":k==="gemini_local"?"gemini":k==="hermes_local"?"hermes":k==="pi_local"?"pi":k==="cursor"?"agent":k==="opencode_local"?"opencode":"claude"})}),e.jsx(oF,{models:z,value:le,onChange:q=>r?de({model:q}):v("adapterConfig","model",q||void 0),open:Z,onOpenChange:V,allowDefault:k!=="opencode_local"&&k!=="hermes_local",required:k==="opencode_local"||k==="hermes_local",groupByProvider:k==="opencode_local",creatable:k==="hermes_local",detectedModel:k==="hermes_local"?A:null,onDetectModel:k==="hermes_local"?async()=>{var D;return((D=(await F()).data)==null?void 0:D.model)??null}:void 0,detectModelLabel:k==="hermes_local"?"Detect from Hermes config":void 0}),T&&e.jsx("p",{className:"text-xs text-destructive",children:T instanceof Error?T.message:"Failed to load adapter models."}),pe&&e.jsxs(e.Fragment,{children:[e.jsx(iF,{value:Fe,options:Pe,onChange:q=>r?de({thinkingEffort:q}):v("adapterConfig",Re,q||void 0),open:W,onOpenChange:J}),k==="codex_local"&&Le&&Fe==="minimal"&&e.jsx("p",{className:"text-xs text-amber-400",children:"Codex may reject `minimal` thinking when search is enabled."})]}),!r&&typeof S.bootstrapPromptTemplate=="string"&&S.bootstrapPromptTemplate&&e.jsxs(e.Fragment,{children:[e.jsx(ct,{label:"Bootstrap prompt (legacy)",hint:Rt.bootstrapPrompt,children:e.jsx(ps,{value:y("adapterConfig","bootstrapPromptTemplate",String(S.bootstrapPromptTemplate??"")),onChange:q=>v("adapterConfig","bootstrapPromptTemplate",q||void 0),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-[44px] text-sm font-mono",imageUploadHandler:async q=>{const D=`agents/${t.agent.id}/bootstrap-prompt`;return(await f.mutateAsync({file:q,namespace:D})).contentPath}})}),e.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-200",children:"Bootstrap prompt is legacy and will be removed in a future release. Consider moving this content into the agent's prompt template or instructions file instead."})]}),k==="claude_local"&&e.jsx(PP,{...Q}),e.jsx(ct,{label:"Extra args (comma-separated)",hint:Rt.extraArgs,children:e.jsx(nn,{value:r?Y.extraArgs:y("adapterConfig","extraArgs",JL(S.extraArgs)),onCommit:q=>r?de({extraArgs:q}):v("adapterConfig","extraArgs",q?GL(q):void 0),immediate:!0,className:Hs,placeholder:"e.g. --verbose, --foo=bar"})}),e.jsx(ct,{label:"Environment variables",hint:Rt.envVars,children:e.jsx(aF,{value:r?Y.envBindings??fg:y("adapterConfig","env",S.env??fg),secrets:p,onCreateSecret:async(q,D)=>await x.mutateAsync({name:q,value:D}),onChange:q=>r?de({envBindings:q??{},envVars:""}):v("adapterConfig","env",q)})}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(ct,{label:"Timeout (sec)",hint:Rt.timeoutSec,children:e.jsx(qi,{value:y("adapterConfig","timeoutSec",Number(S.timeoutSec??0)),onCommit:q=>v("adapterConfig","timeoutSec",q),immediate:!0,className:Hs})}),e.jsx(ct,{label:"Interrupt grace period (sec)",hint:Rt.graceSec,children:e.jsx(qi,{value:y("adapterConfig","graceSec",Number(S.graceSec??15)),onCommit:q=>v("adapterConfig","graceSec",q),immediate:!0,className:Hs})})]})]})]}),r&&l?e.jsxs("div",{className:O(!a&&"border-b border-border"),children:[a?e.jsxs("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[e.jsx($i,{className:"h-3 w-3"})," Run Policy"]}):e.jsxs("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx($i,{className:"h-3 w-3"})," Run Policy"]}),e.jsx("div",{className:O(a?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:e.jsx(Ah,{label:"Heartbeat on interval",hint:Rt.heartbeatInterval,checked:Y.heartbeatEnabled,onCheckedChange:q=>de({heartbeatEnabled:q}),number:Y.intervalSec,onNumberChange:q=>de({intervalSec:q}),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Rt.intervalSec,showNumber:Y.heartbeatEnabled})})]}):r?null:e.jsxs("div",{className:O(!a&&"border-b border-border"),children:[a?e.jsxs("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[e.jsx($i,{className:"h-3 w-3"})," Run Policy"]}):e.jsxs("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx($i,{className:"h-3 w-3"})," Run Policy"]}),e.jsxs("div",{className:O(a?"border border-border rounded-lg overflow-hidden":""),children:[e.jsx("div",{className:O(a?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:e.jsx(Ah,{label:"Heartbeat on interval",hint:Rt.heartbeatInterval,checked:y("heartbeat","enabled",B.enabled!==!1),onCheckedChange:q=>v("heartbeat","enabled",q),number:y("heartbeat","intervalSec",Number(B.intervalSec??300)),onNumberChange:q=>v("heartbeat","intervalSec",q),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Rt.intervalSec,showNumber:y("heartbeat","enabled",B.enabled!==!1)})}),e.jsx(EP,{title:"Advanced Run Policy",bordered:a,open:H,onToggle:()=>U(!H),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(ao,{label:"Wake on demand",hint:Rt.wakeOnDemand,checked:y("heartbeat","wakeOnDemand",B.wakeOnDemand!==!1),onChange:q=>v("heartbeat","wakeOnDemand",q)}),e.jsx(ct,{label:"Cooldown (sec)",hint:Rt.cooldownSec,children:e.jsx(qi,{value:y("heartbeat","cooldownSec",Number(B.cooldownSec??10)),onCommit:q=>v("heartbeat","cooldownSec",q),immediate:!0,className:Hs})}),e.jsx(ct,{label:"Max concurrent runs",hint:Rt.maxConcurrentRuns,children:e.jsx(qi,{value:y("heartbeat","maxConcurrentRuns",Number(B.maxConcurrentRuns??1)),onCommit:q=>v("heartbeat","maxConcurrentRuns",q),immediate:!0,className:Hs})})]})})]})]})]})}function tF({result:t}){const n=t.status==="pass"?"Passed":t.status==="warn"?"Warnings":"Failed",s=t.status==="pass"?"text-green-700 dark:text-green-300 border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10":t.status==="warn"?"text-amber-700 dark:text-amber-300 border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10":"text-red-700 dark:text-red-300 border-red-300 dark:border-red-500/40 bg-red-50 dark:bg-red-500/10";return e.jsxs("div",{className:`rounded-md border px-3 py-2 text-xs ${s}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:n}),e.jsx("span",{className:"text-[11px] opacity-80",children:new Date(t.testedAt).toLocaleTimeString()})]}),e.jsx("div",{className:"mt-2 space-y-1.5",children:t.checks.map((r,a)=>e.jsxs("div",{className:"text-[11px] leading-relaxed break-words",children:[e.jsx("span",{className:"font-medium uppercase tracking-wide opacity-80",children:r.level}),e.jsx("span",{className:"mx-1 opacity-60",children:"·"}),e.jsx("span",{children:r.message}),r.detail&&e.jsxs("span",{className:"block opacity-75 break-all",children:["(",r.detail,")"]}),r.hint&&e.jsxs("span",{className:"block opacity-90 break-words",children:["Hint: ",r.hint]})]},`${r.code}-${a}`))})]})}const nF=new Set(["claude_local","codex_local","gemini_local","opencode_local","pi_local","cursor","hermes_local"]),sF=[..._l.map(t=>({value:t,label:tu[t]??t,comingSoon:!nF.has(t)}))];function rF({value:t,onChange:n}){return e.jsxs(Ht,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t==="opencode_local"?e.jsx(Yc,{className:"h-3.5 w-3.5"}):null,e.jsx("span",{children:tu[t]??t})]}),e.jsx(rn,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Qt,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:sF.map(s=>e.jsxs("button",{disabled:s.comingSoon,className:O("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",s.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",s.value===t&&!s.comingSoon&&"bg-accent"),onClick:()=>{s.comingSoon||n(s.value)},children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.value==="opencode_local"?e.jsx(Yc,{className:"h-3.5 w-3.5"}):null,e.jsx("span",{children:s.label})]}),s.comingSoon&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Coming soon"})]},s.value))})]})}function aF({value:t,secrets:n,onCreateSecret:s,onChange:r}){function a(b){return!b||typeof b!="object"?[{key:"",source:"plain",plainValue:"",secretId:""}]:[...Object.entries(b).map(([y,v])=>{if(typeof v=="string")return{key:y,source:"plain",plainValue:v,secretId:""};if(typeof v=="object"&&v!==null&&"type"in v&&v.type==="secret_ref"){const _=v;return{key:y,source:"secret",plainValue:"",secretId:typeof _.secretId=="string"?_.secretId:""}}if(typeof v=="object"&&v!==null&&"type"in v&&v.type==="plain"){const _=v;return{key:y,source:"plain",plainValue:typeof _.value=="string"?_.value:"",secretId:""}}return{key:y,source:"plain",plainValue:"",secretId:""}}),{key:"",source:"plain",plainValue:"",secretId:""}]}const[o,i]=c.useState(()=>a(t)),[l,u]=c.useState(null),d=c.useRef(t),m=c.useRef(!1);c.useEffect(()=>{if(m.current){m.current=!1,d.current=t;return}t!==d.current&&(d.current=t,i(a(t)))},[t]);function p(b){const g={};for(const y of b){const v=y.key.trim();v&&(y.source==="secret"?y.secretId?g[v]={type:"secret_ref",secretId:y.secretId,version:"latest"}:g[v]={type:"plain",value:y.plainValue}:g[v]={type:"plain",value:y.plainValue})}m.current=!0,r(Object.keys(g).length>0?g:void 0)}function x(b,g){const y=o.map((v,_)=>_===b?{...v,...g}:v);(y[y.length-1].key||y[y.length-1].plainValue||y[y.length-1].secretId)&&y.push({key:"",source:"plain",plainValue:"",secretId:""}),i(y),p(y)}function f(b){const g=o.filter((y,v)=>v!==b);(g.length===0||g[g.length-1].key||g[g.length-1].plainValue||g[g.length-1].secretId)&&g.push({key:"",source:"plain",plainValue:"",secretId:""}),i(g),p(g)}function h(b){return b.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}async function j(b){var S;const g=o[b];if(!g)return;const y=g.key.trim(),v=g.plainValue;if(!y||v.length===0)return;const _=h(y)||"secret",E=(S=window.prompt("Secret name",_))==null?void 0:S.trim();if(E)try{u(null);const M=await s(E,v);x(b,{source:"secret",secretId:M.id})}catch(M){u(M instanceof Error?M.message:"Failed to create secret")}}return e.jsxs("div",{className:"space-y-1.5",children:[o.map((b,g)=>{const y=g===o.length-1&&!b.key&&!b.plainValue&&!b.secretId;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{className:O(Hs,"flex-[2]"),placeholder:"KEY",value:b.key,onChange:v=>x(g,{key:v.target.value})}),e.jsxs("select",{className:O(Hs,"flex-[1] bg-background"),value:b.source,onChange:v=>x(g,{source:v.target.value==="secret"?"secret":"plain",...v.target.value==="plain"?{secretId:""}:{}}),children:[e.jsx("option",{value:"plain",children:"Plain"}),e.jsx("option",{value:"secret",children:"Secret"})]}),b.source==="secret"?e.jsxs(e.Fragment,{children:[e.jsxs("select",{className:O(Hs,"flex-[3] bg-background"),value:b.secretId,onChange:v=>x(g,{secretId:v.target.value}),children:[e.jsx("option",{value:"",children:"Select secret..."}),n.map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))]}),e.jsx("button",{type:"button",className:"inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0",onClick:()=>j(g),disabled:!b.key.trim()||!b.plainValue,title:"Create secret from current plain value",children:"New"})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{className:O(Hs,"flex-[3]"),placeholder:"value",value:b.plainValue,onChange:v=>x(g,{plainValue:v.target.value})}),e.jsx("button",{type:"button",className:"inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0",onClick:()=>j(g),disabled:!b.key.trim()||!b.plainValue,title:"Store value as secret and replace with reference",children:"Seal"})]}),y?e.jsx("div",{className:"w-[26px] shrink-0"}):e.jsx("button",{type:"button",className:"shrink-0 p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors",onClick:()=>f(g),children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]},g)}),l&&e.jsx("p",{className:"text-[11px] text-destructive",children:l}),e.jsx("p",{className:"text-[11px] text-muted-foreground/60",children:"CREWSPACE_* variables are injected automatically at runtime."})]})}function oF({models:t,value:n,onChange:s,open:r,onOpenChange:a,allowDefault:o,required:i,groupByProvider:l,creatable:u,detectedModel:d,onDetectModel:m,detectModelLabel:p}){const[x,f]=c.useState(""),[h,j]=c.useState(!1),b=t.find(S=>S.id===n),g=x.trim(),y=!!(u&&g&&!t.some(S=>S.id.toLowerCase()===g.toLowerCase())),v=c.useMemo(()=>t.filter(S=>{if(!x.trim())return!0;const M=x.toLowerCase(),B=Jm(S.id)??"";return S.id.toLowerCase().includes(M)||S.label.toLowerCase().includes(M)||B.toLowerCase().includes(M)}),[t,x]),_=c.useMemo(()=>{if(!l)return[{provider:"models",entries:[...v].sort((M,B)=>M.id.localeCompare(B.id))}];const S=new Map;for(const M of v){const B=Jm(M.id)??"other",k=S.get(B)??[];k.push(M),S.set(B,k)}return Array.from(S.entries()).sort(([M],[B])=>M.localeCompare(B)).map(([M,B])=>({provider:M,entries:[...B].sort((k,L)=>k.id.localeCompare(L.id))}))},[v,l]);async function E(){if(m){j(!0);try{const S=await m();S&&(s(S),a(!1),f(""))}finally{j(!1)}}}return e.jsx(ct,{label:"Model",hint:Rt.model,children:e.jsxs(Ht,{open:r,onOpenChange:S=>{a(S),S||f("")},children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[e.jsx("span",{className:O(!n&&"text-muted-foreground"),children:b?b.label:n||(o?"Default":i?"Select model (required)":"Select model")}),e.jsx(rn,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(Qt,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:[e.jsxs("div",{className:"relative mb-1",children:[e.jsx("input",{className:"w-full px-2 py-1.5 pr-6 text-xs bg-transparent outline-none border-b border-border placeholder:text-muted-foreground/50",placeholder:u?"Search models... (type to create)":"Search models...",value:x,onChange:S=>f(S.target.value),autoFocus:!0}),x&&e.jsx("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>f(""),children:e.jsxs("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),m&&!d&&!x.trim()&&e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:()=>{E()},disabled:h,children:[e.jsxs("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),e.jsx("path",{d:"M3 3v5h5"})]}),h?"Detecting...":p??"Detect from config"]}),n&&!t.some(S=>S.id===n)&&e.jsxs("button",{type:"button",className:O("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:()=>{a(!1)},children:[e.jsx("span",{className:"block w-full text-left truncate font-mono text-xs",title:n,children:n}),e.jsx("span",{className:"shrink-0 ml-auto text-[9px] font-medium px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-400 border border-green-500/20",children:"current"})]}),d&&d!==n&&e.jsxs("button",{type:"button",className:O("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:()=>{s(d),a(!1)},children:[e.jsx("span",{className:"block w-full text-left truncate font-mono text-xs",title:d,children:d}),e.jsx("span",{className:"shrink-0 ml-auto text-[9px] font-medium px-1.5 py-0.5 rounded-full bg-blue-500/15 text-blue-400 border border-blue-500/20",children:"detected"})]}),e.jsxs("div",{className:"max-h-[240px] overflow-y-auto",children:[o&&e.jsx("button",{type:"button",className:O("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!n&&"bg-accent"),onClick:()=>{s(""),a(!1)},children:"Default"}),y&&e.jsxs("button",{type:"button",className:"flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:()=>{s(g),a(!1),f("")},children:[e.jsx("span",{children:"Use manual model"}),e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:g})]}),_.map(S=>e.jsxs("div",{className:"mb-1 last:mb-0",children:[l&&e.jsxs("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:[S.provider," (",S.entries.length,")"]}),S.entries.map(M=>e.jsx("button",{type:"button",className:O("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",M.id===n&&"bg-accent"),onClick:()=>{s(M.id),a(!1)},children:e.jsx("span",{className:"block w-full text-left truncate",title:M.id,children:l?M0(M.id):M.label})},M.id))]},S.provider)),v.length===0&&!y&&e.jsx("div",{className:"px-2 py-2 space-y-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:m?"No Hermes model detected yet. Configure Hermes or enter a provider/model manually.":"No models found."})})]})]})]})})}function iF({value:t,options:n,onChange:s,open:r,onOpenChange:a}){const o=n.find(i=>i.id===t)??n[0];return e.jsx(ct,{label:"Thinking effort",hint:Rt.thinkingEffort,children:e.jsxs(Ht,{open:r,onOpenChange:a,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[e.jsx("span",{className:O(!t&&"text-muted-foreground"),children:(o==null?void 0:o.label)??"Auto"}),e.jsx(rn,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Qt,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:n.map(i=>e.jsxs("button",{className:O("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",i.id===t&&"bg-accent"),onClick:()=>{s(i.id),a(!1)},children:[e.jsx("span",{children:i.label}),i.id?e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:i.id}):null]},i.id||"auto"))})]})})}function uo({text:t,children:n,className:s,copiedLabel:r="Copied!"}){const[a,o]=c.useState(!1),[i,l]=c.useState(r),u=c.useRef(void 0),d=c.useRef(null),m=c.useCallback(async()=>{try{await navigator.clipboard.writeText(t),l(r)}catch{l("Copy failed")}clearTimeout(u.current),o(!0),u.current=setTimeout(()=>o(!1),1500)},[r,t]);return e.jsxs("span",{className:"relative inline-flex",children:[e.jsx("button",{ref:d,type:"button",className:O("cursor-copy hover:text-foreground transition-colors",s),onClick:m,children:n??t}),e.jsx("span",{role:"status","aria-live":"polite",className:O("pointer-events-none absolute left-1/2 -translate-x-1/2 bottom-full mb-1.5 rounded-md bg-foreground text-background px-2 py-1 text-xs whitespace-nowrap transition-opacity duration-300",a?"opacity-100":"opacity-0"),children:i})]})}function Zw({onClick:t,disabled:n,label:s="Run now",size:r="sm"}){return e.jsxs(G,{variant:"outline",size:r,onClick:t,disabled:n,children:[e.jsx(Dp,{className:"h-3.5 w-3.5 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:s})]})}function lF({isPaused:t,onPause:n,onResume:s,disabled:r,size:a="sm"}){return t?e.jsxs(G,{variant:"outline",size:a,onClick:s,disabled:r,children:[e.jsx(Dp,{className:"h-3.5 w-3.5 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resume"})]}):e.jsxs(G,{variant:"outline",size:a,onClick:n,disabled:r,children:[e.jsx(y1,{className:"h-3.5 w-3.5 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Pause"})]})}function jn({className:t,...n}){return e.jsx("div",{"data-slot":"card",className:O("bg-card text-card-foreground flex flex-col gap-6 border py-6 shadow-sm",t),...n})}function qn({className:t,...n}){return e.jsx("div",{"data-slot":"card-header",className:O("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...n})}function Un({className:t,...n}){return e.jsx("div",{"data-slot":"card-title",className:O("leading-none font-semibold",t),...n})}function cs({className:t,...n}){return e.jsx("div",{"data-slot":"card-description",className:O("text-muted-foreground text-sm",t),...n})}function wn({className:t,...n}){return e.jsx("div",{"data-slot":"card-content",className:O("px-6",t),...n})}function cF({className:t,...n}){return e.jsx("div",{"data-slot":"card-footer",className:O("flex items-center px-6 [.border-t]:pt-6",t),...n})}function hg(t){return(t/100).toFixed(2)}function dF(t){const n=t.trim();if(n.length===0)return 0;const s=Number(n);return!Number.isFinite(s)||s<0?null:Math.round(s*100)}function gg(t){return t==="lifetime"?"Lifetime budget":"Monthly UTC budget"}function uF(t){return t==="hard_stop"?"text-red-300 border-red-500/30 bg-red-500/10":t==="warning"?"text-amber-200 border-amber-500/30 bg-amber-500/10":"text-emerald-200 border-emerald-500/30 bg-emerald-500/10"}function rf({summary:t,onSave:n,isSaving:s,compact:r=!1,variant:a="card"}){const[o,i]=c.useState(hg(t.amount));c.useEffect(()=>{i(hg(t.amount))},[t.amount]);const l=dF(o),u=typeof l=="number"&&l!==t.amount&&!!n,d=t.amount>0?Math.min(100,t.utilizationPercent):0,m=t.status==="hard_stop"?Ja:t.status==="warning"?ir:v1,p=a==="plain",x=p?e.jsxs("div",{className:"grid gap-6 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Observed"}),e.jsx("div",{className:"mt-2 text-xl font-semibold tabular-nums",children:ot(t.observedAmount)}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:t.amount>0?`${t.utilizationPercent}% of limit`:"No cap configured"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Budget"}),e.jsx("div",{className:"mt-2 text-xl font-semibold tabular-nums",children:t.amount>0?ot(t.amount):"Disabled"}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["Soft alert at ",t.warnPercent,"%",t.paused&&t.pauseReason?` · ${t.pauseReason} pause`:""]})]})]}):e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-xl border border-border/70 bg-black/[0.18] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Observed"}),e.jsx("div",{className:"mt-2 text-xl font-semibold tabular-nums",children:ot(t.observedAmount)}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:t.amount>0?`${t.utilizationPercent}% of limit`:"No cap configured"})]}),e.jsxs("div",{className:"rounded-xl border border-border/70 bg-black/[0.18] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Budget"}),e.jsx("div",{className:"mt-2 text-xl font-semibold tabular-nums",children:t.amount>0?ot(t.amount):"Disabled"}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["Soft alert at ",t.warnPercent,"%",t.paused&&t.pauseReason?` · ${t.pauseReason} pause`:""]})]})]}),f=e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Remaining"}),e.jsx("span",{children:t.amount>0?ot(t.remainingAmount):"Unlimited"})]}),e.jsx("div",{className:O("h-2 overflow-hidden rounded-full",p?"bg-border/70":"bg-muted/70"),children:e.jsx("div",{className:O("h-full rounded-full transition-[width,background-color] duration-200",t.status==="hard_stop"?"bg-red-400":t.status==="warning"?"bg-amber-300":"bg-emerald-300"),style:{width:`${d}%`}})})]}),h=t.paused?e.jsxs("div",{className:"flex items-start gap-2 rounded-xl border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-100",children:[e.jsx($p,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("div",{children:t.scopeType==="project"?"Execution is paused for this project until the budget is raised or the incident is dismissed.":"Heartbeats are paused for this scope until the budget is raised or the incident is dismissed."})]}):null,j=n?e.jsxs("div",{className:O("flex flex-col gap-3 sm:flex-row sm:items-end",p?"":"rounded-xl border border-border/70 bg-background/50 p-3"),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("label",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Budget (USD)"}),e.jsx(Xt,{value:o,onChange:b=>i(b.target.value),className:"mt-2",inputMode:"decimal",placeholder:"0.00"})]}),e.jsx(G,{onClick:()=>{typeof l=="number"&&n&&n(l)},disabled:!u||s||l===null,children:s?"Saving...":t.amount>0?"Update budget":"Set budget"})]}):null;return p?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.22em] text-muted-foreground",children:t.scopeType}),e.jsx("div",{className:"mt-2 text-xl font-semibold",children:t.scopeName}),e.jsx("div",{className:"mt-2 text-sm text-muted-foreground",children:gg(t.windowKind)})]}),e.jsxs("div",{className:O("inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.18em]",t.status==="hard_stop"?"text-red-300":t.status==="warning"?"text-amber-200":"text-muted-foreground"),children:[e.jsx(m,{className:"h-3.5 w-3.5"}),t.paused?"Paused":t.status==="warning"?"Warning":t.status==="hard_stop"?"Hard stop":"Healthy"]})]}),x,f,h,j,l===null?e.jsx("p",{className:"text-xs text-destructive",children:"Enter a valid non-negative dollar amount."}):null]}):e.jsxs(jn,{className:O("overflow-hidden border-border/70 bg-card/80",r?"":"shadow-[0_20px_80px_-40px_rgba(0,0,0,0.55)]"),children:[e.jsx(qn,{className:O("gap-3",r?"px-4 pt-4 pb-2":"px-5 pt-5 pb-3"),children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.22em] text-muted-foreground",children:t.scopeType}),e.jsx(Un,{className:"mt-1 text-base",children:t.scopeName}),e.jsx(cs,{className:"mt-1",children:gg(t.windowKind)})]}),e.jsxs("div",{className:O("inline-flex items-center gap-2 rounded-full border px-3 py-1 text-[11px] uppercase tracking-[0.18em]",uF(t.status)),children:[e.jsx(m,{className:"h-3.5 w-3.5"}),t.paused?"Paused":t.status==="warning"?"Warning":t.status==="hard_stop"?"Hard stop":"Healthy"]})]})}),e.jsxs(wn,{className:O("space-y-4",r?"px-4 pb-4 pt-0":"px-5 pb-5 pt-0"),children:[x,f,h,j,l===null?e.jsx("p",{className:"text-xs text-destructive",children:"Enter a valid non-negative dollar amount."}):null]})]})}const bg=16,yg=24,vg="min-h-9";function Go(t,n){const s={children:[]};for(const a of Object.keys(t)){const o=a.split("/").filter(Boolean);let i=s,l="";for(let u=0;u<o.length;u++){const d=o[u];l=l?`${l}/${d}`:d;const m=u===o.length-1;let p=i.children.find(x=>x.name===d);p||(p={name:d,path:l,kind:m?"file":"dir",children:[],action:m?(n==null?void 0:n.get(a))??null:null},i.children.push(p)),i=p}}function r(a){a.children.sort((o,i)=>o.kind!==i.kind?o.kind==="file"?-1:1:o.name.localeCompare(i.name)),a.children.forEach(r)}return r(s),s.children}function af(t){let n=0;for(const s of t)s.kind==="file"?n++:n+=af(s.children);return n}function ql(t,n="all"){const s=new Set;for(const r of t){(n==="all"||r.kind===n)&&s.add(r.path);for(const a of ql(r.children,n))s.add(a)}return s}function mF(t){return t.endsWith(".yaml")||t.endsWith(".yml")?ey:Id}function Yw(t){const n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!n)return null;const s={},r=n[1],a=n[2];let o=null,i=null;for(const l of r.split(`
|
|
88
|
+
`)){const u=l.trim();if(!u||u.startsWith("#"))continue;if(u.startsWith("- ")&&o){i||(i=[]),i.push(u.slice(2).trim().replace(/^["']|["']$/g,""));continue}o&&i&&(s[o]=i,i=null,o=null);const d=u.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)$/);if(d){const m=d[1],p=d[2].trim().replace(/^["']|["']$/g,"");if(p==="null"){o=null;continue}p?(s[m]=p,o=null):o=m}}return o&&i&&(s[o]=i),Object.keys(s).length>0?{data:s,body:a}:null}const Xw={name:"Name",title:"Title",kind:"Kind",reportsTo:"Reports to",skills:"Skills",status:"Status",description:"Description",priority:"Priority",assignee:"Assignee",project:"Project",recurring:"Recurring",targetDate:"Target date"};function ou({nodes:t,selectedFile:n,expandedDirs:s,checkedFiles:r,onToggleDir:a,onSelectFile:o,onToggleCheck:i,renderFileExtra:l,fileRowClassName:u,showCheckboxes:d=!0,depth:m=0}){const p=r??new Set;return e.jsx("div",{children:t.map(x=>{const f=x.kind==="dir"&&s.has(x.path);if(x.kind==="dir"){const g=ql(x.children,"file"),y=[...g].every(_=>p.has(_)),v=[...g].some(_=>p.has(_));return e.jsxs("div",{children:[e.jsxs("div",{className:O(d?"group grid w-full grid-cols-[auto_minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground":"group grid w-full grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",vg),style:{paddingInlineStart:`${bg+m*yg-8}px`},children:[d&&e.jsx("label",{className:"flex items-center pl-2",children:e.jsx("input",{type:"checkbox",checked:y,ref:_=>{_&&(_.indeterminate=v&&!y)},onChange:()=>i==null?void 0:i(x.path,"dir"),className:"mr-2 accent-foreground"})}),e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-2 py-1 text-left",onClick:()=>a(x.path),children:[e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center",children:f?e.jsx(kl,{className:"h-3.5 w-3.5"}):e.jsx(Op,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"truncate",children:x.name})]}),e.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center self-center rounded-sm text-muted-foreground opacity-70 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100",onClick:()=>a(x.path),children:f?e.jsx(rn,{className:"h-3.5 w-3.5"}):e.jsx(sn,{className:"h-3.5 w-3.5"})})]}),f&&e.jsx(ou,{nodes:x.children,selectedFile:n,expandedDirs:s,checkedFiles:p,onToggleDir:a,onSelectFile:o,onToggleCheck:i,renderFileExtra:l,fileRowClassName:u,showCheckboxes:d,depth:m+1})]},x.path)}const h=mF(x.name),j=p.has(x.path),b=u==null?void 0:u(x,j);return e.jsxs("div",{className:O("flex w-full items-center gap-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground cursor-pointer",vg,x.path===n&&"text-foreground bg-accent/20",b),style:{paddingInlineStart:`${bg+m*yg-8}px`},onClick:()=>o(x.path),children:[d&&e.jsx("label",{className:"flex items-center pl-2",children:e.jsx("input",{type:"checkbox",checked:j,onChange:()=>i==null?void 0:i(x.path,"file"),className:"mr-2 accent-foreground"})}),e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 py-1 text-left",onClick:()=>o(x.path),children:[e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center",children:e.jsx(h,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"truncate",children:x.name})]}),l==null?void 0:l(x,j)]},x.path)})})}function jg(){const t=document.getElementById("main-content");if(t instanceof HTMLElement){const n=window.getComputedStyle(t).overflowY;if((n==="auto"||n==="scroll"||n==="overlay")&&t.scrollHeight>t.clientHeight+1)return{type:"element",element:t}}return{type:"window"}}function pF(t){return t.type==="element"?t.element.scrollHeight-t.element.scrollTop-t.element.clientHeight:(document.scrollingElement??document.documentElement).scrollHeight-window.scrollY-window.innerHeight}function eN(){const[t,n]=c.useState(!1);c.useEffect(()=>{const r=()=>{n(pF(jg())>300)},a=document.getElementById("main-content");return r(),a==null||a.addEventListener("scroll",r,{passive:!0}),window.addEventListener("scroll",r,{passive:!0}),window.addEventListener("resize",r),()=>{a==null||a.removeEventListener("scroll",r),window.removeEventListener("scroll",r),window.removeEventListener("resize",r)}},[]);const s=c.useCallback(()=>{const r=jg();if(r.type==="element"){r.element.scrollTo({top:r.element.scrollHeight,behavior:"smooth"});return}const a=document.scrollingElement??document.documentElement;window.scrollTo({top:a.scrollHeight,behavior:"smooth"})},[]);return t?e.jsx("button",{onClick:s,className:"fixed bottom-[calc(1.5rem+5rem+env(safe-area-inset-bottom))] right-6 z-40 flex h-9 w-9 items-center justify-center rounded-full border border-border bg-background shadow-md hover:bg-accent transition-colors md:bottom-6","aria-label":"Scroll to bottom",children:e.jsx(Tp,{className:"h-4 w-4"})}):null}function bc(t,n){return t===n?!0:t.length!==n.length?!1:t.every((s,r)=>s===n[r])}function xF(t,n){const s=!t.hasHydratedSnapshot||bc(t.draft,t.lastSaved);return{draft:s?n:t.draft,lastSaved:n,hasHydratedSnapshot:!0,shouldSkipAutosave:s}}function fF(t,n){return n.has(t.key)?!1:t.origin==="user_installed"||t.origin==="external_unknown"?!0:t.managed===!1&&t.state==="external"}const tN={succeeded:{icon:ho,color:"text-green-600 dark:text-green-400"},failed:{icon:fi,color:"text-red-600 dark:text-red-400"},running:{icon:kn,color:"text-cyan-600 dark:text-cyan-400"},queued:{icon:_r,color:"text-yellow-600 dark:text-yellow-400"},timed_out:{icon:N1,color:"text-orange-600 dark:text-orange-400"},cancelled:{icon:w1,color:"text-neutral-500 dark:text-neutral-400"}},hF="***REDACTED***",gF=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,bF=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/;function yr(t,n){return Ws(t,{enabled:n})}function Oo(t,n){return nd(t,{enabled:n})}function yF(t,n){return gF.test(t)?!0:typeof n!="string"?!1:bF.test(n)}function vF(t,n,s){if(typeof n=="object"&&n!==null&&!Array.isArray(n)&&n.type==="secret_ref")return"***SECRET_REF***";if(yF(t,n))return hF;if(n==null)return"";if(typeof n=="string")return yr(n,s);try{return JSON.stringify(Oo(n,s))}catch{return yr(String(n),s)}}function jF(t){return t.toLowerCase().endsWith(".md")}function wF(t,n){const s=Ha(t);if(!s)return"<unable-to-parse>";const r=Object.keys(s);return r.length===0?"<empty>":r.sort().map(a=>`${a}=${vF(a,s[a],n)}`).join(`
|
|
89
|
+
`)}const nN={timer:"Timer",assignment:"Assignment",on_demand:"On-demand",automation:"Automation"},wg=32;function sN(t){return t===window}function NF(t){const n=window.getComputedStyle(t).overflowY;return n==="auto"||n==="scroll"||n==="overlay"}function kF(t){let n=(t==null?void 0:t.parentElement)??null;for(;n;){if(NF(n))return n;n=n.parentElement}return window}function sc(t){if(sN(t)){const s=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),r=window.scrollY+window.innerHeight;return{scrollHeight:s,distanceFromBottom:Math.max(0,s-r)}}const n=t.scrollTop+t.clientHeight;return{scrollHeight:t.scrollHeight,distanceFromBottom:Math.max(0,t.scrollHeight-n)}}function Ng(t,n="auto"){if(sN(t)){const s=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);window.scrollTo({top:s,behavior:n});return}t.scrollTo({top:t.scrollHeight,behavior:n})}function CF(t){return t==="instructions"||t==="prompts"?"instructions":t==="configure"||t==="configuration"?"configuration":t==="skills"?"skills":t==="budget"?"budget":t==="runs"?t:t==="access"?"access":"dashboard"}function em(t,...n){if(!t)return 0;for(const s of n){const r=t[s];if(typeof r=="number"&&Number.isFinite(r))return r}return 0}function SF(t,n){if(t.size!==n.size)return!1;for(const s of t)if(!n.has(s))return!1;return!0}function cd(t){const n=t.usageJson??null,s=t.resultJson??null,r=em(n,"inputTokens","input_tokens"),a=em(n,"outputTokens","output_tokens"),o=em(n,"cachedInputTokens","cached_input_tokens","cache_read_input_tokens"),i=cj(n,s);return{input:r,output:a,cached:o,cost:i,totalTokens:r+a}}function Ha(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function un(t){if(typeof t!="string")return null;const n=t.trim();return n.length>0?n:null}function IF(t){const n=[];for(const s of t.split(`
|
|
90
|
+
`)){const r=s.trim();if(r)try{const a=JSON.parse(r),o=a.stream==="stderr"||a.stream==="system"?a.stream:"stdout",i=typeof a.chunk=="string"?a.chunk:"",l=typeof a.ts=="string"?a.ts:new Date().toISOString();if(!i)continue;n.push({ts:l,stream:o,chunk:i})}catch{}}return n}function _F(t){switch(t){case"worktree_prepare":return"Worktree setup";case"workspace_provision":return"Provision";case"workspace_teardown":return"Teardown";case"worktree_cleanup":return"Worktree cleanup";default:return t}}function AF(t){switch(t){case"succeeded":return"border-green-500/20 bg-green-500/10 text-green-700 dark:text-green-300";case"failed":return"border-red-500/20 bg-red-500/10 text-red-700 dark:text-red-300";case"running":return"border-cyan-500/20 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300";case"skipped":return"border-yellow-500/20 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300";default:return"border-border bg-muted/40 text-muted-foreground"}}function EF({status:t}){return e.jsx("span",{className:O("inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-medium capitalize",AF(t)),children:t.replace("_"," ")})}function TF({operation:t,censorUsernameInLogs:n}){const[s,r]=c.useState(!1),{data:a,isLoading:o,error:i}=oe({queryKey:["workspace-operation-log",t.id],queryFn:()=>Yt.workspaceOperationLog(t.id),enabled:s&&!!t.logRef,refetchInterval:s&&t.status==="running"?2e3:!1}),l=c.useMemo(()=>a!=null&&a.content?IF(a.content):[],[a==null?void 0:a.content]);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("button",{type:"button",className:"text-[11px] text-muted-foreground underline underline-offset-2 hover:text-foreground",onClick:()=>r(u=>!u),children:s?"Hide full log":"Show full log"}),s&&e.jsxs("div",{className:"rounded-md border border-border bg-background/70 p-2",children:[o&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Loading log..."}),i&&e.jsx("div",{className:"text-xs text-destructive",children:i instanceof Error?i.message:"Failed to load workspace operation log"}),!o&&!i&&l.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"No persisted log lines."}),l.length>0&&e.jsx("div",{className:"max-h-64 overflow-y-auto rounded bg-neutral-100 p-2 font-mono text-xs dark:bg-neutral-950",children:l.map((u,d)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"shrink-0 text-neutral-500",children:new Date(u.ts).toLocaleTimeString("en-US",{hour12:!1})}),e.jsxs("span",{className:O("shrink-0 w-14",u.stream==="stderr"?"text-red-600 dark:text-red-300":u.stream==="system"?"text-blue-600 dark:text-blue-300":"text-muted-foreground"),children:["[",u.stream,"]"]}),e.jsx("span",{className:"whitespace-pre-wrap break-all",children:yr(u.chunk,n)})]},`${u.ts}-${d}`))})]})]})}function RF({operations:t,censorUsernameInLogs:n}){return t.length===0?null:e.jsxs("div",{className:"rounded-lg border border-border bg-background/60 p-3 space-y-3",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Workspace (",t.length,")"]}),e.jsx("div",{className:"space-y-3",children:t.map(s=>{const r=Ha(s.metadata);return e.jsxs("div",{className:"rounded-md border border-border/70 bg-background/70 p-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium",children:_F(s.phase)}),e.jsx(EF,{status:s.status}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[os(s.startedAt),s.finishedAt&&` to ${os(s.finishedAt)}`]})]}),s.command&&e.jsxs("div",{className:"text-xs break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Command: "}),e.jsx("span",{className:"font-mono",children:s.command})]}),s.cwd&&e.jsxs("div",{className:"text-xs break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Working dir: "}),e.jsx("span",{className:"font-mono",children:s.cwd})]}),(un(r==null?void 0:r.branchName)||un(r==null?void 0:r.baseRef)||un(r==null?void 0:r.worktreePath)||un(r==null?void 0:r.repoRoot)||un(r==null?void 0:r.cleanupAction))&&e.jsxs("div",{className:"grid gap-1 text-xs sm:grid-cols-2",children:[un(r==null?void 0:r.branchName)&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Branch: "}),e.jsx("span",{className:"font-mono",children:r==null?void 0:r.branchName})]}),un(r==null?void 0:r.baseRef)&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Base ref: "}),e.jsx("span",{className:"font-mono",children:r==null?void 0:r.baseRef})]}),un(r==null?void 0:r.worktreePath)&&e.jsxs("div",{className:"break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Worktree: "}),e.jsx("span",{className:"font-mono",children:r==null?void 0:r.worktreePath})]}),un(r==null?void 0:r.repoRoot)&&e.jsxs("div",{className:"break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Repo root: "}),e.jsx("span",{className:"font-mono",children:r==null?void 0:r.repoRoot})]}),un(r==null?void 0:r.cleanupAction)&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Cleanup: "}),e.jsx("span",{className:"font-mono",children:r==null?void 0:r.cleanupAction})]})]}),typeof(r==null?void 0:r.created)=="boolean"&&e.jsx("div",{className:"text-xs text-muted-foreground",children:r.created?"Created by this run":"Reused existing workspace"}),s.stderrExcerpt&&s.stderrExcerpt.trim()&&e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-xs text-red-700 dark:text-red-300",children:"stderr excerpt"}),e.jsx("pre",{className:"rounded-md bg-red-50 p-2 text-xs whitespace-pre-wrap break-all text-red-800 dark:bg-neutral-950 dark:text-red-100",children:yr(s.stderrExcerpt,n)})]}),s.stdoutExcerpt&&s.stdoutExcerpt.trim()&&e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"stdout excerpt"}),e.jsx("pre",{className:"rounded-md bg-neutral-100 p-2 text-xs whitespace-pre-wrap break-all dark:bg-neutral-950",children:yr(s.stdoutExcerpt,n)})]}),s.logRef&&e.jsx(TF,{operation:s,censorUsernameInLogs:n})]},s.id)})})]})}function tm(){const{companyPrefix:t,agentId:n,tab:s,runId:r}=Xn(),{companies:a,selectedCompanyId:o,setSelectedCompanyId:i}=et(),{closePanel:l}=ji(),{openNewIssue:u}=In(),{setBreadcrumbs:d}=Ft(),m=at(),p=Sn(),[x,f]=c.useState(null),[h,j]=c.useState(!1),b=r?"runs":CF(s??null),g=b==="dashboard",v=g||(b==="runs"||!!r),[_,E]=c.useState(!1),[S,M]=c.useState(!1),B=c.useRef(null),k=c.useRef(null),{isMobile:L}=mr(),$=n??"",I=c.useMemo(()=>{var ie;if(!t)return null;const D=t.toUpperCase();return((ie=a.find(Ie=>Ie.issuePrefix.toUpperCase()===D))==null?void 0:ie.id)??null},[a,t])??o??void 0,K=$.length>0&&(qd($)||!!I),T=c.useCallback(D=>{B.current=D},[]),z=c.useCallback(D=>{k.current=D},[]),{data:w,isLoading:F,error:A}=oe({queryKey:[...N.agents.detail($),I??null],queryFn:()=>We.get($,I),enabled:K}),R=(w==null?void 0:w.companyId)??o,Q=w?so(w):$,H=(w==null?void 0:w.id)??$,U=(w==null?void 0:w.id)??null,{data:Z}=oe({queryKey:N.agents.runtimeState(U??$),queryFn:()=>We.runtimeState(U,R??void 0),enabled:!!U&&g}),{data:V}=oe({queryKey:N.heartbeats(R,(w==null?void 0:w.id)??void 0),queryFn:()=>Yt.list(R,(w==null?void 0:w.id)??void 0),enabled:!!R&&!!(w!=null&&w.id)&&v}),{data:W}=oe({queryKey:[...N.issues.list(R),"participant-agent",U??"__none__"],queryFn:()=>nt.list(R,{participantAgentId:U}),enabled:!!R&&!!U&&g}),{data:J}=oe({queryKey:N.agents.list(R),queryFn:()=>We.list(R),enabled:!!R&&g}),{data:Y}=oe({queryKey:N.budgets.overview(R??"__none__"),queryFn:()=>Wa.overview(R),enabled:!!R,refetchInterval:3e4,staleTime:5e3}),de=(W??[]).sort((D,ie)=>new Date(ie.updatedAt).getTime()-new Date(D.updatedAt).getTime());(J??[]).find(D=>D.id===(w==null?void 0:w.reportsTo)),(J??[]).filter(D=>D.reportsTo===(w==null?void 0:w.id)&&D.status!=="terminated");const fe=c.useMemo(()=>{const D=Y==null?void 0:Y.policies.find(ue=>ue.scopeType==="agent"&&ue.scopeId===((w==null?void 0:w.id)??$));if(D)return D;const ie=(w==null?void 0:w.budgetMonthlyCents)??0,Ie=(w==null?void 0:w.spentMonthlyCents)??0;return{policyId:"",companyId:R??"",scopeType:"agent",scopeId:(w==null?void 0:w.id)??$,scopeName:(w==null?void 0:w.name)??"Agent",metric:"billed_cents",windowKind:"calendar_month_utc",amount:ie,observedAmount:Ie,remainingAmount:Math.max(0,ie-Ie),utilizationPercent:ie>0?Number((Ie/ie*100).toFixed(2)):0,warnPercent:80,hardStopEnabled:!0,notifyEnabled:!0,isActive:ie>0,status:ie>0&&Ie>=ie?"hard_stop":"ok",paused:(w==null?void 0:w.status)==="paused",pauseReason:(w==null?void 0:w.pauseReason)??null,windowStart:new Date,windowEnd:new Date}},[w,Y==null?void 0:Y.policies,R,$]),Ce=c.useMemo(()=>(V??[]).find(D=>D.status==="running"||D.status==="queued")??null,[V]);c.useEffect(()=>{if(!w)return;if(r){$!==Q&&p(`/agents/${Q}/runs/${r}`,{replace:!0});return}const D=b==="instructions"?"instructions":b==="configuration"?"configuration":b==="skills"?"skills":b==="runs"?"runs":b==="budget"?"budget":b==="access"?"access":"dashboard";if($!==Q||s!==D){p(`/agents/${Q}/${D}`,{replace:!0});return}},[w,$,Q,r,s,b,p]),c.useEffect(()=>{!(w!=null&&w.companyId)||w.companyId===o||i(w.companyId,{source:"route_sync"})},[w==null?void 0:w.companyId,o,i]);const le=ge({mutationFn:async D=>{if(!H)return Promise.reject(new Error("No agent reference"));switch(D){case"invoke":return We.invoke(H,R??void 0);case"pause":return We.pause(H,R??void 0);case"resume":return We.resume(H,R??void 0);case"terminate":return We.terminate(H,R??void 0)}},onSuccess:(D,ie)=>{f(null),m.invalidateQueries({queryKey:N.agents.detail($)}),m.invalidateQueries({queryKey:N.agents.detail(H)}),m.invalidateQueries({queryKey:N.agents.runtimeState(H)}),m.invalidateQueries({queryKey:N.agents.taskSessions(H)}),R&&(m.invalidateQueries({queryKey:N.agents.list(R)}),w!=null&&w.id&&m.invalidateQueries({queryKey:N.heartbeats(R,w.id)})),ie==="invoke"&&D&&typeof D=="object"&&"id"in D&&p(`/agents/${Q}/runs/${D.id}`)},onError:D=>{f(D instanceof Error?D.message:"Action failed")}}),Re=ge({mutationFn:D=>Wa.upsertPolicy(R,{scopeType:"agent",scopeId:(w==null?void 0:w.id)??$,amount:D,windowKind:"calendar_month_utc"}),onSuccess:()=>{R&&(m.invalidateQueries({queryKey:N.budgets.overview(R)}),m.invalidateQueries({queryKey:N.agents.detail($)}),m.invalidateQueries({queryKey:N.agents.detail(H)}),m.invalidateQueries({queryKey:N.agents.list(R)}),m.invalidateQueries({queryKey:N.dashboard(R)}))}}),Pe=ge({mutationFn:D=>We.update(H,{icon:D},R??void 0),onSuccess:()=>{m.invalidateQueries({queryKey:N.agents.detail($)}),m.invalidateQueries({queryKey:N.agents.detail(H)}),R&&m.invalidateQueries({queryKey:N.agents.list(R)})}}),Fe=ge({mutationFn:D=>We.resetSession(H,D,R??void 0),onSuccess:()=>{f(null),m.invalidateQueries({queryKey:N.agents.runtimeState(H)}),m.invalidateQueries({queryKey:N.agents.taskSessions(H)})},onError:D=>{f(D instanceof Error?D.message:"Failed to reset session")}}),pe=ge({mutationFn:D=>We.updatePermissions(H,D,R??void 0),onSuccess:()=>{f(null),m.invalidateQueries({queryKey:N.agents.detail($)}),m.invalidateQueries({queryKey:N.agents.detail(H)}),R&&m.invalidateQueries({queryKey:N.agents.list(R)})},onError:D=>{f(D instanceof Error?D.message:"Failed to update permissions")}});if(c.useEffect(()=>{const D=[{label:"Agents",href:"/agents"}],ie=(w==null?void 0:w.name)??$??"Agent";b==="dashboard"&&!r?D.push({label:ie}):(D.push({label:ie,href:`/agents/${Q}/dashboard`}),r?(D.push({label:"Runs",href:`/agents/${Q}/runs`}),D.push({label:`Run ${r.slice(0,8)}`})):b==="instructions"?D.push({label:"Instructions"}):b==="configuration"?D.push({label:"Configuration"}):b==="runs"?D.push({label:"Runs"}):b==="budget"?D.push({label:"Budget"}):b==="access"?D.push({label:"Access"}):D.push({label:"Dashboard"})),d(D)},[d,w,$,Q,b,r]),c.useEffect(()=>(l(),()=>l()),[l]),xk(c.useCallback(D=>{_&&(D.preventDefault(),D.returnValue="")},[_])),F)return e.jsx(mn,{variant:"detail"});if(A)return e.jsx("p",{className:"text-sm text-destructive",children:A.message});if(!w)return null;if(!r&&!s)return e.jsx(Zt,{to:`/agents/${Q}/dashboard`,replace:!0});const Le=w.status==="pending_approval",q=(b==="configuration"||b==="instructions")&&(_||S);return e.jsxs("div",{className:O("space-y-6",L&&q&&"pb-24"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(DT,{value:w.icon,onChange:D=>Pe.mutate(D),children:e.jsx("button",{className:"shrink-0 flex items-center justify-center h-12 w-12 rounded-lg bg-accent hover:bg-accent/80 transition-colors",children:e.jsx(Cn,{icon:w.icon,className:"h-6 w-6"})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-2xl font-bold truncate",children:w.name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[ed[w.role]??w.role,w.title?` - ${w.title}`:""]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 shrink-0",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>u({assigneeAgentId:w.id}),children:[e.jsx(Ot,{className:"h-3.5 w-3.5 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Assign Task"})]}),e.jsx(Zw,{onClick:()=>le.mutate("invoke"),disabled:le.isPending||Le,label:"Run Heartbeat"}),e.jsx(lF,{isPaused:w.status==="paused",onPause:()=>le.mutate("pause"),onResume:()=>le.mutate("resume"),disabled:le.isPending||Le}),e.jsx("span",{className:"hidden sm:inline",children:e.jsx(Dt,{status:w.status})}),Ce&&e.jsxs(Oe,{to:`/agents/${Q}/runs/${Ce.id}`,className:"sm:hidden flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-blue-500/10 hover:bg-blue-500/20 transition-colors no-underline",children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}),e.jsx("span",{className:"text-[11px] font-medium text-blue-600 dark:text-blue-400",children:"Live"})]}),e.jsxs(Ht,{open:h,onOpenChange:j,children:[e.jsx(Vt,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon-xs",children:e.jsx(xi,{className:"h-4 w-4"})})}),e.jsxs(Qt,{className:"w-44 p-1",align:"end",children:[e.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",onClick:()=>{navigator.clipboard.writeText(w.id),j(!1)},children:[e.jsx(_s,{className:"h-3 w-3"}),"Copy Agent ID"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",onClick:()=>{Fe.mutate(null),j(!1)},children:[e.jsx(Wr,{className:"h-3 w-3"}),"Reset Sessions"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-destructive",onClick:()=>{le.mutate("terminate"),j(!1)},children:[e.jsx(Ls,{className:"h-3 w-3"}),"Terminate"]})]})]})]})]}),!r&&e.jsx(Ss,{value:b,onValueChange:D=>p(`/agents/${Q}/${D}`),children:e.jsx(Ca,{items:[{value:"dashboard",label:"Dashboard"},{value:"instructions",label:"Instructions"},{value:"skills",label:"Skills"},{value:"configuration",label:"Configuration"},{value:"access",label:"Access"},{value:"runs",label:"Runs"},{value:"budget",label:"Budget"}],value:b,onValueChange:D=>p(`/agents/${Q}/${D}`)})}),x&&e.jsx("p",{className:"text-sm text-destructive",children:x}),Le&&e.jsx("p",{className:"text-sm text-amber-500",children:"This agent is pending board approval and cannot be invoked yet."}),!L&&e.jsx("div",{className:O("sticky top-6 z-10 float-right transition-opacity duration-150",q?"opacity-100":"opacity-0 pointer-events-none"),children:e.jsxs("div",{className:"flex items-center gap-2 bg-background/90 backdrop-blur-sm border border-border rounded-lg px-3 py-1.5 shadow-lg",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{var D;return(D=k.current)==null?void 0:D.call(k)},disabled:S,children:"Cancel"}),e.jsx(G,{size:"sm",onClick:()=>{var D;return(D=B.current)==null?void 0:D.call(B)},disabled:S,children:S?"Saving…":"Save"})]})}),L&&q&&e.jsx("div",{className:"fixed inset-x-0 bottom-0 z-30 border-t border-border bg-background/95 backdrop-blur-sm",children:e.jsxs("div",{className:"flex items-center justify-end gap-2 px-3 py-2",style:{paddingBottom:"max(env(safe-area-inset-bottom), 0.5rem)"},children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{var D;return(D=k.current)==null?void 0:D.call(k)},disabled:S,children:"Cancel"}),e.jsx(G,{size:"sm",onClick:()=>{var D;return(D=B.current)==null?void 0:D.call(B)},disabled:S,children:S?"Saving…":"Save"})]})}),b==="dashboard"&&e.jsx(DF,{agent:w,runs:V??[],assignedIssues:de,runtimeState:Z,agentId:w.id,agentRouteId:Q}),b==="instructions"&&e.jsx(qF,{agent:w,companyId:R??void 0,onDirtyChange:E,onSaveActionChange:T,onCancelActionChange:z,onSavingChange:M}),b==="configuration"&&e.jsx(LF,{agent:w,agentId:w.id,companyId:R??void 0,onDirtyChange:E,onSaveActionChange:T,onCancelActionChange:z,onSavingChange:M,updatePermissions:pe}),b==="skills"&&e.jsx(BF,{agent:w,companyId:R??void 0}),b==="runs"&&e.jsx(KF,{runs:V??[],companyId:R,agentId:w.id,agentRouteId:Q,selectedRunId:r??null,adapterType:w.adapterType}),b==="access"&&e.jsx(MF,{agent:w,companyId:R??void 0,updatePermissions:pe}),b==="budget"&&R?e.jsx("div",{className:"max-w-3xl",children:e.jsx(rf,{summary:fe,isSaving:Re.isPending,onSave:D=>Re.mutate(D),variant:"plain"})}):null]})}function PF({checked:t,onChange:n,disabled:s}){return e.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:s,onClick:n,className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 disabled:cursor-not-allowed disabled:opacity-50",t?"bg-green-600":"bg-muted"),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",t?"translate-x-4.5":"translate-x-0.5")})})}function rc({icon:t,title:n,description:s,children:r}){return e.jsxs("div",{className:"rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border bg-muted/30 rounded-t-lg",children:[e.jsx(t,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:n}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s})]})]}),e.jsx("div",{className:"px-4 py-3 space-y-4",children:r})]})}function Yr({label:t,description:n,checked:s,onChange:r,disabled:a,hint:o}){return e.jsxs("div",{className:"flex items-center justify-between gap-4 text-sm",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"text-sm text-foreground",children:t}),(n||o)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:o??n})]}),e.jsx(PF,{checked:s,onChange:r,disabled:a})]})}function nm({paths:t,onChange:n,placeholder:s}){const[r,a]=c.useState(""),o=()=>{const i=r.trim();!i||t.includes(i)||(n([...t,i]),a(""))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:r,onChange:i=>a(i.target.value),onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),o())},placeholder:s,className:"flex-1 text-xs bg-muted/40 border border-border rounded-md px-3 py-1.5 outline-none focus:ring-1 focus:ring-primary font-mono placeholder:text-muted-foreground/50"}),e.jsx(G,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:o,children:"Add"})]}),t.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(i=>e.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-mono bg-muted/60 border border-border rounded px-2 py-0.5",children:[i,e.jsx("button",{onClick:()=>n(t.filter(l=>l!==i)),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(zt,{className:"h-2.5 w-2.5"})})]},i))})]})}function MF({agent:t,companyId:n,updatePermissions:s}){var M,B,k;const r=at(),a=!!((M=t.permissions)!=null&&M.canCreateAgents),o=!!((B=t.access)!=null&&B.canAssignTasks),i=((k=t.access)==null?void 0:k.taskAssignSource)??"none",l=t.role==="ceo"||a,u=i==="ceo_role"?"Enabled automatically for CEO agents.":i==="agent_creator"?"Enabled automatically while this agent can create agents.":i==="explicit_grant"?"Enabled via explicit permission grant.":"Disabled unless explicitly granted.",d=t.metadata??{},[m,p]=c.useState(d.allowedPaths??[]),[x,f]=c.useState(d.blockedPaths??[]),[h,j]=c.useState(d.allowedDomains??[]),[b,g]=c.useState({canReadFiles:!!(d.canReadFiles??!0),canWriteFiles:!!(d.canWriteFiles??!0),canRunCode:!!(d.canRunCode??!0),canUseNetwork:!!(d.canUseNetwork??!0),canUseShell:!!(d.canUseShell??!1),canAccessSecrets:!!(d.canAccessSecrets??!1)}),[y,v]=c.useState(!1),[_,E]=c.useState(!1),S=async()=>{v(!0);try{await We.update(t.id,{metadata:{...d,allowedPaths:m,blockedPaths:x,allowedDomains:h,...b}},n),r.invalidateQueries({queryKey:N.agents.detail(t.id)}),E(!0),setTimeout(()=>E(!1),2e3)}finally{v(!1)}};return e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs(rc,{icon:Ip,title:"Platform Permissions",description:"Controls what this agent can do within CrewSpace",children:[e.jsx(Yr,{label:"Can create new agents",description:"Lets this agent create or hire agents and implicitly assign tasks.",checked:a,onChange:()=>s.mutate({canCreateAgents:!a,canAssignTasks:a?o:!0}),disabled:s.isPending}),e.jsx(Yr,{label:"Can assign tasks",hint:u,checked:o,onChange:()=>s.mutate({canCreateAgents:a,canAssignTasks:!o}),disabled:s.isPending||l})]}),e.jsxs(rc,{icon:tl,title:"Tool Permissions",description:"Controls which tools and capabilities this agent can use",children:[e.jsx(Yr,{label:"Read files",description:"Can read files from the workspace or file system.",checked:b.canReadFiles,onChange:()=>g(L=>({...L,canReadFiles:!L.canReadFiles}))}),e.jsx(Yr,{label:"Write files",description:"Can create or modify files.",checked:b.canWriteFiles,onChange:()=>g(L=>({...L,canWriteFiles:!L.canWriteFiles}))}),e.jsx(Yr,{label:"Execute code",description:"Can run code in a sandbox or shell.",checked:b.canRunCode,onChange:()=>g(L=>({...L,canRunCode:!L.canRunCode}))}),e.jsx(Yr,{label:"Network access",description:"Can make outbound HTTP requests.",checked:b.canUseNetwork,onChange:()=>g(L=>({...L,canUseNetwork:!L.canUseNetwork}))}),e.jsx(Yr,{label:"Shell access",description:"Can run arbitrary shell commands.",checked:b.canUseShell,onChange:()=>g(L=>({...L,canUseShell:!L.canUseShell}))}),e.jsx(Yr,{label:"Access secrets",description:"Can read secrets and API keys stored in the vault.",checked:b.canAccessSecrets,onChange:()=>g(L=>({...L,canAccessSecrets:!L.canAccessSecrets}))})]}),e.jsxs(rc,{icon:j1,title:"File System Access",description:"Restrict which file paths this agent can access",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:"Allowed paths"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to allow all paths. Add paths to restrict access."}),e.jsx(nm,{paths:m,onChange:p,placeholder:"/workspace/src"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:"Blocked paths"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paths the agent is explicitly denied access to."}),e.jsx(nm,{paths:x,onChange:f,placeholder:"/etc/secrets"})]})]}),e.jsx(rc,{icon:Hb,title:"Network Access",description:"Control which external domains this agent can reach",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:"Allowed domains"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to allow all domains. Add domains to allowlist."}),e.jsx(nm,{paths:h,onChange:j,placeholder:"api.github.com"})]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(G,{onClick:S,disabled:y,size:"sm",children:[y?e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):null,y?"Saving…":_?"Saved!":"Save Access Settings"]}),_&&e.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[e.jsx(ho,{className:"h-3.5 w-3.5"}),"Saved"]})]})]})}function $F({runs:t,agentId:n}){if(t.length===0)return null;const s=[...t].sort((m,p)=>new Date(p.createdAt).getTime()-new Date(m.createdAt).getTime()),a=s.find(m=>m.status==="running"||m.status==="queued")??s[0],o=a.status==="running"||a.status==="queued",i=tN[a.status]??{icon:_r,color:"text-neutral-400"},l=i.icon,u=a.resultJson?String(a.resultJson.summary??a.resultJson.result??""):a.error??"",d=c.useMemo(()=>{if(!u)return"";const m=u.replace(/^#{1,6}\s+/gm,"").split(`
|
|
91
|
+
`).map(f=>f.trim()).filter(f=>f.length>0&&!f.startsWith("---")&&!f.startsWith("|")&&!f.startsWith("```")&&!/^[-*>]/.test(f)&&!/^\d+\./.test(f)),p=[];let x=0;for(const f of m){if(p.length>=3||x+f.length>280)break;p.push(f),x+=f.length}return p.join(" ")},[u]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-sm font-medium",children:[o&&e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-cyan-400"})]}),o?"Live Run":"Latest Run"]}),e.jsx(Oe,{to:`/agents/${n}/runs/${a.id}`,className:"shrink-0 text-xs text-muted-foreground hover:text-foreground transition-colors no-underline",children:"View details →"})]}),e.jsxs(Oe,{to:`/agents/${n}/runs/${a.id}`,className:O("block border rounded-lg p-4 space-y-2 w-full no-underline transition-colors hover:bg-muted/50 cursor-pointer",o?"border-cyan-500/30 shadow-[0_0_12px_rgba(6,182,212,0.08)]":"border-border"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l,{className:O("h-3.5 w-3.5",i.color,a.status==="running"&&"animate-spin")}),e.jsx(Dt,{status:a.status}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:a.id.slice(0,8)}),e.jsx("span",{className:O("inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium",a.invocationSource==="timer"?"bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300":a.invocationSource==="assignment"?"bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300":a.invocationSource==="on_demand"?"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300":"bg-muted text-muted-foreground"),children:nN[a.invocationSource]??a.invocationSource}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:os(a.createdAt)})]}),d&&e.jsx("div",{className:"overflow-hidden max-h-16",children:e.jsx(Xs,{className:"[&>*:first-child]:mt-0 [&>*:last-child]:mb-0",children:d})})]})]})}function DF({agent:t,runs:n,assignedIssues:s,runtimeState:r,agentId:a,agentRouteId:o}){return e.jsxs("div",{className:"space-y-8",children:[e.jsx($F,{runs:n,agentId:o}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(pa,{title:"Run Activity",subtitle:"Last 14 days",children:e.jsx(Uw,{runs:n})}),e.jsx(pa,{title:"Issues by Priority",subtitle:"Last 14 days",children:e.jsx(Bw,{issues:s})}),e.jsx(pa,{title:"Issues by Status",subtitle:"Last 14 days",children:e.jsx(Kw,{issues:s})}),e.jsx(pa,{title:"Success Rate",subtitle:"Last 14 days",children:e.jsx(zw,{runs:n})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Recent Issues"}),e.jsx(Oe,{to:`/issues?participantAgentId=${a}`,className:"text-xs text-muted-foreground hover:text-foreground transition-colors",children:"See All →"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recent issues."}):e.jsxs("div",{className:"border border-border rounded-lg",children:[s.slice(0,10).map(i=>e.jsx(gr,{identifier:i.identifier??i.id.slice(0,8),title:i.title,to:`/issues/${i.identifier??i.id}`,trailing:e.jsx(Dt,{status:i.status})},i.id)),s.length>10&&e.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground text-center border-t border-border",children:["+",s.length-10," more issues"]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Costs"}),e.jsx(OF,{runtimeState:r,runs:n})]})]})}function OF({runtimeState:t,runs:n}){const s=n.filter(r=>{const a=cd(r);return a.cost>0||a.input>0||a.output>0||a.cached>0}).sort((r,a)=>new Date(a.createdAt).getTime()-new Date(r.createdAt).getTime());return e.jsxs("div",{className:"space-y-4",children:[t&&e.jsx("div",{className:"border border-border rounded-lg p-4",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 tabular-nums",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground block",children:"Input tokens"}),e.jsx("span",{className:"text-lg font-semibold",children:Et(t.totalInputTokens)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground block",children:"Output tokens"}),e.jsx("span",{className:"text-lg font-semibold",children:Et(t.totalOutputTokens)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground block",children:"Cached tokens"}),e.jsx("span",{className:"text-lg font-semibold",children:Et(t.totalCachedInputTokens)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground block",children:"Total cost"}),e.jsx("span",{className:"text-lg font-semibold",children:ot(t.totalCostCents)})]})]})}),s.length>0&&e.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-accent/20",children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Date"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Run"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium text-muted-foreground",children:"Input"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium text-muted-foreground",children:"Output"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium text-muted-foreground",children:"Cost"})]})}),e.jsx("tbody",{children:s.slice(0,10).map(r=>{const a=cd(r);return e.jsxs("tr",{className:"border-b border-border last:border-b-0",children:[e.jsx("td",{className:"px-3 py-2",children:xs(r.createdAt)}),e.jsx("td",{className:"px-3 py-2 font-mono",children:r.id.slice(0,8)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Et(a.input)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Et(a.output)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:a.cost>0?`$${a.cost.toFixed(4)}`:"-"})]},r.id)})})]})})]})}function LF({agent:t,agentId:n,companyId:s,onDirtyChange:r,onSaveActionChange:a,onCancelActionChange:o,onSavingChange:i,updatePermissions:l}){const u=at(),[d,m]=c.useState(!1),{data:p}=oe({queryKey:N.agents.configRevisions(t.id),queryFn:()=>We.listConfigRevisions(t.id,s)}),x=ge({mutationFn:f=>We.rollbackConfigRevision(t.id,f,s),onSuccess:()=>{u.invalidateQueries({queryKey:N.agents.detail(t.id)}),u.invalidateQueries({queryKey:N.agents.detail(t.urlKey)}),u.invalidateQueries({queryKey:N.agents.configRevisions(t.id)})}});return e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsx(FF,{agent:t,onDirtyChange:r,onSaveActionChange:a,onCancelActionChange:o,onSavingChange:i,updatePermissions:l,companyId:s,hidePromptTemplate:!0,hideInstructionsFile:!0}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-medium mb-3",children:"API Keys"}),e.jsx(WF,{agentId:n,companyId:s})]}),e.jsxs("div",{children:[e.jsxs("button",{className:"flex items-center gap-2 text-sm font-medium hover:text-foreground transition-colors",onClick:()=>m(f=>!f),children:[d?e.jsx(rn,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(sn,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Configuration Revisions",e.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:(p==null?void 0:p.length)??0})]}),d&&e.jsx("div",{className:"mt-3",children:(p??[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No configuration revisions yet."}):e.jsx("div",{className:"space-y-2",children:(p??[]).slice(0,10).map(f=>e.jsxs("div",{className:"border border-border/70 rounded-md p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:f.id.slice(0,8)}),e.jsx("span",{className:"mx-1",children:"·"}),e.jsx("span",{children:xs(f.createdAt)}),e.jsx("span",{className:"mx-1",children:"·"}),e.jsx("span",{children:f.source})]}),e.jsx(G,{size:"sm",variant:"outline",className:"h-7 px-2.5 text-xs",onClick:()=>x.mutate(f.id),disabled:x.isPending,children:"Restore"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Changed:"," ",f.changedKeys.length>0?f.changedKeys.join(", "):"no tracked changes"]})]},f.id))})})]})]})}function FF({agent:t,companyId:n,onDirtyChange:s,onSaveActionChange:r,onCancelActionChange:a,onSavingChange:o,updatePermissions:i,hidePromptTemplate:l,hideInstructionsFile:u}){var S,M,B;const d=at(),{pushToast:m}=ds(),[p,x]=c.useState(!1),f=c.useRef(t),{data:h}=oe({queryKey:n?N.agents.adapterModels(n,t.adapterType):["agents","none","adapter-models",t.adapterType],queryFn:()=>We.adapterModels(n,t.adapterType),enabled:!!n}),j=ge({mutationFn:k=>We.update(t.id,k,n),onMutate:()=>{x(!0)},onSuccess:()=>{d.invalidateQueries({queryKey:N.agents.detail(t.id)}),d.invalidateQueries({queryKey:N.agents.detail(t.urlKey)}),d.invalidateQueries({queryKey:N.agents.configRevisions(t.id)}),d.invalidateQueries({queryKey:N.agents.list(t.companyId)})},onError:k=>{x(!1);const L=k instanceof Qr||k instanceof Error?k.message:"Could not save agent";m({title:"Save failed",body:L,tone:"error"})}});c.useEffect(()=>{p&&t!==f.current&&x(!1),f.current=t},[t,p]);const b=j.isPending||p;c.useEffect(()=>{o(b)},[o,b]);const g=!!((S=t.permissions)!=null&&S.canCreateAgents),y=!!((M=t.access)!=null&&M.canAssignTasks),v=((B=t.access)==null?void 0:B.taskAssignSource)??"none",_=t.role==="ceo"||g,E=v==="ceo_role"?"Enabled automatically for CEO agents.":v==="agent_creator"?"Enabled automatically while this agent can create new agents.":v==="explicit_grant"?"Enabled via explicit company permission grant.":"Disabled unless explicitly granted.";return e.jsxs("div",{className:"space-y-6",children:[e.jsx(sf,{mode:"edit",agent:t,onSave:k=>j.mutate(k),isSaving:b,adapterModels:h,onDirtyChange:s,onSaveActionChange:r,onCancelActionChange:a,hideInlineSave:!0,hidePromptTemplate:l,hideInstructionsFile:u,sectionLayout:"cards"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-medium mb-3",children:"Permissions"}),e.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 text-sm",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{children:"Can create new agents"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Lets this agent create or hire agents and implicitly assign tasks."})]}),e.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":g,className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 disabled:cursor-not-allowed disabled:opacity-50",g?"bg-green-600":"bg-muted"),onClick:()=>i.mutate({canCreateAgents:!g,canAssignTasks:g?y:!0}),disabled:i.isPending,children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",g?"translate-x-4.5":"translate-x-0.5")})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 text-sm",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{children:"Can assign tasks"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:E})]}),e.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":y,className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 disabled:cursor-not-allowed disabled:opacity-50",y?"bg-green-600":"bg-muted"),onClick:()=>i.mutate({canCreateAgents:g,canAssignTasks:!y}),disabled:i.isPending||_,children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",y?"translate-x-4.5":"translate-x-0.5")})})]})]})]})]})}function qF({agent:t,companyId:n,onDirtyChange:s,onSaveActionChange:r,onCancelActionChange:a,onSavingChange:o}){const i=at(),{selectedCompanyId:l}=et(),{isMobile:u}=mr(),[d,m]=c.useState("AGENTS.md"),[p,x]=c.useState(!1),[f,h]=c.useState(null),[j,b]=c.useState(null),[g,y]=c.useState(""),[v,_]=c.useState(!1),[E,S]=c.useState([]),[M,B]=c.useState(new Set),[k,L]=c.useState(260),$=c.useRef(null),[C,I]=c.useState(!1),K=c.useRef(null),T=c.useRef(null);c.useEffect(()=>{m("AGENTS.md"),x(!1),h(null),b(null),y(""),_(!1),S([]),B(new Set),I(!1),K.current=null,T.current=null},[t.id]);const z=t.adapterType==="claude_local"||t.adapterType==="codex_local"||t.adapterType==="opencode_local"||t.adapterType==="pi_local"||t.adapterType==="hermes_local"||t.adapterType==="cursor",{data:w,isLoading:F}=oe({queryKey:N.agents.instructionsBundle(t.id),queryFn:()=>We.instructionsBundle(t.id,n),enabled:!!(n&&z)}),A=(w==null?void 0:w.mode)??"managed",R=A==="managed"?(w==null?void 0:w.managedRootPath)??(w==null?void 0:w.rootPath)??"":(w==null?void 0:w.rootPath)??"",Q=(j==null?void 0:j.mode)??A,H=(j==null?void 0:j.entryFile)??(w==null?void 0:w.entryFile)??"AGENTS.md",U=(j==null?void 0:j.rootPath)??R,Z=c.useMemo(()=>(w==null?void 0:w.files.map(be=>be.path))??[],[w]),V=!!(w&&Q===A&&H===w.entryFile&&U===R),W=c.useMemo(()=>V?[...new Set([H,...Z,...E])]:[H,...E],[V,H,Z,E]),J=c.useMemo(()=>Go(Object.fromEntries(W.map(be=>[be,""]))),[W]),Y=d||H,de=V&&Z.includes(Y),fe=(w==null?void 0:w.files.find(be=>be.path===Y))??null,{data:Ce,isLoading:le}=oe({queryKey:N.agents.instructionsFile(t.id,Y),queryFn:()=>We.instructionsFile(t.id,Y,n),enabled:!!(n&&z&&de)}),Re=ge({mutationFn:be=>We.updateInstructionsBundle(t.id,be,n),onMutate:()=>I(!0),onSuccess:()=>{i.invalidateQueries({queryKey:N.agents.instructionsBundle(t.id)}),i.invalidateQueries({queryKey:N.agents.detail(t.id)}),i.invalidateQueries({queryKey:N.agents.detail(t.urlKey)})},onError:()=>I(!1)}),Pe=ge({mutationFn:be=>We.saveInstructionsFile(t.id,be,n),onMutate:()=>I(!0),onSuccess:(be,he)=>{S(Se=>Se.filter(we=>we!==he.path)),i.invalidateQueries({queryKey:N.agents.instructionsBundle(t.id)}),i.invalidateQueries({queryKey:N.agents.instructionsFile(t.id,he.path)}),i.invalidateQueries({queryKey:N.agents.detail(t.id)}),i.invalidateQueries({queryKey:N.agents.detail(t.urlKey)})},onError:()=>I(!1)}),Fe=ge({mutationFn:be=>We.deleteInstructionsFile(t.id,be,n),onMutate:()=>I(!0),onSuccess:(be,he)=>{i.invalidateQueries({queryKey:N.agents.instructionsBundle(t.id)}),i.removeQueries({queryKey:N.agents.instructionsFile(t.id,he)}),i.invalidateQueries({queryKey:N.agents.detail(t.id)}),i.invalidateQueries({queryKey:N.agents.detail(t.urlKey)})},onError:()=>I(!1)}),pe=ge({mutationFn:async({file:be,namespace:he})=>{if(!l)throw new Error("Select a company to upload images");return Aa.uploadImage(l,be,he)}});c.useEffect(()=>{if(!w)return;if(!V){d!==H&&m(H);return}const be=w.files.map(he=>he.path);if(be.length===0){d!==w.entryFile&&m(w.entryFile);return}!be.includes(d)&&d!==H&&!E.includes(d)&&m(be.includes(w.entryFile)?w.entryFile:be[0])},[w,V,H,E,d]),c.useEffect(()=>{const be=new Set;for(const he of W){const Se=he.split("/");let we="";for(let ee=0;ee<Se.length-1;ee++)we=we?`${we}/${Se[ee]}`:Se[ee],be.add(we)}B(he=>SF(he,be)?he:be)},[W]),c.useEffect(()=>{const be=de&&Ce?`${Ce.path}:${Ce.content}`:`draft:${Q}:${U}:${Y}`;if(C){I(!1),b(null),h(null),K.current=be;return}K.current!==be&&(h(null),K.current=be)},[C,Q,U,Ce,de,Y]),c.useEffect(()=>{w&&b(be=>be||{mode:A,rootPath:R,entryFile:w.entryFile})},[w,A,R]),c.useEffect(()=>{!w||Q!=="external"||(T.current={rootPath:U,entryFile:H,selectedFile:Y})},[w,H,Q,U,Y]);const Le=de?(Ce==null?void 0:Ce.content)??"":"",q=f??Le,D=!!(j&&(j.mode!==A||j.rootPath!==R||j.entryFile!==((w==null?void 0:w.entryFile)??"AGENTS.md"))),ie=f!==null&&f!==Le,Ie=D||ie,ue=Re.isPending||Pe.isPending||Fe.isPending||C;c.useEffect(()=>{o(ue)},[o,ue]),c.useEffect(()=>{s(Ie)},[s,Ie]),c.useEffect(()=>{r(Ie?()=>{(async()=>{const he=!!(w!=null&&w.legacyPromptTemplateActive)||!!(w!=null&&w.legacyBootstrapPromptTemplateActive);D&&j&&await Re.mutateAsync({mode:j.mode,rootPath:j.mode==="external"?j.rootPath:null,entryFile:j.entryFile}),ie&&await Pe.mutateAsync({path:Y,content:q,clearLegacyPromptTemplate:he})})().catch(()=>{})}:null)},[w,D,j,q,ie,Ie,r,Pe,Y,Re]),c.useEffect(()=>{a(Ie?()=>{h(null),w&&b({mode:A,rootPath:R,entryFile:w.entryFile})}:null)},[w,Ie,a,A,R]);const Be=c.useCallback(be=>{be.preventDefault();const he=be.clientX,Se=k,we=me=>{const ye=me.clientX-he,Ke=Math.max(180,Math.min(500,Se+ye));L(Ke)},ee=()=>{document.removeEventListener("mousemove",we),document.removeEventListener("mouseup",ee),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",we),document.addEventListener("mouseup",ee),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[k]);return z?F&&!w?e.jsx(UF,{}):e.jsxs("div",{className:"max-w-6xl space-y-6",children:[((w==null?void 0:w.warnings)??[]).length>0&&e.jsx("div",{className:"space-y-2",children:((w==null?void 0:w.warnings)??[]).map(be=>e.jsx("div",{className:"rounded-md border border-sky-500/25 bg-sky-500/10 px-3 py-2 text-xs text-sky-100",children:be},be))}),e.jsxs(Sa,{defaultOpen:Q==="external",children:[e.jsxs(Ia,{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors group",children:[e.jsx(sn,{className:"h-3 w-3 transition-transform group-data-[state=open]:rotate-90"}),"Advanced"]}),e.jsx(_a,{className:"pt-4 pb-6",children:e.jsx(Lj,{children:e.jsxs("div",{className:"grid gap-x-6 gap-y-4 sm:grid-cols-[auto_1fr_1fr]",children:[e.jsxs("label",{className:"space-y-1.5",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:["Mode",e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx(zo,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),e.jsx(Yn,{side:"right",sideOffset:4,children:"Managed: CrewSpace stores and serves the instructions bundle. External: you provide a path on disk where the instructions live."})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{type:"button",size:"sm",variant:Q==="managed"?"default":"outline",onClick:()=>{Q==="external"&&(T.current={rootPath:U,entryFile:H,selectedFile:Y});const be=H||"AGENTS.md";b({mode:"managed",rootPath:(w==null?void 0:w.managedRootPath)??U,entryFile:be}),m(be)},children:"Managed"}),e.jsx(G,{type:"button",size:"sm",variant:Q==="external"?"default":"outline",onClick:()=>{const be=T.current,he=(be==null?void 0:be.entryFile)??H??"AGENTS.md";b({mode:"external",rootPath:(be==null?void 0:be.rootPath)??((w==null?void 0:w.mode)==="external"?w.rootPath??"":""),entryFile:he}),m((be==null?void 0:be.selectedFile)??he)},children:"External"})]})]}),e.jsxs("label",{className:"space-y-1.5 min-w-0",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:["Root path",e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx(zo,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),e.jsx(Yn,{side:"right",sideOffset:4,children:"The absolute directory on disk where the instructions bundle lives. In managed mode this is set by CrewSpace automatically."})]})]}),Q==="managed"?e.jsxs("div",{className:"flex items-center gap-1.5 font-mono text-xs text-muted-foreground pt-1.5",children:[e.jsx("span",{className:"min-w-0 truncate",title:U||void 0,children:U||"(managed)"}),U&&e.jsx(uo,{text:U,className:"shrink-0",children:e.jsx(_s,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Xt,{value:U,onChange:be=>{const he=be.target.value;T.current={rootPath:he,entryFile:H,selectedFile:Y},b({mode:"external",rootPath:he,entryFile:H})},className:"font-mono text-sm",placeholder:"/absolute/path/to/agent/prompts"}),U&&e.jsx(uo,{text:U,className:"shrink-0",children:e.jsx(_s,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("label",{className:"space-y-1.5",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:["Entry file",e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx(zo,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),e.jsx(Yn,{side:"right",sideOffset:4,children:"The main file the agent reads first when loading instructions. Defaults to AGENTS.md."})]})]}),e.jsx(Xt,{value:H,onChange:be=>{const he=be.target.value||"AGENTS.md",Se=Y===H?he:Y;Q==="external"&&(T.current={rootPath:U,entryFile:he,selectedFile:Se}),Y===H&&m(he),b({mode:Q,rootPath:U,entryFile:he})},className:"font-mono text-sm"})]})]})})})]}),e.jsxs("div",{ref:$,className:O("flex gap-0",u&&"flex-col gap-3"),children:[e.jsxs("div",{className:O("border border-border rounded-lg p-3 space-y-3 shrink-0",u&&p&&"block",u&&!p&&"hidden"),style:u?void 0:{width:k},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Files"}),e.jsxs("div",{className:"flex items-center gap-1",children:[!v&&e.jsx(G,{type:"button",size:"icon",variant:"outline",className:"h-7 w-7",onClick:()=>_(!0),children:"+"}),u&&e.jsx(G,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>x(!1),children:"✕"})]})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Xt,{value:g,onChange:be=>y(be.target.value),placeholder:"TOOLS.md",className:"font-mono text-sm",autoFocus:!0,onKeyDown:be=>{be.key==="Escape"&&(_(!1),y(""))}}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{type:"button",size:"sm",variant:"default",className:"flex-1",disabled:!g.trim()||g.includes(".."),onClick:()=>{const be=g.trim();!be||be.includes("..")||(S(he=>he.includes(be)?he:[...he,be]),m(be),h(""),y(""),_(!1))},children:"Create"}),e.jsx(G,{type:"button",size:"sm",variant:"outline",className:"flex-1",onClick:()=>{_(!1),y("")},children:"Cancel"})]})]}),e.jsx(ou,{nodes:J,selectedFile:Y,expandedDirs:M,checkedFiles:new Set,onToggleDir:be=>B(he=>{const Se=new Set(he);return Se.has(be)?Se.delete(be):Se.add(be),Se}),onSelectFile:be=>{m(be),Z.includes(be)||h(""),u&&x(!1)},onToggleCheck:()=>{},showCheckboxes:!1,renderFileExtra:be=>{const he=w==null?void 0:w.files.find(Se=>Se.path===be.path);return he?he.deprecated?e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("span",{className:"ml-3 shrink-0 rounded border border-amber-500/40 bg-amber-500/10 text-amber-200 px-1.5 py-0.5 text-[10px] uppercase tracking-wide cursor-help",children:"virtual file"})}),e.jsx(Yn,{side:"right",sideOffset:4,children:"Legacy inline prompt — this deprecated virtual file preserves the old promptTemplate content"})]}):e.jsx("span",{className:"ml-3 shrink-0 rounded border border-border text-muted-foreground px-1.5 py-0.5 text-[10px] uppercase tracking-wide",children:he.isEntryFile?"entry":`${he.size}b`}):null}})]}),!u&&e.jsx("div",{className:"w-1 shrink-0 cursor-col-resize hover:bg-border active:bg-primary/50 rounded transition-colors mx-1",onMouseDown:Be}),e.jsxs("div",{className:O("border border-border rounded-lg p-4 space-y-3 min-w-0 flex-1",u&&p&&"hidden"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[u&&e.jsx(G,{type:"button",size:"icon",variant:"outline",className:"h-7 w-7 shrink-0",onClick:()=>x(!0),children:e.jsx(kl,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"text-sm font-medium font-mono truncate",children:Y}),e.jsx("p",{className:"text-xs text-muted-foreground",children:de?fe!=null&&fe.deprecated?"Deprecated virtual file":`${(Ce==null?void 0:Ce.language)??"text"} file`:"New file in this bundle"})]})]}),de&&!(fe!=null&&fe.deprecated)&&Y!==H&&e.jsx(G,{type:"button",size:"sm",variant:"outline",onClick:()=>{confirm(`Delete ${Y}?`)&&Fe.mutate(Y,{onSuccess:()=>{m(H),h(null)}})},disabled:Fe.isPending,children:"Delete"})]}),de&&le&&!Ce?e.jsx(rN,{}):jF(Y)?e.jsx(ps,{value:q,onChange:be=>h(be??""),placeholder:"# Agent instructions",contentClassName:"min-h-[420px] text-sm font-mono",imageUploadHandler:async be=>{const he=`agents/${t.id}/instructions/${Y.replaceAll("/","-")}`;return(await pe.mutateAsync({file:be,namespace:he})).contentPath}},Y):e.jsx("textarea",{value:q,onChange:be=>h(be.target.value),className:"min-h-[420px] w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-sm outline-none",placeholder:"File contents"})]})]})]}):e.jsx("div",{className:"max-w-3xl",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Instructions bundles are only available for local adapters."})})}function UF(){return e.jsxs("div",{className:"max-w-5xl space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{className:"h-4 w-40"}),e.jsx(Ze,{className:"h-4 w-[30rem] max-w-full"})]}),e.jsx(Ze,{className:"h-4 w-16"})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:Array.from({length:3}).map((t,n)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{className:"h-3 w-20"}),e.jsx(Ze,{className:"h-10 w-full"})]},n))})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[260px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ze,{className:"h-4 w-12"}),e.jsx(Ze,{className:"h-8 w-16"})]}),e.jsx(Ze,{className:"h-10 w-full"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((t,n)=>e.jsx(Ze,{className:"h-9 w-full rounded-none"},n))})]}),e.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{className:"h-4 w-48"}),e.jsx(Ze,{className:"h-3 w-28"})]}),e.jsx(rN,{})]})]})]})}function rN(){return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ze,{className:"h-10 w-full"}),e.jsx(Ze,{className:"h-[420px] w-full"})]})}function BF({agent:t,companyId:n}){const s=at(),[r,a]=c.useState([]),[o,i]=c.useState([]),[l,u]=c.useState(!1),d=c.useRef([]),m=c.useRef(!1),p=c.useRef(!0),{data:x,isLoading:f}=oe({queryKey:N.agents.skills(t.id),queryFn:()=>We.skills(t.id,n),enabled:!!n}),{data:h}=oe({queryKey:N.companySkills.list(n??""),queryFn:()=>nr.list(n),enabled:!!n}),j=ge({mutationFn:$=>We.syncSkills(t.id,$,n),onSuccess:async $=>{s.setQueryData(N.agents.skills(t.id),$),d.current=$.desiredSkills,i($.desiredSkills),await Promise.all([s.invalidateQueries({queryKey:N.agents.detail(t.id)}),s.invalidateQueries({queryKey:N.agents.detail(t.urlKey)})])}});c.useEffect(()=>{a([]),i([]),d.current=[],m.current=!1,p.current=!0},[t.id]),c.useEffect(()=>{if(!x)return;const $=xF({draft:r,lastSaved:d.current,hasHydratedSnapshot:m.current},x.desiredSkills);p.current=$.shouldSkipAutosave,m.current=$.hasHydratedSnapshot,a($.draft),d.current=$.lastSaved,i($.lastSaved)},[r,x]),c.useEffect(()=>{if(!x)return;if(p.current){p.current=!1;return}if(j.isPending||bc(r,d.current))return;const $=window.setTimeout(()=>{bc(r,d.current)||j.mutate(r)},250);return()=>window.clearTimeout($)},[r,x,j.isPending,j.mutate]);const b=c.useMemo(()=>new Map((h??[]).map($=>[$.key,$])),[h]),g=c.useMemo(()=>new Set((h??[]).map($=>$.key)),[h]),y=c.useMemo(()=>new Map(((x==null?void 0:x.entries)??[]).map($=>[$.key,$])),[x]),v=c.useMemo(()=>(h??[]).filter($=>{var C;return!((C=y.get($.key))!=null&&C.required)}).map($=>{var C,I,K;return{id:$.id,key:$.key,name:$.name,description:$.description,detail:((C=y.get($.key))==null?void 0:C.detail)??null,locationLabel:((I=y.get($.key))==null?void 0:I.locationLabel)??null,originLabel:((K=y.get($.key))==null?void 0:K.originLabel)??null,linkTo:`/skills/${$.id}`,readOnly:!1,adapterEntry:y.get($.key)??null}}),[y,h]),_=c.useMemo(()=>((x==null?void 0:x.entries)??[]).filter($=>$.required).map($=>{const C=b.get($.key);return{id:(C==null?void 0:C.id)??`required:${$.key}`,key:$.key,name:(C==null?void 0:C.name)??$.key,description:(C==null?void 0:C.description)??null,detail:$.detail??null,locationLabel:$.locationLabel??null,originLabel:$.originLabel??null,linkTo:C?`/skills/${C.id}`:null,readOnly:!1,adapterEntry:$}}),[b,x]),E=c.useMemo(()=>((x==null?void 0:x.entries)??[]).filter($=>fF($,g)).map($=>({id:`external:${$.key}`,key:$.key,name:$.runtimeName??$.key,description:null,detail:$.detail??null,locationLabel:$.locationLabel??null,originLabel:$.originLabel??null,linkTo:null,readOnly:!0,adapterEntry:$})),[g,x]),S=c.useMemo(()=>r.filter($=>!b.has($)),[b,r]),M=c.useMemo(()=>{switch(x==null?void 0:x.mode){case"persistent":return"Kept in the workspace";case"ephemeral":return"Applied when the agent runs";case"unsupported":return"Tracked only";default:return"Unknown"}},[x==null?void 0:x.mode]),B=c.useMemo(()=>(x==null?void 0:x.mode)!=="unsupported"?null:t.adapterType==="openclaw_gateway"?"CrewSpace cannot manage OpenClaw skills here. Visit your OpenClaw instance to manage this agent's skills.":"CrewSpace cannot manage skills for this adapter yet. Manage them in the adapter directly.",[t.adapterType,x==null?void 0:x.mode]),k=!bc(r,o),L=j.isPending?"Saving changes...":k?"Saving soon...":null;return e.jsxs("div",{className:"max-w-4xl space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx(Oe,{to:"/skills",className:"text-sm font-medium text-foreground underline-offset-4 no-underline transition-colors hover:text-foreground/70 hover:underline",children:"View company skills library"}),L?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[j.isPending?e.jsx(kn,{className:"h-3.5 w-3.5 animate-spin"}):null,e.jsx("span",{children:L})]}):null]}),x!=null&&x.warnings.length?e.jsx("div",{className:"space-y-1 rounded-xl border border-amber-300/60 bg-amber-50/60 px-4 py-3 text-sm text-amber-800 dark:border-amber-500/30 dark:bg-amber-950/20 dark:text-amber-200",children:x.warnings.map($=>e.jsx("div",{children:$},$))}):null,B?e.jsx("div",{className:"rounded-xl border border-border px-4 py-3 text-sm text-muted-foreground",children:B}):null,f?e.jsx(mn,{variant:"list"}):e.jsxs(e.Fragment,{children:[(()=>{const $=C=>{const I=C.adapterEntry??y.get(C.key),K=!!(I!=null&&I.required),T=O("flex items-start gap-3 border-b border-border px-3 py-3 text-sm last:border-b-0",C.readOnly?"bg-muted/20":"hover:bg-accent/20"),z=e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:e.jsx("span",{className:"truncate font-medium",children:C.name})}),C.linkTo?e.jsx(Oe,{to:C.linkTo,className:"shrink-0 text-xs text-muted-foreground no-underline hover:text-foreground",children:"View"}):null]}),C.description&&e.jsx(Xs,{className:"mt-1 text-xs text-muted-foreground prose-p:my-1 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",children:C.description}),C.readOnly&&C.originLabel&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:C.originLabel}),C.readOnly&&C.locationLabel&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Location: ",C.locationLabel]}),C.detail&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:C.detail})]});if(C.readOnly)return e.jsxs("div",{className:T,children:[e.jsx("span",{className:"mt-1 h-2 w-2 rounded-full bg-muted-foreground/40"}),z]},C.id);const w=K||r.includes(C.key),F=K||(x==null?void 0:x.mode)==="unsupported",A=e.jsx("input",{type:"checkbox",checked:w,disabled:F,onChange:R=>{const Q=R.target.checked?Array.from(new Set([...r,C.key])):r.filter(H=>H!==C.key);a(Q)},className:"mt-0.5 disabled:cursor-not-allowed disabled:opacity-60"});return e.jsxs("label",{className:T,children:[K&&(I!=null&&I.requiredReason)?e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("span",{children:A})}),e.jsx(Yn,{side:"top",children:I.requiredReason})]}):(x==null?void 0:x.mode)==="unsupported"?e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("span",{children:A})}),e.jsx(Yn,{side:"top",children:B??"Manage skills in the adapter directly."})]}):A,z]},C.id)};return v.length===0&&_.length===0&&E.length===0?e.jsx("section",{className:"border-y border-border",children:e.jsx("div",{className:"px-3 py-6 text-sm text-muted-foreground",children:"Import skills into the company library first, then attach them here."})}):e.jsxs(e.Fragment,{children:[v.length>0&&e.jsx("section",{className:"border-y border-border",children:v.map($)}),_.length>0&&e.jsxs("section",{className:"border-y border-border",children:[e.jsx("div",{className:"border-b border-border bg-muted/40 px-3 py-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Required by CrewSpace"})}),_.map($)]}),E.length>0&&e.jsxs("section",{className:"border-y border-border",children:[e.jsxs("div",{role:"button",tabIndex:0,className:"flex cursor-pointer items-center gap-2 border-b border-border bg-muted/40 px-3 py-2 select-none",onClick:()=>u(C=>!C),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),u(I=>!I))},children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["(",E.length,") User-installed skills, not managed by CrewSpace"]}),l?e.jsx(rn,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(sn,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),l&&E.map($)]})]})})(),S.length>0&&e.jsxs("div",{className:"rounded-xl border border-amber-300/60 bg-amber-50/60 px-4 py-3 text-sm text-amber-800 dark:border-amber-500/30 dark:bg-amber-950/20 dark:text-amber-200",children:[e.jsx("div",{className:"font-medium",children:"Requested skills missing from the company library"}),e.jsx("div",{className:"mt-1 text-xs",children:S.join(", ")})]}),e.jsxs("section",{className:"border-t border-border pt-4",children:[e.jsxs("div",{className:"grid gap-2 text-sm sm:grid-cols-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/60 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Adapter"}),e.jsx("span",{className:"font-medium",children:tu[t.adapterType]??t.adapterType})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/60 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Skills applied"}),e.jsx("span",{children:M})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/60 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Selected skills"}),e.jsx("span",{children:r.length})]})]}),j.isError&&e.jsx("p",{className:"mt-3 text-xs text-destructive",children:j.error instanceof Error?j.error.message:"Failed to update skills"})]})]})]})}function kg({run:t,isSelected:n,agentId:s}){const r=tN[t.status]??{icon:_r,color:"text-neutral-400"},a=r.icon,o=cd(t),i=t.resultJson?String(t.resultJson.summary??t.resultJson.result??""):t.error??"";return e.jsxs(Oe,{to:n?`/agents/${s}/runs`:`/agents/${s}/runs/${t.id}`,className:O("flex flex-col gap-1 w-full px-3 py-2.5 text-left border-b border-border last:border-b-0 transition-colors no-underline text-inherit",n?"bg-accent/40":"hover:bg-accent/20"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a,{className:O("h-3.5 w-3.5 shrink-0",r.color,t.status==="running"&&"animate-spin")}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.id.slice(0,8)}),e.jsx("span",{className:O("inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium shrink-0",t.invocationSource==="timer"?"bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300":t.invocationSource==="assignment"?"bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300":t.invocationSource==="on_demand"?"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300":"bg-muted text-muted-foreground"),children:nN[t.invocationSource]??t.invocationSource}),e.jsx("span",{className:"ml-auto text-[11px] text-muted-foreground shrink-0",children:os(t.createdAt)})]}),i&&e.jsx("span",{className:"text-xs text-muted-foreground truncate pl-5.5",children:i.slice(0,60)}),(o.totalTokens>0||o.cost>0)&&e.jsxs("div",{className:"flex items-center gap-2 pl-5.5 text-[11px] text-muted-foreground tabular-nums",children:[o.totalTokens>0&&e.jsxs("span",{children:[Et(o.totalTokens)," tok"]}),o.cost>0&&e.jsxs("span",{children:["$",o.cost.toFixed(3)]})]})]})}function KF({runs:t,companyId:n,agentId:s,agentRouteId:r,selectedRunId:a,adapterType:o}){var m;const{isMobile:i}=mr();if(t.length===0)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"No runs yet."});const l=[...t].sort((p,x)=>new Date(x.createdAt).getTime()-new Date(p.createdAt).getTime()),u=i?a:a??((m=l[0])==null?void 0:m.id)??null,d=l.find(p=>p.id===u)??null;return i?d?e.jsxs("div",{className:"space-y-3 min-w-0 overflow-x-hidden",children:[e.jsxs(Oe,{to:`/agents/${r}/runs`,className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors no-underline",children:[e.jsx(fo,{className:"h-3.5 w-3.5"}),"Back to runs"]}),e.jsx(Cg,{run:d,agentRouteId:r,adapterType:o},d.id)]}):e.jsx("div",{className:"border border-border rounded-lg overflow-x-hidden",children:l.map(p=>e.jsx(kg,{run:p,isSelected:!1,agentId:r},p.id))}):e.jsxs("div",{className:"flex gap-0",children:[e.jsx("div",{className:O("shrink-0 border border-border rounded-lg",d?"w-72":"w-full"),children:e.jsx("div",{className:"sticky top-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 2rem)"},children:l.map(p=>e.jsx(kg,{run:p,isSelected:p.id===u,agentId:r},p.id))})}),d&&e.jsx("div",{className:"flex-1 min-w-0 pl-4",children:e.jsx(Cg,{run:d,agentRouteId:r,adapterType:o},d.id)})]})}function Cg({run:t,agentRouteId:n,adapterType:s}){const r=at(),a=Sn(),{data:o}=oe({queryKey:N.runDetail(t.id),queryFn:()=>Yt.get(t.id),enabled:!!t.id}),i=o??t,l=cd(i),[u,d]=c.useState(!1),[m,p]=c.useState(null);c.useEffect(()=>{p(null)},[i.id]);const x=ge({mutationFn:()=>Yt.cancel(i.id),onSuccess:()=>{r.invalidateQueries({queryKey:N.heartbeats(i.companyId,i.agentId)})}}),f=i.errorCode==="process_lost"&&i.status==="failed",h=c.useMemo(()=>{const A={resumeFromRunId:i.id},R=Ha(i.contextSnapshot);if(!R)return A;const Q=un(R.issueId),H=un(R.taskId),U=un(R.taskKey),Z=un(R.wakeCommentId)??un(R.commentId);return Q&&(A.issueId=Q),H&&(A.taskId=H),U&&(A.taskKey=U),Z&&(A.commentId=Z),A},[i.contextSnapshot,i.id]),j=ge({mutationFn:async()=>{const A=await We.wakeup(i.agentId,{source:"on_demand",triggerDetail:"manual",reason:"resume_process_lost_run",payload:h},i.companyId);if(!("id"in A))throw new Error("Resume request was skipped because the agent is not currently invokable.");return A},onSuccess:A=>{r.invalidateQueries({queryKey:N.heartbeats(i.companyId,i.agentId)}),a(`/agents/${n}/runs/${A.id}`)}}),b=i.status==="failed"||i.status==="timed_out",g=c.useMemo(()=>{const A={},R=Ha(i.contextSnapshot);if(!R)return A;const Q=un(R.issueId),H=un(R.taskId),U=un(R.taskKey);return Q&&(A.issueId=Q),H&&(A.taskId=H),U&&(A.taskKey=U),A},[i.contextSnapshot]),y=ge({mutationFn:async()=>{const A=await We.wakeup(i.agentId,{source:"on_demand",triggerDetail:"manual",reason:"retry_failed_run",payload:g},i.companyId);if(!("id"in A))throw new Error("Retry was skipped because the agent is not currently invokable.");return A},onSuccess:A=>{r.invalidateQueries({queryKey:N.heartbeats(i.companyId,i.agentId)}),a(`/agents/${n}/runs/${A.id}`)}}),{data:v}=oe({queryKey:N.runIssues(i.id),queryFn:()=>ya.issuesForRun(i.id)}),_=c.useMemo(()=>Array.from(new Set((v??[]).map(A=>A.issueId))),[v]),E=ge({mutationFn:async()=>_.length===0?0:(await Promise.all(_.map(A=>We.resetSession(i.agentId,A,i.companyId))),_.length),onSuccess:()=>{r.invalidateQueries({queryKey:N.agents.runtimeState(i.agentId)}),r.invalidateQueries({queryKey:N.agents.taskSessions(i.agentId)}),r.invalidateQueries({queryKey:N.runIssues(i.id)})}}),S=ge({mutationFn:()=>We.loginWithClaude(i.agentId,i.companyId),onSuccess:A=>{p(A)}}),M=i.status==="running"&&!!i.startedAt&&!i.finishedAt,[B,k]=c.useState(()=>i.startedAt?Math.max(0,Math.round((Date.now()-new Date(i.startedAt).getTime())/1e3)):0);c.useEffect(()=>{if(!M||!i.startedAt)return;const A=new Date(i.startedAt).getTime();k(Math.max(0,Math.round((Date.now()-A)/1e3)));const R=setInterval(()=>{k(Math.max(0,Math.round((Date.now()-A)/1e3)))},1e3);return()=>clearInterval(R)},[M,i.startedAt]);const L={hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1},$=i.startedAt?new Date(i.startedAt).toLocaleTimeString("en-US",L):null,C=i.finishedAt?new Date(i.finishedAt).toLocaleTimeString("en-US",L):null,K=(i.startedAt&&i.finishedAt?Math.round((new Date(i.finishedAt).getTime()-new Date(i.startedAt).getTime())/1e3):null)??(M?B:null),T=l.input>0||l.output>0||l.cached>0||l.cost>0,z=!!(i.sessionIdBefore||i.sessionIdAfter),w=i.sessionIdBefore&&i.sessionIdAfter&&i.sessionIdBefore!==i.sessionIdAfter;i.sessionIdAfter||i.sessionIdBefore;const F=i.exitCode!==null&&i.exitCode!==0;return e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsxs("div",{className:"flex-1 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{status:i.status}),(i.status==="running"||i.status==="queued")&&e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive text-xs h-6 px-2",onClick:()=>x.mutate(),disabled:x.isPending,children:x.isPending?"Cancelling…":"Cancel"}),f&&e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs h-6 px-2",onClick:()=>j.mutate(),disabled:j.isPending,children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),j.isPending?"Resuming…":"Resume"]}),b&&!f&&e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs h-6 px-2",onClick:()=>y.mutate(),disabled:y.isPending,children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),y.isPending?"Retrying…":"Retry"]})]}),j.isError&&e.jsx("div",{className:"text-xs text-destructive",children:j.error instanceof Error?j.error.message:"Failed to resume run"}),y.isError&&e.jsx("div",{className:"text-xs text-destructive",children:y.error instanceof Error?y.error.message:"Failed to retry run"}),$&&e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"text-sm font-mono",children:[$,C&&e.jsx("span",{className:"text-muted-foreground",children:" → "}),C]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[os(i.startedAt),i.finishedAt&&e.jsxs(e.Fragment,{children:[" → ",os(i.finishedAt)]})]}),K!==null&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Duration: ",K>=60?`${Math.floor(K/60)}m ${K%60}s`:`${K}s`]})]}),i.error&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-red-600 dark:text-red-400",children:i.error}),i.errorCode&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",i.errorCode,")"]})]}),i.errorCode==="claude_auth_required"&&s==="claude_local"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>S.mutate(),disabled:S.isPending,children:S.isPending?"Running claude login...":"Login to Claude Code"}),S.isError&&e.jsx("p",{className:"text-xs text-destructive",children:S.error instanceof Error?S.error.message:"Failed to run Claude login"}),(m==null?void 0:m.loginUrl)&&e.jsxs("p",{className:"text-xs",children:["Login URL:",e.jsx("a",{href:m.loginUrl,className:"text-blue-600 underline underline-offset-2 ml-1 break-all dark:text-blue-400",target:"_blank",rel:"noreferrer",children:m.loginUrl})]}),m&&e.jsxs(e.Fragment,{children:[!!m.stdout&&e.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap",children:m.stdout}),!!m.stderr&&e.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap",children:m.stderr})]})]}),F&&e.jsxs("div",{className:"text-xs text-red-600 dark:text-red-400",children:["Exit code ",i.exitCode,i.signal&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(signal: ",i.signal,")"]})]})]}),T&&e.jsxs("div",{className:"border-t sm:border-t-0 sm:border-l border-border p-4 grid grid-cols-2 gap-x-4 sm:gap-x-8 gap-y-3 content-center tabular-nums",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Input"}),e.jsx("div",{className:"text-sm font-medium font-mono",children:Et(l.input)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Output"}),e.jsx("div",{className:"text-sm font-medium font-mono",children:Et(l.output)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cached"}),e.jsx("div",{className:"text-sm font-medium font-mono",children:Et(l.cached)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cost"}),e.jsx("div",{className:"text-sm font-medium font-mono",children:l.cost>0?`$${l.cost.toFixed(4)}`:"-"})]})]})]}),z&&e.jsxs("div",{className:"border-t border-border",children:[e.jsxs("button",{className:"flex items-center gap-1.5 w-full px-4 py-2 text-xs text-muted-foreground hover:text-foreground transition-colors",onClick:()=>d(A=>!A),children:[e.jsx(sn,{className:O("h-3 w-3 transition-transform",u&&"rotate-90")}),"Session",w&&e.jsx("span",{className:"text-yellow-400 ml-1",children:"(changed)"})]}),u&&e.jsxs("div",{className:"px-4 pb-3 space-y-1 text-xs",children:[i.sessionIdBefore&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-12",children:w?"Before":"ID"}),e.jsx(uo,{text:i.sessionIdBefore,className:"font-mono"})]}),w&&i.sessionIdAfter&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-12",children:"After"}),e.jsx(uo,{text:i.sessionIdAfter,className:"font-mono"})]}),_.length>0&&e.jsxs("div",{className:"pt-1",children:[e.jsx("button",{type:"button",className:"text-[11px] text-muted-foreground underline underline-offset-2 hover:text-foreground disabled:opacity-60",disabled:E.isPending,onClick:()=>{const A=_.length;window.confirm(`Clear session for ${A} issue${A===1?"":"s"} touched by this run?`)&&E.mutate()},children:E.isPending?"clearing session...":"clear session for these issues"}),E.isError&&e.jsx("p",{className:"text-[11px] text-destructive mt-1",children:E.error instanceof Error?E.error.message:"Failed to clear sessions"})]})]})]})]}),v&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Issues Touched (",v.length,")"]}),e.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:v.map(A=>e.jsxs(Oe,{to:`/issues/${A.identifier??A.issueId}`,className:"flex items-center justify-between w-full px-3 py-2 text-xs hover:bg-accent/20 transition-colors text-left no-underline text-inherit",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Dt,{status:A.status}),e.jsx("span",{className:"truncate",children:A.title})]}),e.jsx("span",{className:"font-mono text-muted-foreground shrink-0 ml-2",children:A.identifier??A.issueId.slice(0,8)})]},A.issueId))})]}),i.stderrExcerpt&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs font-medium text-red-600 dark:text-red-400",children:"stderr"}),e.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap",children:i.stderrExcerpt})]}),i.stdoutExcerpt&&!i.logRef&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"stdout"}),e.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap",children:i.stdoutExcerpt})]}),e.jsx(zF,{run:i,adapterType:s}),e.jsx(eN,{})]})}function zF({run:t,adapterType:n}){var H;const[s,r]=c.useState([]),[a,o]=c.useState([]),[i,l]=c.useState(!0),[u,d]=c.useState(!!t.logRef),[m,p]=c.useState(null),[x,f]=c.useState(0),[h,j]=c.useState(!1),[b,g]=c.useState(!1),[y,v]=c.useState("nice"),_=c.useRef(null),E=c.useRef(""),S=c.useRef(null),M=c.useRef(!1),B=c.useRef({scrollHeight:0,distanceFromBottom:Number.POSITIVE_INFINITY}),k=t.status==="running"||t.status==="queued",{data:L=[]}=oe({queryKey:N.runWorkspaceOperations(t.id),queryFn:()=>Yt.workspaceOperations(t.id),refetchInterval:k?2e3:!1});function $(U){return U instanceof Qr&&U.status===404}function C(U,Z=!1){if(!U&&!Z)return;const W=`${E.current}${U}`.split(`
|
|
92
|
+
`);E.current=W.pop()??"",Z&&E.current&&(W.push(E.current),E.current="");const J=[];for(const Y of W){const de=Y.trim();if(de)try{const fe=JSON.parse(de),Ce=fe.stream==="stderr"||fe.stream==="system"?fe.stream:"stdout",le=typeof fe.chunk=="string"?fe.chunk:"",Re=typeof fe.ts=="string"?fe.ts:new Date().toISOString();if(!le)continue;J.push({ts:Re,stream:Ce,chunk:le})}catch{}}J.length>0&&o(Y=>[...Y,...J])}const{data:I}=oe({queryKey:["run-events",t.id],queryFn:()=>Yt.events(t.id,0,200)});c.useEffect(()=>{I&&(r(I),l(!1))},[I]);const K=c.useCallback(()=>{if(S.current)return S.current;const U=kF(_.current);return S.current=U,U},[]),T=c.useCallback(()=>{const U=K(),Z=sc(U);B.current=Z;const V=Z.distanceFromBottom<=wg;M.current=V,j(W=>W===V?W:V)},[K]);c.useEffect(()=>{if(S.current=null,B.current={scrollHeight:0,distanceFromBottom:Number.POSITIVE_INFINITY},!k){M.current=!1,j(!1);return}T()},[k,t.id,T]),c.useEffect(()=>{if(!k)return;const U=K();return T(),U===window?window.addEventListener("scroll",T,{passive:!0}):U.addEventListener("scroll",T,{passive:!0}),window.addEventListener("resize",T),()=>{U===window?window.removeEventListener("scroll",T):U.removeEventListener("scroll",T),window.removeEventListener("resize",T)}},[k,t.id,K,T]),c.useEffect(()=>{if(!k||!M.current)return;const U=K(),Z=B.current,V=sc(U),W=Math.max(0,V.scrollHeight-Z.scrollHeight),J=Z.distanceFromBottom+W;if(V.distanceFromBottom-J>wg){M.current=!1,j(!1),B.current=V;return}Ng(U,"auto");const de=sc(U);B.current=de,M.current||(M.current=!0),j(fe=>fe||!0)},[s.length,a.length,k,K]),c.useEffect(()=>{let U=!1;if(E.current="",o([]),f(0),p(null),!t.logRef&&!k)return d(!1),()=>{U=!0};d(!0);const Z=typeof t.logBytes=="number"&&t.logBytes>0?Math.min(Math.max(t.logBytes+1024,256e3),2e6):256e3;return(async()=>{try{let W=0,J=!0;for(;!U;){const Y=await Yt.log(t.id,W,J?Z:256e3);if(U)break;C(Y.content,Y.nextOffset===void 0);const de=Y.nextOffset??W+Y.content.length;if(f(de),W=de,J=!1,Y.nextOffset===void 0||k)break}}catch(W){if(!U){if(k&&$(W)){d(!1);return}p(W instanceof Error?W.message:"Failed to load run log")}}finally{U||d(!1)}})(),()=>{U=!0}},[t.id,t.logRef,t.logBytes,k]),c.useEffect(()=>{if(!k||b)return;const U=setInterval(async()=>{const Z=s.length>0?Math.max(...s.map(V=>V.seq)):0;try{const V=await Yt.events(t.id,Z,100);V.length>0&&r(W=>[...W,...V])}catch{}},2e3);return()=>clearInterval(U)},[t.id,k,b,s]),c.useEffect(()=>{if(!k||b)return;const U=setInterval(async()=>{try{const Z=await Yt.log(t.id,x,256e3);Z.content&&C(Z.content,Z.nextOffset===void 0),Z.nextOffset!==void 0?f(Z.nextOffset):Z.content.length>0&&f(V=>V+Z.content.length)}catch(Z){if($(Z))return}},2e3);return()=>clearInterval(U)},[t.id,k,b,x]),c.useEffect(()=>{if(!k)return;let U=!1,Z=null,V=null;const W=()=>{U||(Z=window.setTimeout(J,1500))},J=()=>{if(U)return;const de=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/companies/${encodeURIComponent(t.companyId)}/events/ws`;V=new WebSocket(de),V.onopen=()=>{g(!0)},V.onmessage=fe=>{const Ce=typeof fe.data=="string"?fe.data:"";if(!Ce)return;let le;try{le=JSON.parse(Ce)}catch{return}if(le.companyId!==t.companyId)return;const Re=Ha(le.payload),Pe=un(Re==null?void 0:Re.runId);if(!Re||Pe!==t.id)return;if(le.type==="heartbeat.run.log"){const Ie=typeof Re.chunk=="string"?Re.chunk:"";if(!Ie)return;const ue=un(Re.stream),Be=ue==="stderr"||ue==="system"?ue:"stdout",be=un(Re.ts)??le.createdAt;o(he=>[...he,{ts:be,stream:Be,chunk:Ie}]);return}if(le.type!=="heartbeat.run.event")return;const Fe=typeof Re.seq=="number"?Re.seq:null;if(Fe===null||!Number.isFinite(Fe))return;const pe=un(Re.stream),Le=pe==="stdout"||pe==="stderr"||pe==="system"?pe:null,q=un(Re.level),D=q==="info"||q==="warn"||q==="error"?q:null,ie={id:Fe,companyId:t.companyId,runId:t.id,agentId:t.agentId,seq:Fe,eventType:un(Re.eventType)??"event",stream:Le,level:D,color:un(Re.color),message:un(Re.message),payload:Ha(Re.payload),createdAt:new Date(le.createdAt)};r(Ie=>Ie.some(ue=>ue.seq===Fe)?Ie:[...Ie,ie])},V.onerror=()=>{V==null||V.close()},V.onclose=()=>{g(!1),W()}};return J(),()=>{U=!0,g(!1),Z!==null&&window.clearTimeout(Z),V&&(V.onopen=null,V.onmessage=null,V.onerror=null,V.onclose=null,V.close(1e3,"run_detail_unmount"))}},[k,t.companyId,t.id,t.agentId]);const z=((H=oe({queryKey:N.instance.generalSettings,queryFn:()=>Rr.getGeneral()}).data)==null?void 0:H.censorUsernameInLogs)===!0,w=c.useMemo(()=>{const U=s.find(Z=>Z.eventType==="adapter.invoke");return Oo(Ha((U==null?void 0:U.payload)??null),z)},[z,s]),F=c.useMemo(()=>oo(n),[n]),A=c.useMemo(()=>ew(a,F.parseStdoutLine,{censorUsernameInLogs:z}),[F,z,a]);if(c.useEffect(()=>{v("nice")},[t.id]),i&&u)return e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading run logs..."});if(s.length===0&&a.length===0&&!m)return e.jsx("p",{className:"text-xs text-muted-foreground",children:"No log events."});const R={info:"text-foreground",warn:"text-yellow-600 dark:text-yellow-400",error:"text-red-600 dark:text-red-400"},Q={stdout:"text-foreground",stderr:"text-red-600 dark:text-red-300",system:"text-blue-600 dark:text-blue-300"};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(RF,{operations:L,censorUsernameInLogs:z}),w&&e.jsxs("div",{className:"rounded-lg border border-border bg-background/60 p-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Invocation"}),typeof w.adapterType=="string"&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Adapter: "}),w.adapterType]}),typeof w.cwd=="string"&&e.jsxs("div",{className:"text-xs break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Working dir: "}),e.jsx("span",{className:"font-mono",children:w.cwd})]}),typeof w.command=="string"&&e.jsxs("div",{className:"text-xs break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Command: "}),e.jsx("span",{className:"font-mono",children:[w.command,...Array.isArray(w.commandArgs)?w.commandArgs.filter(U=>typeof U=="string"):[]].join(" ")})]}),Array.isArray(w.commandNotes)&&w.commandNotes.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Command notes"}),e.jsx("ul",{className:"list-disc pl-5 space-y-1",children:w.commandNotes.filter(U=>typeof U=="string"&&U.trim().length>0).map((U,Z)=>e.jsx("li",{className:"text-xs break-all font-mono",children:U},`${Z}-${U}`))})]}),w.prompt!==void 0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Prompt"}),e.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap",children:typeof w.prompt=="string"?yr(w.prompt,z):JSON.stringify(Oo(w.prompt,z),null,2)})]}),w.context!==void 0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Context"}),e.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(Oo(w.context,z),null,2)})]}),w.env!==void 0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Environment"}),e.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap font-mono",children:wF(w.env,z)})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Transcript (",A.length,")"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"inline-flex rounded-lg border border-border/70 bg-background/70 p-0.5",children:["nice","raw"].map(U=>e.jsx("button",{type:"button",className:O("rounded-md px-2.5 py-1 text-[11px] font-medium capitalize transition-colors",y===U?"bg-accent text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),onClick:()=>v(U),children:U},U))}),k&&!h&&e.jsx(G,{variant:"ghost",size:"xs",onClick:()=>{const U=K();M.current=!0,j(!0),Ng(U,"auto"),B.current=sc(U)},children:"Jump to live"}),k&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-cyan-400",children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-cyan-400"})]}),"Live"]})]})]}),e.jsxs("div",{className:"max-h-[38rem] overflow-y-auto rounded-2xl border border-border/70 bg-background/40 p-3 sm:p-4",children:[e.jsx(Ni,{entries:A,mode:y,streaming:k,emptyMessage:t.logRef?"Waiting for transcript...":"No persisted transcript for this run."}),m&&e.jsx("div",{className:"mt-3 rounded-xl border border-red-500/20 bg-red-500/[0.06] px-3 py-2 text-xs text-red-700 dark:text-red-300",children:m}),e.jsx("div",{ref:_})]}),(t.status==="failed"||t.status==="timed_out")&&e.jsxs("div",{className:"rounded-lg border border-red-300 dark:border-red-500/30 bg-red-50 dark:bg-red-950/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-red-700 dark:text-red-300",children:"Failure details"}),t.error&&e.jsxs("div",{className:"text-xs text-red-600 dark:text-red-200",children:[e.jsx("span",{className:"text-red-700 dark:text-red-300",children:"Error: "}),yr(t.error,z)]}),t.stderrExcerpt&&t.stderrExcerpt.trim()&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-red-700 dark:text-red-300 mb-1",children:"stderr excerpt"}),e.jsx("pre",{className:"bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100",children:yr(t.stderrExcerpt,z)})]}),t.resultJson&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-red-700 dark:text-red-300 mb-1",children:"adapter result JSON"}),e.jsx("pre",{className:"bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100",children:JSON.stringify(Oo(t.resultJson,z),null,2)})]}),t.stdoutExcerpt&&t.stdoutExcerpt.trim()&&!t.resultJson&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-red-700 dark:text-red-300 mb-1",children:"stdout excerpt"}),e.jsx("pre",{className:"bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100",children:yr(t.stdoutExcerpt,z)})]})]}),s.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Events (",s.length,")"]}),e.jsx("div",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-lg p-3 font-mono text-xs space-y-0.5",children:s.map(U=>{const Z=U.color??(U.level?R[U.level]:null)??(U.stream?Q[U.stream]:null)??"text-foreground";return e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-neutral-400 dark:text-neutral-600 shrink-0 select-none w-16",children:new Date(U.createdAt).toLocaleTimeString("en-US",{hour12:!1})}),e.jsx("span",{className:O("shrink-0 w-14",U.stream?Q[U.stream]??"text-neutral-500":"text-neutral-500"),children:U.stream?`[${U.stream}]`:""}),e.jsx("span",{className:O("break-all",Z),children:U.message?yr(U.message,z):U.payload?JSON.stringify(Oo(U.payload,z)):""})]},U.id)})})]})]})}function WF({agentId:t,companyId:n}){const s=at(),[r,a]=c.useState(""),[o,i]=c.useState(null),[l,u]=c.useState(!1),[d,m]=c.useState(!1),{data:p,isLoading:x}=oe({queryKey:N.agents.keys(t),queryFn:()=>We.listKeys(t,n)}),f=ge({mutationFn:()=>We.createKey(t,r.trim()||"Default",n),onSuccess:y=>{i(y.token),u(!0),a(""),s.invalidateQueries({queryKey:N.agents.keys(t)})}}),h=ge({mutationFn:y=>We.revokeKey(t,y,n),onSuccess:()=>{s.invalidateQueries({queryKey:N.agents.keys(t)})}});function j(){o&&(navigator.clipboard.writeText(o),m(!0),setTimeout(()=>m(!1),2e3))}const b=(p??[]).filter(y=>!y.revokedAt),g=(p??[]).filter(y=>y.revokedAt);return e.jsxs("div",{className:"space-y-6",children:[o&&e.jsxs("div",{className:"border border-yellow-300 dark:border-yellow-600/40 bg-yellow-50 dark:bg-yellow-500/5 rounded-lg p-4 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-yellow-700 dark:text-yellow-400",children:"API key created — copy it now, it will not be shown again."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 bg-neutral-100 dark:bg-neutral-950 rounded px-3 py-1.5 text-xs font-mono text-green-700 dark:text-green-300 truncate",children:l?o:o.replace(/./g,"•")}),e.jsx(G,{variant:"ghost",size:"icon-sm",onClick:()=>u(y=>!y),title:l?"Hide":"Show",children:l?e.jsx(al,{className:"h-3.5 w-3.5"}):e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon-sm",onClick:j,title:"Copy",children:e.jsx(_s,{className:"h-3.5 w-3.5"})}),d&&e.jsx("span",{className:"text-xs text-green-400",children:"Copied!"})]}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-muted-foreground text-xs",onClick:()=>i(null),children:"Dismiss"})]}),e.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[e.jsxs("h3",{className:"text-xs font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(k1,{className:"h-3.5 w-3.5"}),"Create API Key"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"API keys allow this agent to authenticate calls to the CrewSpace server."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{placeholder:"Key name (e.g. production)",value:r,onChange:y=>a(y.target.value),className:"h-8 text-sm",onKeyDown:y=>{y.key==="Enter"&&f.mutate()}}),e.jsxs(G,{size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1"}),"Create"]})]})]}),x&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading keys..."}),!x&&b.length===0&&!o&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No active API keys."}),b.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Active Keys"}),e.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:b.map(y=>e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:y.name}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-3",children:["Created ",xs(y.createdAt)]})]}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive text-xs",onClick:()=>h.mutate(y.id),disabled:h.isPending,children:"Revoke"})]},y.id))})]}),g.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Revoked Keys"}),e.jsx("div",{className:"border border-border rounded-lg divide-y divide-border opacity-50",children:g.map(y=>e.jsx("div",{className:"flex items-center justify-between px-4 py-2.5",children:e.jsxs("div",{children:[e.jsx("span",{className:"text-sm line-through",children:y.name}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-3",children:["Revoked ",y.revokedAt?xs(y.revokedAt):""]})]})},y.id))})]})]})}function HF(){const{selectedCompanyId:t}=et(),{openNewProject:n}=In(),{setBreadcrumbs:s}=Ft();c.useEffect(()=>{s([{label:"Projects"}])},[s]);const{data:r,isLoading:a,error:o}=oe({queryKey:N.projects.list(t),queryFn:()=>en.list(t),enabled:!!t}),i=c.useMemo(()=>(r??[]).filter(l=>!l.archivedAt),[r]);return t?a?e.jsx(mn,{variant:"list"}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(G,{size:"sm",variant:"outline",onClick:n,children:[e.jsx(Ot,{className:"h-4 w-4 mr-1"}),"Add Project"]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o.message}),!a&&i.length===0&&e.jsx(tn,{icon:Sr,message:"No projects yet.",action:"Add Project",onAction:n}),i.length>0&&e.jsx("div",{className:"border border-border",children:i.map(l=>e.jsx(gr,{title:l.name,subtitle:l.description??void 0,to:El(l),trailing:e.jsxs("div",{className:"flex items-center gap-3",children:[l.targetDate&&e.jsx("span",{className:"text-xs text-muted-foreground",children:xs(l.targetDate)}),e.jsx(Dt,{status:l.status})]})},l.id))})]}):e.jsx(tn,{icon:Sr,message:"Select a company to view projects."})}function yn({className:t,orientation:n="horizontal",decorative:s=!0,...r}){return e.jsx(PC,{"data-slot":"separator",decorative:s,orientation:n,className:O("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}const VF=250,QF=1600;function aN(){const[t,n]=c.useState("idle"),s=c.useRef(0),r=c.useRef(null),a=c.useRef(null),o=c.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null),a.current&&(clearTimeout(a.current),a.current=null)},[]);c.useEffect(()=>o,[o]);const i=c.useCallback(()=>{s.current+=1,o(),n("idle")},[o]),l=c.useCallback(()=>{o(),n("idle")},[o]),u=c.useCallback(async d=>{const m=s.current+1;s.current=m,o(),r.current=setTimeout(()=>{s.current===m&&n("saving")},VF);try{if(await d(),s.current!==m)return;o(),n("saved"),a.current=setTimeout(()=>{s.current===m&&n("idle")},QF)}catch(p){throw s.current!==m||(o(),n("error")),p}},[o]);return{state:t,markDirty:l,reset:i,runSave:u}}const Sg="px-1 -mx-1",GF="px-1",JF=900;function kr({value:t,onSave:n,as:s="span",className:r,placeholder:a="Click to edit...",multiline:o=!1,imageUploadHandler:i,mentions:l}){const[u,d]=c.useState(!1),[m,p]=c.useState(!1),[x,f]=c.useState(t),h=c.useRef(null),j=c.useRef(null),b=c.useRef(null),{state:g,markDirty:y,reset:v,runSave:_}=aN();c.useEffect(()=>{o&&m||f(t)},[t,o,m]),c.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const E=c.useCallback(k=>{k&&(k.style.height="auto",k.style.height=`${k.scrollHeight}px`)},[]);c.useEffect(()=>{u&&h.current&&(h.current.focus(),h.current.select(),h.current instanceof HTMLTextAreaElement&&E(h.current))},[u,E]),c.useEffect(()=>{if(!u||!o)return;const k=requestAnimationFrame(()=>{var L;(L=j.current)==null||L.focus()});return()=>cancelAnimationFrame(k)},[u,o]);const S=c.useCallback(async(k=x)=>{const L=k.trim();L&&L!==t?await Promise.resolve(n(L)):f(t),o||d(!1)},[x,o,n,t]);function M(k){k.key==="Enter"&&!o&&(k.preventDefault(),S()),k.key==="Escape"&&(b.current&&clearTimeout(b.current),v(),f(t),o?(p(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):d(!1))}if(c.useEffect(()=>{if(!o||!m)return;const k=x.trim();if(!k||k===t){g!=="saved"&&v();return}return y(),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{_(()=>S(k))},JF),()=>{b.current&&clearTimeout(b.current)}},[g,S,x,y,o,m,v,_,t]),o)return e.jsxs("div",{className:O(GF,"rounded transition-colors",m?"bg-transparent":"hover:bg-accent/20"),onFocusCapture:()=>p(!0),onBlurCapture:k=>{if(k.currentTarget.contains(k.relatedTarget))return;b.current&&clearTimeout(b.current),p(!1);const L=x.trim();if(!L||L===t){v(),S();return}_(()=>S())},onKeyDown:M,children:[e.jsx(ps,{ref:j,value:x,onChange:f,placeholder:a,bordered:!1,className:"bg-transparent",contentClassName:O("crewspace-edit-in-place-content",r),imageUploadHandler:i,mentions:l,onSubmit:()=>{const k=x.trim();if(!k||k===t){v(),S();return}_(()=>S())}}),e.jsx("div",{className:"flex min-h-4 items-center justify-end pr-1",children:e.jsx("span",{className:O("text-[11px] transition-opacity duration-150",g==="error"?"text-destructive":"text-muted-foreground",g==="idle"?"opacity-0":"opacity-100"),children:g==="saving"?"Autosaving...":g==="saved"?"Saved":g==="error"?"Could not save":"Idle"})})]});if(u)return e.jsx("textarea",{ref:h,value:x,rows:1,onChange:k=>{f(k.target.value),E(k.target)},onBlur:()=>{S()},onKeyDown:M,className:O("w-full bg-transparent rounded outline-none resize-none overflow-hidden",Sg,r)});const B=t&&o?"div":s;return e.jsx(B,{className:O("cursor-pointer rounded hover:bg-accent/50 transition-colors overflow-hidden",Sg,!t&&"text-muted-foreground italic",r),onClick:()=>d(!0),children:t||a})}const ZF=[{value:"backlog",label:"Backlog"},{value:"planned",label:"Planned"},{value:"in_progress",label:"In Progress"},{value:"completed",label:"Completed"},{value:"cancelled",label:"Cancelled"}];function aa({state:t}){return t==="saving"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(kn,{className:"h-3 w-3 animate-spin"}),"Saving"]}):t==="saved"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-green-600 dark:text-green-400",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Saved"]}):t==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-destructive",children:[e.jsx(_d,{className:"h-3 w-3"}),"Failed"]}):null}function Ra({label:t,state:n}){return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t}),e.jsx(aa,{state:n})]})}function Xr({label:t,children:n,alignStart:s=!1,valueClassName:r=""}){return e.jsxs("div",{className:O("flex gap-3 py-1.5",s?"items-start":"items-center"),children:[e.jsx("div",{className:"shrink-0 w-20",children:t}),e.jsx("div",{className:O("min-w-0 flex-1",s?"pt-0.5":"flex items-center gap-1.5",r),children:n})]})}function YF({status:t,onChange:n}){const[s,r]=c.useState(!1),a=$0[t]??D0;return e.jsxs(Ht,{open:s,onOpenChange:r,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:O("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0 cursor-pointer hover:opacity-80 transition-opacity",a),children:t.replace("_"," ")})}),e.jsx(Qt,{className:"w-40 p-1",align:"start",children:ZF.map(o=>e.jsx(G,{variant:"ghost",size:"sm",className:O("w-full justify-start gap-2 text-xs",o.value===t&&"bg-accent"),onClick:()=>{n(o.value),r(!1)},children:o.label},o.value))})]})}function XF({project:t,onArchive:n,archivePending:s}){const[r,a]=c.useState(!1),o=!t.archivedAt,i=o?"Archive":"Unarchive";return e.jsxs("div",{className:"space-y-3 rounded-md border border-destructive/40 bg-destructive/5 px-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"Archive this project to hide it from the sidebar and project selectors.":"Unarchive this project to restore it in the sidebar and project selectors."}),s?e.jsxs(G,{size:"sm",variant:"destructive",disabled:!0,children:[e.jsx(kn,{className:"h-3 w-3 animate-spin mr-1"}),o?"Archiving...":"Unarchiving..."]}):r?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm text-destructive font-medium",children:[i," “",t.name,"”?"]}),e.jsx(G,{size:"sm",variant:"destructive",onClick:()=>{a(!1),n(o)},children:"Confirm"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>a(!1),children:"Cancel"})]}):e.jsx(G,{size:"sm",variant:"destructive",onClick:()=>a(!0),children:o?e.jsxs(e.Fragment,{children:[e.jsx(ty,{className:"h-3 w-3 mr-1"}),i," project"]}):e.jsxs(e.Fragment,{children:[e.jsx(C1,{className:"h-3 w-3 mr-1"}),i," project"]})})]})}function eq({project:t,onUpdate:n,onFieldUpdate:s,getFieldSaveState:r,onArchive:a,archivePending:o}){var Le;const{selectedCompanyId:i}=et(),l=at(),[u,d]=c.useState(!1),[m,p]=c.useState(!1),[x,f]=c.useState(null),[h,j]=c.useState(""),[b,g]=c.useState(""),[y,v]=c.useState(null),_=(q,D)=>{if(s){s(q,D);return}n==null||n(D)},E=q=>(r==null?void 0:r(q))??"idle",{data:S}=oe({queryKey:N.goals.list(i),queryFn:()=>Zs.list(i),enabled:!!i}),{data:M}=oe({queryKey:N.instance.experimentalSettings,queryFn:()=>Rr.getExperimental()}),B=t.goalIds.length>0?t.goalIds:t.goalId?[t.goalId]:[],k=t.goals.length>0?t.goals:B.map(q=>{var D;return{id:q,title:((D=S==null?void 0:S.find(ie=>ie.id===q))==null?void 0:D.title)??q.slice(0,8)}}),L=(S??[]).filter(q=>!B.includes(q.id)),$=t.workspaces??[],C=t.codebase,I=t.primaryWorkspace??null,K=$.some(q=>q.id!==(I==null?void 0:I.id)),T=t.executionWorkspacePolicy??null,z=(T==null?void 0:T.enabled)===!0,w=(M==null?void 0:M.enableIsolatedWorkspaces)===!0,F=(T==null?void 0:T.defaultMode)==="isolated_workspace"?"isolated_workspace":"shared_workspace",A=(T==null?void 0:T.workspaceStrategy)??{type:"git_worktree",baseRef:"",branchTemplate:"",worktreeParentDir:""},R=()=>{l.invalidateQueries({queryKey:N.projects.detail(t.id)}),t.urlKey!==t.id&&l.invalidateQueries({queryKey:N.projects.detail(t.urlKey)}),i&&l.invalidateQueries({queryKey:N.projects.list(i)})},Q=ge({mutationFn:q=>en.createWorkspace(t.id,q),onSuccess:()=>{j(""),g(""),f(null),v(null),R()}}),H=ge({mutationFn:q=>en.removeWorkspace(t.id,q),onSuccess:()=>{j(""),g(""),f(null),v(null),R()}}),U=ge({mutationFn:({workspaceId:q,data:D})=>en.updateWorkspace(t.id,q,D),onSuccess:()=>{j(""),g(""),f(null),v(null),R()}}),Z=q=>{!n&&!s||_("goals",{goalIds:B.filter(D=>D!==q)})},V=q=>{!n&&!s||B.includes(q)||(_("goals",{goalIds:[...B,q]}),d(!1))},W=q=>{if(!(!n&&!s))return{executionWorkspacePolicy:{enabled:z,defaultMode:F,allowIssueOverride:(T==null?void 0:T.allowIssueOverride)??!0,...T,...q}}},J=q=>q.startsWith("/")||/^[A-Za-z]:[\\/]/.test(q),Y=q=>{try{const D=new URL(q),ie=D.hostname.toLowerCase();return ie!=="github.com"&&ie!=="www.github.com"?!1:D.pathname.split("/").filter(Boolean).length>=2}catch{return!1}},de=q=>{if(!q)return!1;try{const D=new URL(q);return D.protocol==="http:"||D.protocol==="https:"}catch{return!1}},fe=q=>{var D;try{const ie=new URL(q),Ie=ie.pathname.split("/").filter(Boolean);if(Ie.length<2)return ie.host;const ue=Ie[0],Be=(D=Ie[1])==null?void 0:D.replace(/\.git$/i,"");return!ue||!Be?ie.host:`${ie.host}/${ue}/${Be}`}catch{return q}},Ce=(q,D)=>{if(D)return"git_repo";if(q)return"local_path"},le=q=>{const D=q.cwd!==void 0?q.cwd:C.localFolder,ie=q.repoUrl!==void 0?q.repoUrl:C.repoUrl;if(!D&&!ie){I&&H.mutate(I.id);return}const Ie={...q.cwd!==void 0?{cwd:q.cwd}:{},...q.repoUrl!==void 0?{repoUrl:q.repoUrl}:{},...Ce(D,ie)?{sourceType:Ce(D,ie)}:{},isPrimary:!0};if(I){U.mutate({workspaceId:I.id,data:Ie});return}Q.mutate(Ie)},Re=()=>{const q=h.trim();if(!q){v(null),le({cwd:null});return}if(!J(q)){v("Local folder must be a full absolute path.");return}v(null),le({cwd:q})},Pe=()=>{const q=b.trim();if(!q){v(null),le({repoUrl:null});return}if(!Y(q)){v("Repo must use a valid GitHub repo URL.");return}v(null),le({repoUrl:q})},Fe=()=>{window.confirm(C.repoUrl?"Clear local folder from this workspace?":"Delete this workspace local folder?")&&le({cwd:null})},pe=()=>{const q=!!C.localFolder;if(window.confirm(q?"Clear repo from this workspace?":"Delete this workspace repo?")){if(I&&q){U.mutate({workspaceId:I.id,data:{repoUrl:null,repoRef:null,defaultRef:null,sourceType:Ce(C.localFolder,null)}});return}le({repoUrl:null})}};return e.jsxs("div",{children:[e.jsxs("div",{className:"space-y-1 pb-4",children:[e.jsx(Xr,{label:e.jsx(Ra,{label:"Name",state:E("name")}),children:n||s?e.jsx(nn,{value:t.name,onCommit:q=>_("name",{name:q}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-sm outline-none",placeholder:"Project name"}):e.jsx("span",{className:"text-sm",children:t.name})}),e.jsx(Xr,{label:e.jsx(Ra,{label:"Description",state:E("description")}),alignStart:!0,valueClassName:"space-y-0.5",children:n||s?e.jsx(kr,{value:t.description??"",onSave:q=>_("description",{description:q}),as:"p",className:"text-sm text-muted-foreground",placeholder:"Add a description...",multiline:!0}):e.jsx("p",{className:"text-sm text-muted-foreground",children:((Le=t.description)==null?void 0:Le.trim())||"No description"})}),e.jsx(Xr,{label:e.jsx(Ra,{label:"Status",state:E("status")}),children:n||s?e.jsx(YF,{status:t.status,onChange:q=>_("status",{status:q})}):e.jsx(Dt,{status:t.status})}),t.leadAgentId&&e.jsx(Xr,{label:"Lead",children:e.jsx("span",{className:"text-sm font-mono",children:t.leadAgentId.slice(0,8)})}),e.jsxs(Xr,{label:e.jsx(Ra,{label:"Goals",state:E("goals")}),alignStart:!0,valueClassName:"space-y-2",children:[k.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:k.map(q=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-xs",children:[e.jsx(Oe,{to:`/goals/${q.id}`,className:"hover:underline max-w-[220px] truncate",children:q.title}),(n||s)&&e.jsx("button",{className:"text-muted-foreground hover:text-foreground",type:"button",onClick:()=>Z(q.id),"aria-label":`Remove goal ${q.title}`,children:e.jsx(zt,{className:"h-3 w-3"})})]},q.id))}),(n||s)&&e.jsxs(Ht,{open:u,onOpenChange:d,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"xs",className:O("h-6 w-fit px-2",k.length>0&&"ml-1"),disabled:L.length===0,children:[e.jsx(Ot,{className:"h-3 w-3 mr-1"}),"Goal"]})}),e.jsx(Qt,{className:"w-56 p-1",align:"start",children:L.length===0?e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All goals linked."}):L.map(q=>e.jsx("button",{className:"flex items-center w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",onClick:()=>V(q.id),children:q.title},q.id))})]})]}),e.jsx(Xr,{label:e.jsx(Ra,{label:"Created",state:"idle"}),children:e.jsx("span",{className:"text-sm",children:xs(t.createdAt)})}),e.jsx(Xr,{label:e.jsx(Ra,{label:"Updated",state:"idle"}),children:e.jsx("span",{className:"text-sm",children:xs(t.updatedAt)})}),t.targetDate&&e.jsx(Xr,{label:e.jsx(Ra,{label:"Target Date",state:"idle"}),children:e.jsx("span",{className:"text-sm",children:xs(t.targetDate)})})]}),e.jsx(yn,{className:"my-4"}),e.jsxs("div",{className:"space-y-1 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Codebase"}),e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-border text-[10px] text-muted-foreground hover:text-foreground","aria-label":"Codebase help",children:"?"})}),e.jsx(Yn,{side:"top",children:"Repo identifies the source of truth. Local folder is the default place agents write code."})]})]}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border/70 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Repo"}),C.repoUrl?e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[de(C.repoUrl)?e.jsxs("a",{href:C.repoUrl,target:"_blank",rel:"noreferrer",className:"inline-flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground hover:underline",children:[e.jsx(Sc,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:fe(C.repoUrl)}),e.jsx(Is,{className:"h-3 w-3 shrink-0"})]}):e.jsxs("div",{className:"inline-flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Sc,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:C.repoUrl})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"xs",className:"h-6 px-2",onClick:()=>{f("repo"),g(C.repoUrl??""),v(null)},children:"Change repo"}),e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:pe,"aria-label":"Clear repo",children:e.jsx(Ls,{className:"h-3 w-3"})})]})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Not set."}),e.jsx(G,{variant:"outline",size:"xs",className:"h-6 px-2",onClick:()=>{f("repo"),g(C.repoUrl??""),v(null)},children:"Set repo"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Local folder"}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("div",{className:"min-w-0 truncate font-mono text-xs text-muted-foreground",children:C.effectiveLocalFolder}),C.origin==="managed_checkout"&&e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"CrewSpace-managed folder."})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"xs",className:"h-6 px-2",onClick:()=>{f("local"),j(C.localFolder??""),v(null)},children:C.localFolder?"Change local folder":"Set local folder"}),C.localFolder?e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:Fe,"aria-label":"Clear local folder",children:e.jsx(Ls,{className:"h-3 w-3"})}):null]})]})]}),K&&e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Additional legacy workspace records exist on this project. CrewSpace is using the primary workspace as the codebase view."}),I!=null&&I.runtimeServices&&I.runtimeServices.length>0?e.jsx("div",{className:"space-y-1",children:I.runtimeServices.map(q=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border border-border/60 px-2 py-1",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium",children:q.serviceName}),e.jsx("span",{className:O("rounded-full px-1.5 py-0.5 text-[10px] uppercase tracking-wide",q.status==="running"?"bg-green-500/15 text-green-700 dark:text-green-300":q.status==="failed"?"bg-red-500/15 text-red-700 dark:text-red-300":"bg-muted text-muted-foreground"),children:q.status})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:q.url?e.jsx("a",{href:q.url,target:"_blank",rel:"noreferrer",className:"hover:text-foreground hover:underline",children:q.url}):q.command??"No URL"})]}),e.jsx("div",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:q.lifecycle})]},q.id))}):null]}),x==="local"&&e.jsxs("div",{className:"space-y-1.5 rounded-md border border-border p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",value:h,onChange:q=>j(q.target.value),placeholder:"/absolute/path/to/workspace"}),e.jsx(pr,{})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"outline",size:"xs",className:"h-6 px-2",disabled:!h.trim()&&!I||Q.isPending||U.isPending,onClick:Re,children:"Save"}),e.jsx(G,{variant:"ghost",size:"xs",className:"h-6 px-2",onClick:()=>{f(null),j(""),v(null)},children:"Cancel"})]})]}),x==="repo"&&e.jsxs("div",{className:"space-y-1.5 rounded-md border border-border p-2",children:[e.jsx("input",{className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs outline-none",value:b,onChange:q=>g(q.target.value),placeholder:"https://github.com/org/repo"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"outline",size:"xs",className:"h-6 px-2",disabled:!b.trim()&&!I||Q.isPending||U.isPending,onClick:Pe,children:"Save"}),e.jsx(G,{variant:"ghost",size:"xs",className:"h-6 px-2",onClick:()=>{f(null),g(""),v(null)},children:"Cancel"})]})]}),y&&e.jsx("p",{className:"text-xs text-destructive",children:y}),Q.isError&&e.jsx("p",{className:"text-xs text-destructive",children:"Failed to save workspace."}),H.isError&&e.jsx("p",{className:"text-xs text-destructive",children:"Failed to delete workspace."}),U.isError&&e.jsx("p",{className:"text-xs text-destructive",children:"Failed to update workspace."})]}),w?e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"my-4"}),e.jsxs("div",{className:"py-1.5 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Execution Workspaces"}),e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-border text-[10px] text-muted-foreground hover:text-foreground","aria-label":"Execution workspaces help",children:"?"})}),e.jsx(Yn,{side:"top",children:"Project-owned defaults for isolated issue checkouts and execution workspace behavior."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx("span",{children:"Enable isolated issue checkouts"}),e.jsx(aa,{state:E("execution_workspace_enabled")})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Let issues choose between the project's primary checkout and an isolated execution workspace."})]}),n||s?e.jsx("button",{"data-slot":"toggle",className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors",z?"bg-green-600":"bg-muted"),type:"button",onClick:()=>_("execution_workspace_enabled",W({enabled:!z})),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",z?"translate-x-4.5":"translate-x-0.5")})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:z?"Enabled":"Disabled"})]}),z?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{children:"New issues default to isolated checkout"}),e.jsx(aa,{state:E("execution_workspace_default_mode")})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"If disabled, new issues stay on the project's primary checkout unless someone opts in."})]}),e.jsx("button",{"data-slot":"toggle",className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors",F==="isolated_workspace"?"bg-green-600":"bg-muted"),type:"button",onClick:()=>_("execution_workspace_default_mode",W({defaultMode:F==="isolated_workspace"?"shared_workspace":"isolated_workspace"})),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",F==="isolated_workspace"?"translate-x-4.5":"translate-x-0.5")})})]}),e.jsx("div",{className:"border-t border-border/60 pt-2",children:e.jsx("button",{type:"button",className:"flex w-full items-center gap-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground",onClick:()=>p(q=>!q),children:m?"Hide advanced checkout settings":"Show advanced checkout settings"})}),m?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Host-managed implementation: ",e.jsx("span",{className:"text-foreground",children:"Git worktree"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Base ref"}),e.jsx(aa,{state:E("execution_workspace_base_ref")})]})}),e.jsx(nn,{value:A.baseRef??"",onCommit:q=>_("execution_workspace_base_ref",{...W({workspaceStrategy:{...A,type:"git_worktree",baseRef:q||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"origin/main"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Branch template"}),e.jsx(aa,{state:E("execution_workspace_branch_template")})]})}),e.jsx(nn,{value:A.branchTemplate??"",onCommit:q=>_("execution_workspace_branch_template",{...W({workspaceStrategy:{...A,type:"git_worktree",branchTemplate:q||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"{{issue.identifier}}-{{slug}}"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Worktree parent dir"}),e.jsx(aa,{state:E("execution_workspace_worktree_parent_dir")})]})}),e.jsx(nn,{value:A.worktreeParentDir??"",onCommit:q=>_("execution_workspace_worktree_parent_dir",{...W({workspaceStrategy:{...A,type:"git_worktree",worktreeParentDir:q||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:".crewspace/worktrees"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Provision command"}),e.jsx(aa,{state:E("execution_workspace_provision_command")})]})}),e.jsx(nn,{value:A.provisionCommand??"",onCommit:q=>_("execution_workspace_provision_command",{...W({workspaceStrategy:{...A,type:"git_worktree",provisionCommand:q||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"bash ./scripts/provision-worktree.sh"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Teardown command"}),e.jsx(aa,{state:E("execution_workspace_teardown_command")})]})}),e.jsx(nn,{value:A.teardownCommand??"",onCommit:q=>_("execution_workspace_teardown_command",{...W({workspaceStrategy:{...A,type:"git_worktree",teardownCommand:q||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"bash ./scripts/teardown-worktree.sh"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Provision runs inside the derived worktree before agent execution. Teardown is stored here for future cleanup flows."})]}):null]}):null]})]})]}):null]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"my-4"}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"text-xs font-medium text-destructive uppercase tracking-wide",children:"Danger Zone"}),e.jsx(XF,{project:t,onArchive:a,archivePending:o})]})]})]})}function tq(t){return t==="blocked"?"border-destructive/30 bg-destructive/5 text-destructive":t==="ready_with_warnings"?"border-amber-500/30 bg-amber-500/10 text-amber-800 dark:text-amber-300":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"}function oN({workspaceId:t,workspaceName:n,currentStatus:s,open:r,onOpenChange:a,onClosed:o}){var j,b;const i=at(),{pushToast:l}=ds(),u=s==="cleanup_failed"?"Retry close":"Close workspace",d=oe({queryKey:N.executionWorkspaces.closeReadiness(t),queryFn:()=>or.getCloseReadiness(t),enabled:r}),m=ge({mutationFn:()=>or.update(t,{status:"archived"}),onSuccess:g=>{i.setQueryData(N.executionWorkspaces.detail(g.id),g),i.invalidateQueries({queryKey:N.executionWorkspaces.closeReadiness(g.id)}),l({title:s==="cleanup_failed"?"Workspace close retried":"Workspace closed",tone:"success"}),a(!1),o==null||o(g)},onError:g=>{l({title:"Failed to close workspace",body:g instanceof Error?g.message:"Unknown error",tone:"error"})}}),p=d.data??null,x=(p==null?void 0:p.linkedIssues.filter(g=>!g.isTerminal))??[],f=(p==null?void 0:p.linkedIssues.filter(g=>g.isTerminal))??[],h=s==="archived"||m.isPending||d.isLoading||p==null||p.state==="blocked";return e.jsx(Cs,{open:r,onOpenChange:g=>{m.isPending||a(g)},children:e.jsxs(Fs,{className:"max-h-[85vh] overflow-y-auto sm:max-w-2xl",children:[e.jsxs(fa,{children:[e.jsx(ha,{children:u}),e.jsxs(ga,{className:"break-words",children:["Archive ",e.jsx("span",{className:"font-medium text-foreground",children:n})," and clean up any owned workspace artifacts. CrewSpace keeps the workspace record and issue history, but removes it from active workspace views."]})]}),d.isLoading?e.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-border bg-muted/30 px-4 py-3 text-sm text-muted-foreground",children:[e.jsx(kn,{className:"h-4 w-4 animate-spin"}),"Checking whether this workspace is safe to close..."]}):d.error?e.jsx("div",{className:"rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to inspect workspace close readiness."}):p?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:`rounded-xl border px-4 py-3 text-sm ${tq(p.state)}`,children:[e.jsx("div",{className:"font-medium",children:p.state==="blocked"?"Close is blocked":p.state==="ready_with_warnings"?"Close is allowed with warnings":"Close is ready"}),e.jsx("div",{className:"mt-1 text-xs opacity-80",children:p.isSharedWorkspace?"This is a shared workspace session. Archiving it removes this session record but keeps the underlying project workspace.":(j=p.git)!=null&&j.workspacePath&&p.git.repoRoot&&p.git.workspacePath!==p.git.repoRoot?"This execution workspace has its own checkout path and can be archived independently.":p.isProjectPrimaryWorkspace?"This execution workspace currently points at the project's primary workspace path.":"This workspace is disposable and can be archived."})]}),x.length>0?e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Blocking issues"}),e.jsx("div",{className:"space-y-2",children:x.map(g=>e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-4 py-3 text-sm",children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsxs(Oe,{to:Bc(g),className:"min-w-0 break-words font-medium hover:underline",children:[g.identifier??g.id," · ",g.title]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.status})]})},g.id))})]}):null,p.blockingReasons.length>0?e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Blocking reasons"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:p.blockingReasons.map((g,y)=>e.jsx("li",{className:"break-words rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-destructive",children:g},`blocking-${y}`))})]}):null,p.warnings.length>0?e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Warnings"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:p.warnings.map((g,y)=>e.jsx("li",{className:"break-words rounded-lg border border-amber-500/20 bg-amber-500/5 px-3 py-2",children:g},`warning-${y}`))})]}):null,p.git?e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Git status"}),e.jsx("div",{className:"rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm",children:e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-muted-foreground",children:"Branch"}),e.jsx("div",{className:"font-mono text-xs",children:p.git.branchName??"Unknown"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-muted-foreground",children:"Base ref"}),e.jsx("div",{className:"font-mono text-xs",children:p.git.baseRef??"Not set"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-muted-foreground",children:"Merged into base"}),e.jsx("div",{children:p.git.isMergedIntoBase==null?"Unknown":p.git.isMergedIntoBase?"Yes":"No"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-muted-foreground",children:"Ahead / behind"}),e.jsxs("div",{children:[(p.git.aheadCount??0).toString()," / ",(p.git.behindCount??0).toString()]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-muted-foreground",children:"Dirty tracked files"}),e.jsx("div",{children:p.git.dirtyEntryCount})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-muted-foreground",children:"Untracked files"}),e.jsx("div",{children:p.git.untrackedEntryCount})]})]})})]}):null,f.length>0?e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Other linked issues"}),e.jsx("div",{className:"space-y-2",children:f.map(g=>e.jsx("div",{className:"rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm",children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsxs(Oe,{to:Bc(g),className:"min-w-0 break-words font-medium hover:underline",children:[g.identifier??g.id," · ",g.title]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.status})]})},g.id))})]}):null,p.runtimeServices.length>0?e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Attached runtime services"}),e.jsx("div",{className:"space-y-2",children:p.runtimeServices.map(g=>e.jsxs("div",{className:"rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:g.serviceName}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[g.status," · ",g.lifecycle]})]}),e.jsx("div",{className:"mt-1 break-words text-xs text-muted-foreground",children:g.url??g.command??g.cwd??"No additional details"})]},g.id))})]}):null,e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Cleanup actions"}),e.jsx("div",{className:"space-y-2",children:p.plannedActions.map((g,y)=>e.jsxs("div",{className:"rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:g.label}),e.jsx("div",{className:"mt-1 break-words text-muted-foreground",children:g.description}),g.command?e.jsx("pre",{className:"mt-2 whitespace-pre-wrap break-all rounded-lg bg-background px-3 py-2 font-mono text-xs text-foreground",children:g.command}):null]},`${g.kind}-${y}`))})]}),s==="cleanup_failed"?e.jsx("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/5 px-4 py-3 text-sm text-muted-foreground",children:"Cleanup previously failed on this workspace. Retrying close will rerun the cleanup flow and update the workspace status if it succeeds."}):null,s==="archived"?e.jsx("div",{className:"rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm text-muted-foreground",children:"This workspace is already archived."}):null,(b=p.git)!=null&&b.repoRoot?e.jsxs("div",{className:"break-words text-xs text-muted-foreground",children:["Repo root: ",e.jsx("span",{className:"font-mono break-all",children:p.git.repoRoot}),p.git.workspacePath?e.jsxs(e.Fragment,{children:[" · ","Workspace path: ",e.jsx("span",{className:"font-mono break-all",children:p.git.workspacePath})]}):null]}):null,e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Last checked ",js(new Date)]})]}):null,e.jsxs(Ho,{children:[e.jsx(G,{variant:"outline",onClick:()=>a(!1),disabled:m.isPending,children:"Cancel"}),e.jsxs(G,{variant:s==="cleanup_failed"?"default":"destructive",onClick:()=>m.mutate(),disabled:h,children:[m.isPending?e.jsx(kn,{className:"mr-2 h-4 w-4 animate-spin"}):null,u]})]})]})})}function sm(t,n){const s={};for(const r of t){const a=n(r);s[a]||(s[a]=[]),s[a].push(r)}return s}const rm={critical:{icon:ir,color:ua.critical,label:"Critical"},high:{icon:Qb,color:ua.high,label:"High"},medium:{icon:Ep,color:ua.medium,label:"Medium"},low:{icon:Tp,color:ua.low,label:"Low"}},nq=["critical","high","medium","low"];function vs({priority:t,onChange:n,className:s,showLabel:r}){const[a,o]=c.useState(!1),i=rm[t]??rm.medium,l=i.icon,u=e.jsx("span",{className:O("inline-flex items-center justify-center shrink-0",i.color,n&&!r&&"cursor-pointer",s),children:e.jsx(l,{className:"h-3.5 w-3.5"})});if(!n)return r?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[u,e.jsx("span",{className:"text-sm",children:i.label})]}):u;const d=r?e.jsxs("button",{className:"inline-flex items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",children:[u,e.jsx("span",{className:"text-sm",children:i.label})]}):u;return e.jsxs(Ht,{open:a,onOpenChange:o,children:[e.jsx(Vt,{asChild:!0,children:d}),e.jsx(Qt,{className:"w-36 p-1",align:"start",children:nq.map(m=>{const p=rm[m],x=p.icon;return e.jsxs(G,{variant:"ghost",size:"sm",className:O("w-full justify-start gap-2 text-xs",m===t&&"bg-accent"),onClick:()=>{n(m),o(!1)},children:[e.jsx(x,{className:O("h-3.5 w-3.5",p.color)}),p.label]},m)})})]})}const iN="from";function sq(t){if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.label=="string"&&typeof n.href=="string"}function lN(t){return t==="issues"||t==="inbox"}function rq(t){if(typeof t!="object"||t===null)return null;const n=t.issueDetailSource;return lN(n)?n:null}function cN(t){if(!t)return null;const s=new URLSearchParams(t).get(iN);return lN(s)?s:null}function aq(t){return t==="inbox"?{label:"Inbox",href:"/inbox"}:{label:"Issues",href:"/issues"}}function dN(t,n,s){return{issueDetailBreadcrumb:{label:t,href:n},issueDetailSource:s}}function Gi(t,n,s){const r=rq(n)??cN(s);if(!r)return`/issues/${t}`;const a=new URLSearchParams;return a.set(iN,r),`/issues/${t}?${a.toString()}`}function oq(t,n){if(typeof t=="object"&&t!==null){const r=t.issueDetailBreadcrumb;if(sq(r))return r}const s=cN(n);return s?aq(s):null}function uN({issue:t,issueLinkState:n,selected:s=!1,mobileLeading:r,desktopMetaLeading:a,desktopLeadingSpacer:o=!1,mobileMeta:i,desktopTrailing:l,trailingMeta:u,unreadState:d=null,onMarkRead:m,onArchive:p,archiveDisabled:x,className:f}){const h=t.identifier??t.id,j=t.identifier??t.id.slice(0,8),b=d!==null,g=d==="visible"||d==="fading",y=s?"!text-muted-foreground !border-muted-foreground":void 0;return e.jsxs(Oe,{to:Gi(h,n),state:n,"data-inbox-issue-link":!0,className:O("group flex items-start gap-2 border-b border-border py-2.5 pl-2 pr-3 text-sm no-underline text-inherit transition-colors last:border-b-0 sm:items-center sm:py-2 sm:pl-1",s?"hover:bg-transparent":"hover:bg-accent/50",f),children:[e.jsx("span",{className:"shrink-0 pt-px sm:hidden",children:r??e.jsx(Pn,{status:t.status,className:y})}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-1 sm:contents",children:[e.jsx("span",{className:"line-clamp-2 text-sm sm:order-2 sm:min-w-0 sm:flex-1 sm:truncate sm:line-clamp-none",children:t.title}),e.jsxs("span",{className:"flex items-center gap-2 sm:order-1 sm:shrink-0",children:[o?e.jsx("span",{className:"hidden w-3.5 shrink-0 sm:block"}):null,a??e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden shrink-0 sm:inline-flex",children:e.jsx(Pn,{status:t.status,className:y})}),e.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:j})]}),i?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs text-muted-foreground sm:hidden","aria-hidden":"true",children:"·"}),e.jsx("span",{className:"text-xs text-muted-foreground sm:hidden",children:i})]}):null]})]}),l||u?e.jsxs("span",{className:"ml-auto hidden shrink-0 items-center gap-2 sm:order-3 sm:flex sm:gap-3",children:[l,u?e.jsx("span",{className:"text-xs text-muted-foreground",children:u}):null]}):null,b?e.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:g?e.jsx("button",{type:"button",onClick:v=>{v.preventDefault(),v.stopPropagation(),m==null||m()},onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),v.stopPropagation(),m==null||m())},className:O("inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors",s?"hover:bg-muted/80":"hover:bg-blue-500/20"),"aria-label":"Mark as read",children:e.jsx("span",{className:O("block h-2 w-2 rounded-full transition-opacity duration-300",s?"bg-muted-foreground/70":"bg-blue-600 dark:bg-blue-400",d==="fading"?"opacity-0":"opacity-100")})}):p?e.jsx("button",{type:"button",onClick:v=>{v.preventDefault(),v.stopPropagation(),p()},onKeyDown:v=>{v.key!=="Enter"&&v.key!==" "||(v.preventDefault(),v.stopPropagation(),p())},disabled:x,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:e.jsx(zt,{className:"h-3.5 w-3.5"})}):e.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null]})}function Gs({className:t,...n}){return e.jsx(wy,{"data-slot":"checkbox",className:O("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...n,children:e.jsx(ky,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:e.jsx(Nn,{className:"size-3.5"})})})}const am=["backlog","todo","in_progress","in_review","blocked","done","cancelled"];function iq(t){return t.replace(/_/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function lq({status:t,issues:n,agents:s,liveIssueIds:r}){const{setNodeRef:a,isOver:o}=Rj({id:t});return e.jsxs("div",{className:"flex flex-col min-w-[260px] w-[260px] shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2 py-2 mb-1",children:[e.jsx(Pn,{status:t}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:iq(t)}),e.jsx("span",{className:"text-xs text-muted-foreground/60 ml-auto tabular-nums",children:n.length})]}),e.jsx("div",{ref:a,className:`flex-1 min-h-[120px] rounded-md p-1 space-y-1 transition-colors ${o?"bg-accent/40":"bg-muted/20"}`,children:e.jsx(Ix,{items:n.map(i=>i.id),strategy:Sx,children:n.map(i=>e.jsx(mN,{issue:i,agents:s,isLive:r==null?void 0:r.has(i.id)},i.id))})})]})}function mN({issue:t,agents:n,isLive:s,isOverlay:r}){const{attributes:a,listeners:o,setNodeRef:i,transform:l,transition:u,isDragging:d}=_x({id:t.id,data:{issue:t}}),m={transform:Er.Transform.toString(l),transition:u},p=x=>{var f;return!x||!n?null:((f=n.find(h=>h.id===x))==null?void 0:f.name)??null};return e.jsx("div",{ref:i,style:m,...a,...o,className:`rounded-md border bg-card p-2.5 cursor-grab active:cursor-grabbing transition-shadow ${d&&!r?"opacity-30":""} ${r?"shadow-lg ring-1 ring-primary/20":"hover:shadow-sm"}`,children:e.jsxs(Oe,{to:`/issues/${t.identifier??t.id}`,className:"block no-underline text-inherit",onClick:x=>{d&&x.preventDefault()},children:[e.jsxs("div",{className:"flex items-start gap-1.5 mb-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-mono shrink-0",children:t.identifier??t.id.slice(0,8)}),s&&e.jsxs("span",{className:"relative flex h-2 w-2 shrink-0 mt-0.5",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]})]}),e.jsx("p",{className:"text-sm leading-snug line-clamp-2 mb-2",children:t.title}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{priority:t.priority}),t.assigneeAgentId&&(()=>{const x=p(t.assigneeAgentId);return x?e.jsx(Ut,{name:x,size:"xs"}):e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:t.assigneeAgentId.slice(0,8)})})()]})]})})}function cq({issues:t,agents:n,liveIssueIds:s,onUpdateIssue:r}){const[a,o]=c.useState(null),i=bx(gx(wx,{activationConstraint:{distance:5}})),l=c.useMemo(()=>{const x={};for(const f of am)x[f]=[];for(const f of t)x[f.status]&&x[f.status].push(f);return x},[t]),u=c.useMemo(()=>a?t.find(x=>x.id===a):null,[a,t]);function d(x){o(x.active.id)}function m(x){o(null);const{active:f,over:h}=x;if(!h)return;const j=f.id,b=t.find(y=>y.id===j);if(!b)return;let g=null;if(am.includes(h.id))g=h.id;else{const y=t.find(v=>v.id===h.id);y&&(g=y.status)}g&&g!==b.status&&r(j,{status:g})}function p(x){}return e.jsxs(Cx,{sensors:i,onDragStart:d,onDragOver:p,onDragEnd:m,children:[e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-4 -mx-2 px-2",children:am.map(x=>e.jsx(lq,{status:x,issues:l[x]??[],agents:n,liveIssueIds:s},x))}),e.jsx(NE,{children:u?e.jsx(mN,{issue:u,agents:n,isOverlay:!0}):null})]})}const dd=["in_progress","todo","backlog","in_review","blocked","done","cancelled"],ud=["critical","high","medium","low"];function ac(t){return t.replace(/_/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const md={statuses:[],priorities:[],assignees:[],labels:[],projects:[],sortField:"updated",sortDir:"desc",groupBy:"none",viewMode:"list",collapsedGroups:[]},dq=[{label:"All",statuses:[]},{label:"Active",statuses:["todo","in_progress","in_review","blocked"]},{label:"Backlog",statuses:["backlog"]},{label:"Done",statuses:["done","cancelled"]}],uq=150;function Ig(t){try{const n=localStorage.getItem(t);if(n)return{...md,...JSON.parse(n)}}catch{}return{...md}}function mq(t,n){localStorage.setItem(t,JSON.stringify(n))}function pq(t,n){if(t.length!==n.length)return!1;const s=[...t].sort(),r=[...n].sort();return s.every((a,o)=>a===r[o])}function Pa(t,n){return t.includes(n)?t.filter(s=>s!==n):[...t,n]}function xq(t,n,s){let r=t;return n.statuses.length>0&&(r=r.filter(a=>n.statuses.includes(a.status))),n.priorities.length>0&&(r=r.filter(a=>n.priorities.includes(a.priority))),n.assignees.length>0&&(r=r.filter(a=>{for(const o of n.assignees)if(o==="__unassigned"&&!a.assigneeAgentId&&!a.assigneeUserId||o==="__me"&&s&&a.assigneeUserId===s||a.assigneeAgentId===o)return!0;return!1})),n.labels.length>0&&(r=r.filter(a=>(a.labelIds??[]).some(o=>n.labels.includes(o)))),n.projects.length>0&&(r=r.filter(a=>a.projectId!=null&&n.projects.includes(a.projectId))),r}function fq(t,n){const s=[...t],r=n.sortDir==="asc"?1:-1;return s.sort((a,o)=>{switch(n.sortField){case"status":return r*(dd.indexOf(a.status)-dd.indexOf(o.status));case"priority":return r*(ud.indexOf(a.priority)-ud.indexOf(o.priority));case"title":return r*a.title.localeCompare(o.title);case"created":return r*(new Date(a.createdAt).getTime()-new Date(o.createdAt).getTime());case"updated":return r*(new Date(a.updatedAt).getTime()-new Date(o.updatedAt).getTime());default:return 0}}),s}function hq(t){let n=0;return t.statuses.length>0&&n++,t.priorities.length>0&&n++,t.assignees.length>0&&n++,t.labels.length>0&&n++,t.projects.length>0&&n++,n}function gq({initialValue:t,onValueCommitted:n}){const[s,r]=c.useState(t),a=c.useRef(n);return c.useEffect(()=>{r(t)},[t]),c.useEffect(()=>{a.current=n},[n]),c.useEffect(()=>{const o=window.setTimeout(()=>{a.current(s)},uq);return()=>window.clearTimeout(o)},[s]),e.jsxs("div",{className:"relative w-48 sm:w-64 md:w-80",children:[e.jsx(ws,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(Xt,{value:s,onChange:o=>r(o.target.value),placeholder:"Search issues...",className:"pl-7 text-xs sm:text-sm","aria-label":"Search issues"})]})}function pN({issues:t,isLoading:n,error:s,agents:r,projects:a,liveIssueIds:o,projectId:i,viewStateKey:l,issueLinkState:u,initialAssignees:d,initialSearch:m,searchFilters:p,onSearchChange:x,onUpdateIssue:f}){var U,Z;const{selectedCompanyId:h}=et(),{openNewIssue:j}=In(),{data:b}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),g=((U=b==null?void 0:b.user)==null?void 0:U.id)??((Z=b==null?void 0:b.session)==null?void 0:Z.userId)??null,y=h?`${l}:${h}`:l,[v,_]=c.useState(()=>d?{...md,assignees:d,statuses:[]}:Ig(y)),[E,S]=c.useState(null),[M,B]=c.useState(""),[k,L]=c.useState(m??""),$=k.trim();c.useEffect(()=>{L(m??"")},[m]);const C=c.useRef(y);c.useEffect(()=>{C.current!==y&&(C.current=y,_(d?{...md,assignees:d,statuses:[]}:Ig(y)))},[y,d]);const I=c.useCallback(V=>{c.startTransition(()=>{L(V)}),x==null||x(V)},[x]),K=c.useCallback(V=>{_(W=>{const J={...W,...V};return mq(y,J),J})},[y]),{data:T=[]}=oe({queryKey:[...N.issues.search(h,$,i),p??{}],queryFn:()=>nt.list(h,{q:$,projectId:i,...p}),enabled:!!h&&$.length>0,placeholderData:V=>V}),z=c.useCallback(V=>{var W;return!V||!r?null:((W=r.find(J=>J.id===V))==null?void 0:W.name)??null},[r]),w=c.useMemo(()=>{const V=$.length>0?T:t,W=xq(V,v,g);return fq(W,v)},[t,T,v,$,g]),{data:F}=oe({queryKey:N.issues.labels(h),queryFn:()=>nt.listLabels(h),enabled:!!h}),A=hq(v),R=c.useMemo(()=>{if(v.groupBy==="none")return[{key:"__all",label:null,items:w}];if(v.groupBy==="status"){const W=sm(w,J=>J.status);return dd.filter(J=>{var Y;return(Y=W[J])==null?void 0:Y.length}).map(J=>({key:J,label:ac(J),items:W[J]}))}if(v.groupBy==="priority"){const W=sm(w,J=>J.priority);return ud.filter(J=>{var Y;return(Y=W[J])==null?void 0:Y.length}).map(J=>({key:J,label:ac(J),items:W[J]}))}const V=sm(w,W=>W.assigneeAgentId??(W.assigneeUserId?`__user:${W.assigneeUserId}`:"__unassigned"));return Object.keys(V).map(W=>({key:W,label:W==="__unassigned"?"Unassigned":W.startsWith("__user:")?Gm(W.slice(7),g)??"User":z(W)??W.slice(0,8),items:V[W]}))},[w,v.groupBy,r,z,g]),Q=V=>{const W={};return i&&(W.projectId=i),V&&(v.groupBy==="status"?W.status=V:v.groupBy==="priority"?W.priority=V:v.groupBy==="assignee"&&V!=="__unassigned"&&(V.startsWith("__user:")?W.assigneeUserId=V.slice(7):W.assigneeAgentId=V)),W},H=(V,W,J=null)=>{f(V,{assigneeAgentId:W,assigneeUserId:J}),S(null),B("")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 sm:gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 sm:gap-3",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>j(Q()),children:[e.jsx(Ot,{className:"h-4 w-4 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"New Issue"})]}),e.jsx(gq,{initialValue:m??"",onValueCommitted:I})]}),e.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1 shrink-0",children:[e.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden mr-1",children:[e.jsx("button",{className:`p-1.5 transition-colors ${v.viewMode==="list"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>K({viewMode:"list"}),title:"List view",children:e.jsx(Xb,{className:"h-3.5 w-3.5"})}),e.jsx("button",{className:`p-1.5 transition-colors ${v.viewMode==="board"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>K({viewMode:"board"}),title:"Board view",children:e.jsx(S1,{className:"h-3.5 w-3.5"})})]}),e.jsxs(Ht,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:`text-xs ${A>0?"text-blue-600 dark:text-blue-400":""}`,children:[e.jsx(I1,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:A>0?`Filters: ${A}`:"Filter"}),A>0&&e.jsx("span",{className:"sm:hidden text-[10px] font-medium ml-0.5",children:A}),A>0&&e.jsx(zt,{className:"h-3 w-3 ml-1 hidden sm:block",onClick:V=>{V.stopPropagation(),K({statuses:[],priorities:[],assignees:[],labels:[],projects:[]})}})]})}),e.jsx(Qt,{align:"end",className:"w-[min(480px,calc(100vw-2rem))] p-0",children:e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Filters"}),A>0&&e.jsx("button",{className:"text-xs text-muted-foreground hover:text-foreground",onClick:()=>K({statuses:[],priorities:[],assignees:[],labels:[]}),children:"Clear"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Quick filters"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:dq.map(V=>{const W=pq(v.statuses,V.statuses);return e.jsx("button",{className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${W?"bg-primary text-primary-foreground border-primary":"border-border text-muted-foreground hover:text-foreground hover:border-foreground/30"}`,onClick:()=>K({statuses:W?[]:[...V.statuses]}),children:V.label},V.label)})})]}),e.jsx("div",{className:"border-t border-border"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsx("div",{className:"space-y-0.5",children:dd.map(V=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[e.jsx(Gs,{checked:v.statuses.includes(V),onCheckedChange:()=>K({statuses:Pa(v.statuses,V)})}),e.jsx(Pn,{status:V}),e.jsx("span",{className:"text-sm",children:ac(V)})]},V))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Priority"}),e.jsx("div",{className:"space-y-0.5",children:ud.map(V=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[e.jsx(Gs,{checked:v.priorities.includes(V),onCheckedChange:()=>K({priorities:Pa(v.priorities,V)})}),e.jsx(vs,{priority:V}),e.jsx("span",{className:"text-sm",children:ac(V)})]},V))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Assignee"}),e.jsxs("div",{className:"space-y-0.5 max-h-32 overflow-y-auto",children:[e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[e.jsx(Gs,{checked:v.assignees.includes("__unassigned"),onCheckedChange:()=>K({assignees:Pa(v.assignees,"__unassigned")})}),e.jsx("span",{className:"text-sm",children:"No assignee"})]}),g&&e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[e.jsx(Gs,{checked:v.assignees.includes("__me"),onCheckedChange:()=>K({assignees:Pa(v.assignees,"__me")})}),e.jsx(Ns,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:"Me"})]}),(r??[]).map(V=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[e.jsx(Gs,{checked:v.assignees.includes(V.id),onCheckedChange:()=>K({assignees:Pa(v.assignees,V.id)})}),e.jsx("span",{className:"text-sm",children:V.name})]},V.id))]})]}),F&&F.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Labels"}),e.jsx("div",{className:"space-y-0.5 max-h-32 overflow-y-auto",children:F.map(V=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[e.jsx(Gs,{checked:v.labels.includes(V.id),onCheckedChange:()=>K({labels:Pa(v.labels,V.id)})}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:V.color}}),e.jsx("span",{className:"text-sm",children:V.name})]},V.id))})]}),a&&a.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Project"}),e.jsx("div",{className:"space-y-0.5 max-h-32 overflow-y-auto",children:a.map(V=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[e.jsx(Gs,{checked:v.projects.includes(V.id),onCheckedChange:()=>K({projects:Pa(v.projects,V.id)})}),e.jsx("span",{className:"text-sm",children:V.name})]},V.id))})]})]})]})]})})]}),v.viewMode==="list"&&e.jsxs(Ht,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs",children:[e.jsx(_1,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Sort"})]})}),e.jsx(Qt,{align:"end",className:"w-48 p-0",children:e.jsx("div",{className:"p-2 space-y-0.5",children:[["status","Status"],["priority","Priority"],["title","Title"],["created","Created"],["updated","Updated"]].map(([V,W])=>e.jsxs("button",{className:`flex items-center justify-between w-full px-2 py-1.5 text-sm rounded-sm ${v.sortField===V?"bg-accent/50 text-foreground":"hover:bg-accent/50 text-muted-foreground"}`,onClick:()=>{v.sortField===V?K({sortDir:v.sortDir==="asc"?"desc":"asc"}):K({sortField:V,sortDir:"asc"})},children:[e.jsx("span",{children:W}),v.sortField===V&&e.jsx("span",{className:"text-xs text-muted-foreground",children:v.sortDir==="asc"?"↑":"↓"})]},V))})})]}),v.viewMode==="list"&&e.jsxs(Ht,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs",children:[e.jsx(Jb,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Group"})]})}),e.jsx(Qt,{align:"end",className:"w-44 p-0",children:e.jsx("div",{className:"p-2 space-y-0.5",children:[["status","Status"],["priority","Priority"],["assignee","Assignee"],["none","None"]].map(([V,W])=>e.jsxs("button",{className:`flex items-center justify-between w-full px-2 py-1.5 text-sm rounded-sm ${v.groupBy===V?"bg-accent/50 text-foreground":"hover:bg-accent/50 text-muted-foreground"}`,onClick:()=>K({groupBy:V}),children:[e.jsx("span",{children:W}),v.groupBy===V&&e.jsx(Nn,{className:"h-3.5 w-3.5"})]},V))})})]})]})]}),n&&e.jsx(mn,{variant:"issues-list"}),s&&e.jsx("p",{className:"text-sm text-destructive",children:s.message}),!n&&w.length===0&&v.viewMode==="list"&&e.jsx(tn,{icon:rs,message:"No issues match the current filters or search.",action:"Create Issue",onAction:()=>j(Q())}),v.viewMode==="board"?e.jsx(cq,{issues:w,agents:r,liveIssueIds:o,onUpdateIssue:f}):R.map(V=>e.jsxs(Sa,{open:!v.collapsedGroups.includes(V.key),onOpenChange:W=>{K({collapsedGroups:W?v.collapsedGroups.filter(J=>J!==V.key):[...v.collapsedGroups,V.key]})},children:[V.label&&e.jsxs("div",{className:"flex items-center py-1.5 pl-1 pr-3",children:[e.jsxs(Ia,{className:"flex items-center gap-1.5",children:[e.jsx(sn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90"}),e.jsx("span",{className:"text-sm font-semibold uppercase tracking-wide",children:V.label})]}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:"ml-auto text-muted-foreground",onClick:()=>j(Q(V.key)),children:e.jsx(Ot,{className:"h-3 w-3"})})]}),e.jsx(_a,{children:V.items.map(W=>e.jsx(uN,{issue:W,issueLinkState:u,desktopLeadingSpacer:!0,mobileLeading:e.jsx("span",{onClick:J=>{J.preventDefault(),J.stopPropagation()},children:e.jsx(Pn,{status:W.status,onChange:J=>f(W.id,{status:J})})}),desktopMetaLeading:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden shrink-0 sm:inline-flex",onClick:J=>{J.preventDefault(),J.stopPropagation()},children:e.jsx(Pn,{status:W.status,onChange:J=>f(W.id,{status:J})})}),e.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:W.identifier??W.id.slice(0,8)}),(o==null?void 0:o.has(W.id))&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-blue-500/10 px-1.5 py-0.5 sm:gap-1.5 sm:px-2",children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-500"})]}),e.jsx("span",{className:"hidden text-[11px] font-medium text-blue-600 dark:text-blue-400 sm:inline",children:"Live"})]})]}),mobileMeta:as(W.updatedAt),desktopTrailing:e.jsxs(e.Fragment,{children:[(W.labels??[]).length>0&&e.jsxs("span",{className:"hidden items-center gap-1 overflow-hidden md:flex md:max-w-[240px]",children:[(W.labels??[]).slice(0,3).map(J=>e.jsx("span",{className:"inline-flex items-center rounded-full border px-1.5 py-0.5 text-[10px] font-medium",style:{borderColor:J.color,color:Yd(J.color,.12),backgroundColor:`${J.color}1f`},children:J.name},J.id)),(W.labels??[]).length>3&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",(W.labels??[]).length-3]})]}),e.jsxs(Ht,{open:E===W.id,onOpenChange:J=>{S(J?W.id:null),J||B("")},children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:"flex w-[180px] shrink-0 items-center rounded-md px-2 py-1 transition-colors hover:bg-accent/50",onClick:J=>{J.preventDefault(),J.stopPropagation()},children:W.assigneeAgentId&&z(W.assigneeAgentId)?e.jsx(Ut,{name:z(W.assigneeAgentId),size:"sm"}):W.assigneeUserId?e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:"inline-flex h-5 w-5 items-center justify-center rounded-full border border-dashed border-muted-foreground/35 bg-muted/30",children:e.jsx(Ns,{className:"h-3 w-3"})}),Gm(W.assigneeUserId,g)??"User"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("span",{className:"inline-flex h-5 w-5 items-center justify-center rounded-full border border-dashed border-muted-foreground/35 bg-muted/30",children:e.jsx(Ns,{className:"h-3 w-3"})}),"Assignee"]})})}),e.jsxs(Qt,{className:"w-56 p-1",align:"end",onClick:J=>J.stopPropagation(),onPointerDownOutside:()=>B(""),children:[e.jsx("input",{className:"mb-1 w-full border-b border-border bg-transparent px-2 py-1.5 text-xs outline-none placeholder:text-muted-foreground/50",placeholder:"Search assignees...",value:M,onChange:J=>B(J.target.value),autoFocus:!0}),e.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[e.jsx("button",{className:O("flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent/50",!W.assigneeAgentId&&!W.assigneeUserId&&"bg-accent"),onClick:J=>{J.preventDefault(),J.stopPropagation(),H(W.id,null,null)},children:"No assignee"}),g&&e.jsxs("button",{className:O("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",W.assigneeUserId===g&&"bg-accent"),onClick:J=>{J.preventDefault(),J.stopPropagation(),H(W.id,null,g)},children:[e.jsx(Ns,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:"Me"})]}),(r??[]).filter(J=>M.trim()?J.name.toLowerCase().includes(M.toLowerCase()):!0).map(J=>e.jsx("button",{className:O("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",W.assigneeAgentId===J.id&&"bg-accent"),onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),H(W.id,J.id,null)},children:e.jsx(Ut,{name:J.name,size:"sm",className:"min-w-0"})},J.id))]})]})]})]}),trailingMeta:xs(W.createdAt)},W.id))})]},V.key))]})}function bq(t){if(!t)return null;const n=t instanceof Date?t:new Date(t);return Number.isNaN(n.getTime())?null:n}function om(...t){let n=new Date(0);for(const s of t){const r=bq(s);r&&r.getTime()>n.getTime()&&(n=r)}return n}function yq(t){var n,s,r;return((n=t.primaryWorkspace)==null?void 0:n.id)??((s=t.workspaces.find(a=>a.isPrimary))==null?void 0:s.id)??((r=t.workspaces[0])==null?void 0:r.id)??null}function vq(t){const n=t.executionWorkspace.projectWorkspaceId??t.issue.projectWorkspaceId??null;return t.executionWorkspace.mode==="shared_workspace"&&n===t.primaryWorkspaceId}function jq(t){var o,i,l,u,d,m,p,x,f,h,j,b,g,y,v,_,E,S,M;const n=yq(t.project),s=new Map(t.executionWorkspaces.map(B=>[B.id,B])),r=new Map(t.project.workspaces.map(B=>[B.id,B])),a=new Map;for(const B of t.issues){if(B.executionWorkspaceId){const C=s.get(B.executionWorkspaceId);if(!C||C.status==="archived"||vq({executionWorkspace:C,issue:B,primaryWorkspaceId:n}))continue;const I=a.get(`execution:${C.id}`),K=[...(I==null?void 0:I.issues)??[],B].sort((T,z)=>new Date(z.updatedAt).getTime()-new Date(T.updatedAt).getTime());a.set(`execution:${C.id}`,{key:`execution:${C.id}`,kind:"execution_workspace",workspaceId:C.id,workspaceName:C.name,cwd:C.cwd??null,branchName:C.branchName??C.baseRef??null,lastUpdatedAt:om(I==null?void 0:I.lastUpdatedAt,C.lastUsedAt,C.updatedAt,B.updatedAt),projectWorkspaceId:C.projectWorkspaceId??B.projectWorkspaceId??null,executionWorkspaceId:C.id,executionWorkspaceStatus:C.status,serviceCount:((o=C.runtimeServices)==null?void 0:o.length)??0,runningServiceCount:((i=C.runtimeServices)==null?void 0:i.filter(T=>T.status==="running").length)??0,primaryServiceUrl:((u=(l=C.runtimeServices)==null?void 0:l.find(T=>T.url))==null?void 0:u.url)??null,hasRuntimeConfig:!!(((d=C.config)==null?void 0:d.workspaceRuntime)??((p=(m=r.get(C.projectWorkspaceId??B.projectWorkspaceId??""))==null?void 0:m.runtimeConfig)==null?void 0:p.workspaceRuntime)),issues:K});continue}if(!B.projectWorkspaceId||B.projectWorkspaceId===n)continue;const k=r.get(B.projectWorkspaceId);if(!k)continue;const L=a.get(`project:${k.id}`),$=[...(L==null?void 0:L.issues)??[],B].sort((C,I)=>new Date(I.updatedAt).getTime()-new Date(C.updatedAt).getTime());a.set(`project:${k.id}`,{key:`project:${k.id}`,kind:"project_workspace",workspaceId:k.id,workspaceName:k.name,cwd:k.cwd??null,branchName:k.repoRef??k.defaultRef??null,lastUpdatedAt:om(L==null?void 0:L.lastUpdatedAt,k.updatedAt,B.updatedAt),projectWorkspaceId:k.id,executionWorkspaceId:null,executionWorkspaceStatus:null,serviceCount:((x=k.runtimeServices)==null?void 0:x.length)??0,runningServiceCount:((f=k.runtimeServices)==null?void 0:f.filter(C=>C.status==="running").length)??0,primaryServiceUrl:((j=(h=k.runtimeServices)==null?void 0:h.find(C=>C.url))==null?void 0:j.url)??null,hasRuntimeConfig:!!((b=k.runtimeConfig)!=null&&b.workspaceRuntime),issues:$})}for(const B of t.project.workspaces){const k=`project:${B.id}`;a.has(k)||!(B.isPrimary||(g=B.runtimeConfig)!=null&&g.workspaceRuntime||(((y=B.runtimeServices)==null?void 0:y.length)??0)>0)||a.set(k,{key:k,kind:"project_workspace",workspaceId:B.id,workspaceName:B.name,cwd:B.cwd??null,branchName:B.repoRef??B.defaultRef??null,lastUpdatedAt:om(B.updatedAt),projectWorkspaceId:B.id,executionWorkspaceId:null,executionWorkspaceStatus:null,serviceCount:((v=B.runtimeServices)==null?void 0:v.length)??0,runningServiceCount:((_=B.runtimeServices)==null?void 0:_.filter($=>$.status==="running").length)??0,primaryServiceUrl:((S=(E=B.runtimeServices)==null?void 0:E.find($=>$.url))==null?void 0:S.url)??null,hasRuntimeConfig:!!((M=B.runtimeConfig)!=null&&M.workspaceRuntime),issues:[]})}return[...a.values()].sort((B,k)=>{const L=k.lastUpdatedAt.getTime()-B.lastUpdatedAt.getTime();return L!==0?L:B.workspaceName.localeCompare(k.workspaceName)})}function oc(t){return typeof t=="string"&&t.startsWith("plugin:")}function wq(t,n){const s=t.split("/").filter(Boolean),r=s.indexOf("projects");if(r===-1||s[r+1]!==n)return null;const a=s[r+2];return a==="overview"?"overview":a==="configuration"?"configuration":a==="budget"?"budget":a==="issues"?"list":a==="workspaces"?"workspaces":null}function Nq({project:t,onUpdate:n,imageUploadHandler:s}){return e.jsxs("div",{className:"space-y-6",children:[e.jsx(kr,{value:t.description??"",onSave:r=>n({description:r}),as:"p",className:"text-sm text-muted-foreground",placeholder:"Add a description...",multiline:!0,imageUploadHandler:s}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("div",{className:"mt-1",children:e.jsx(Dt,{status:t.status})})]}),t.targetDate&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Target Date"}),e.jsx("p",{children:t.targetDate})]})]})]})}function kq({currentColor:t,onSelect:n}){const[s,r]=c.useState(!1),a=c.useRef(null);return c.useEffect(()=>{if(!s)return;function o(i){a.current&&!a.current.contains(i.target)&&r(!1)}return document.addEventListener("mousedown",o),()=>document.removeEventListener("mousedown",o)},[s]),e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>r(!s),className:"shrink-0 h-5 w-5 rounded-md cursor-pointer hover:ring-2 hover:ring-foreground/20 transition-[box-shadow]",style:{backgroundColor:t},"aria-label":"Change project color"}),s&&e.jsx("div",{className:"absolute top-full left-0 mt-2 p-2 bg-popover border border-border rounded-lg shadow-lg z-50 w-max",children:e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Cm.map(o=>e.jsx("button",{onClick:()=>{n(o),r(!1)},className:`h-6 w-6 rounded-md cursor-pointer transition-[transform,box-shadow] duration-150 hover:scale-110 ${o===t?"ring-2 ring-foreground ring-offset-1 ring-offset-background":"hover:ring-2 hover:ring-foreground/30"}`,style:{backgroundColor:o},"aria-label":`Select color ${o}`},o))})})]})}function Cq({projectId:t,companyId:n}){const s=at(),{data:r}=oe({queryKey:N.agents.list(n),queryFn:()=>We.list(n),enabled:!!n}),{data:a}=oe({queryKey:N.liveRuns(n),queryFn:()=>Yt.liveRunsForCompany(n),enabled:!!n,refetchInterval:5e3}),o=c.useMemo(()=>{const m=new Set;for(const p of a??[])p.issueId&&m.add(p.issueId);return m},[a]),{data:i,isLoading:l,error:u}=oe({queryKey:N.issues.listByProject(n,t),queryFn:()=>nt.list(n,{projectId:t}),enabled:!!n}),d=ge({mutationFn:({id:m,data:p})=>nt.update(m,p),onSuccess:()=>{s.invalidateQueries({queryKey:N.issues.listByProject(n,t)}),s.invalidateQueries({queryKey:N.issues.list(n)})}});return e.jsx(pN,{issues:i??[],isLoading:l,error:u,agents:r,liveIssueIds:o,projectId:t,viewStateKey:`crewspace:project-view:${t}`,onUpdateIssue:(m,p)=>d.mutate({id:m,data:p})})}function Sq({companyId:t,projectId:n,projectRef:s,summaries:r}){const a=at(),[o,i]=c.useState(null),[l,u]=c.useState(null),d=ge({mutationFn:async f=>(i(`${f.key}:${f.action}`),f.kind==="project_workspace"?await en.controlWorkspaceRuntimeServices(n,f.workspaceId,f.action,t):await or.controlRuntimeServices(f.workspaceId,f.action)),onSettled:()=>{i(null),a.invalidateQueries({queryKey:N.executionWorkspaces.list(t,{projectId:n})}),a.invalidateQueries({queryKey:N.projects.detail(n)}),a.invalidateQueries({queryKey:N.issues.listByProject(t,n)})}});if(r.length===0)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"No non-default workspace activity yet."});const m=r.filter(f=>f.executionWorkspaceStatus!=="cleanup_failed"),p=r.filter(f=>f.executionWorkspaceStatus==="cleanup_failed"),x=f=>{const h=f.issues.slice(0,3),j=Math.max(f.issues.length-h.length,0),b=f.kind==="project_workspace"?Ud({id:s,urlKey:s},f.workspaceId):`/execution-workspaces/${f.workspaceId}`;return e.jsx("div",{className:"border-b border-border px-4 py-3 last:border-b-0",children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-[minmax(0,18rem)_minmax(0,1fr)_auto] md:items-start",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Oe,{to:b,className:"block truncate text-sm font-medium hover:underline",children:f.workspaceName}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Yo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-mono",children:f.branchName??"No branch info"})]}),e.jsxs("span",{className:"rounded-full border border-border px-2 py-0.5 text-[11px]",children:[f.runningServiceCount,"/",f.serviceCount," services running"]}),f.executionWorkspaceStatus?e.jsx("span",{className:"rounded-full border border-border px-2 py-0.5 text-[11px]",children:f.executionWorkspaceStatus}):null]}),f.primaryServiceUrl?e.jsx("a",{href:f.primaryServiceUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs text-muted-foreground hover:underline",children:f.primaryServiceUrl}):null,f.cwd?e.jsxs("div",{className:"mt-2 flex min-w-0 items-start gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 truncate font-mono leading-tight",title:f.cwd,children:f.cwd}),e.jsx(uo,{text:f.cwd,className:"shrink-0",copiedLabel:"Path copied",children:e.jsx(_s,{className:"h-3.5 w-3.5"})})]}):null]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground",children:["Issues (",f.issues.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[h.map(g=>e.jsxs(Oe,{to:`/issues/${g.identifier??g.id}`,className:"inline-flex max-w-full items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5 text-left text-xs leading-none transition-colors hover:bg-accent",children:[e.jsx("span",{className:"shrink-0 font-mono text-[11px] text-muted-foreground",children:g.identifier??g.id.slice(0,8)}),e.jsx("span",{className:"truncate leading-tight",children:g.title})]},g.id)),j>0?e.jsxs("span",{className:"inline-flex items-center rounded-md border border-dashed border-border px-2.5 py-1.5 text-xs text-muted-foreground",children:["... and ",j," more"]}):null]})]}),e.jsxs("div",{className:"flex shrink-0 flex-col items-start gap-2 md:items-end",children:[e.jsx(Oe,{to:b,className:"text-xs font-medium text-foreground hover:underline",children:f.kind==="project_workspace"?"Configure workspace":"View workspace"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",disabled:d.isPending||!f.hasRuntimeConfig||o!==null&&o!==`${f.key}:start`,onClick:()=>d.mutate({key:f.key,kind:f.kind,workspaceId:f.workspaceId,action:"start"}),children:[o===`${f.key}:start`?e.jsx(kn,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):null,"Start"]}),e.jsx(G,{variant:"outline",size:"sm",disabled:d.isPending||f.serviceCount===0,onClick:()=>d.mutate({key:f.key,kind:f.kind,workspaceId:f.workspaceId,action:"stop"}),children:"Stop"})]}),f.kind==="execution_workspace"&&f.executionWorkspaceId&&f.executionWorkspaceStatus?e.jsx(G,{variant:"outline",size:"sm",onClick:()=>u({id:f.executionWorkspaceId,name:f.workspaceName,status:f.executionWorkspaceStatus}),children:f.executionWorkspaceStatus==="cleanup_failed"?"Retry close":"Close workspace"}):null,e.jsxs("div",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Nl,{className:"h-3.5 w-3.5"}),as(f.lastUpdatedAt)]})]})]})},f.key)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:m.map(x)}),p.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Cleanup attention needed"}),e.jsx("div",{className:"overflow-hidden rounded-xl border border-amber-500/20 bg-amber-500/5",children:p.map(x)})]}):null]}),l?e.jsx(oN,{workspaceId:l.id,workspaceName:l.name,currentStatus:l.status,open:!0,onOpenChange:f=>{f||u(null)},onClosed:()=>{a.invalidateQueries({queryKey:N.executionWorkspaces.list(t,{projectId:n})}),a.invalidateQueries({queryKey:N.projects.detail(n)}),a.invalidateQueries({queryKey:N.issues.listByProject(t,n)}),u(null)}}):null]})}function Ma(){var Ie;const{companyPrefix:t,projectId:n,filter:s}=Xn(),{companies:r,selectedCompanyId:a,setSelectedCompanyId:o}=et(),{closePanel:i}=ji(),{setBreadcrumbs:l}=Ft(),{pushToast:u}=ds(),d=at(),m=Sn(),p=fn(),[x,f]=c.useState({}),h=c.useRef({}),j=c.useRef({}),b=n??"",y=c.useMemo(()=>{var Be;if(!t)return null;const ue=t.toUpperCase();return((Be=r.find(be=>be.issuePrefix.toUpperCase()===ue))==null?void 0:Be.id)??null},[r,t])??a??void 0,v=b.length>0&&(qd(b)||!!y),_=b?wq(p.pathname,b):null,E=c.useMemo(()=>{const ue=new URLSearchParams(p.search).get("tab");return oc(ue)?ue:null},[p.search]),S=_??E,{data:M,isLoading:B,error:k}=oe({queryKey:[...N.projects.detail(b),y??null],queryFn:()=>en.get(b,y),enabled:v}),L=M?Al(M):b,$=(M==null?void 0:M.id)??b,C=(M==null?void 0:M.companyId)??a,I=oe({queryKey:N.instance.experimentalSettings,queryFn:()=>Rr.getExperimental()}),{slots:K,isLoading:T}=yi({slotTypes:["detailTab"],entityType:"project",enabled:!!C}),z=c.useMemo(()=>K.map(ue=>({value:`plugin:${ue.pluginKey}:${ue.id}`,label:ue.displayName,slot:ue})),[K]),w=z.find(ue=>ue.value===S)??null,F=((Ie=I.data)==null?void 0:Ie.enableIsolatedWorkspaces)===!0,A=(M==null?void 0:M.id)??null,{data:R=[],isLoading:Q,error:H}=oe({queryKey:A&&C?N.issues.listByProject(C,A):["issues","__workspace-tab__","disabled"],queryFn:()=>nt.list(C,{projectId:A}),enabled:!!(C&&A&&F)}),{data:U=[],isLoading:Z,error:V}=oe({queryKey:A&&C?N.executionWorkspaces.list(C,{projectId:A}):["execution-workspaces","__workspace-tab__","disabled"],queryFn:()=>or.list(C,{projectId:A}),enabled:!!(C&&A&&F)}),W=c.useMemo(()=>!M||!F?[]:jq({project:M,issues:R,executionWorkspaces:U}),[M,F,R,U]),J=F&&W.length>0,Y=I.isFetched&&(!F||!Q&&!Z),de=H??V;c.useEffect(()=>{!(M!=null&&M.companyId)||M.companyId===a||o(M.companyId,{source:"route_sync"})},[M==null?void 0:M.companyId,a,o]);const fe=()=>{d.invalidateQueries({queryKey:N.projects.detail(b)}),d.invalidateQueries({queryKey:N.projects.detail($)}),C&&d.invalidateQueries({queryKey:N.projects.list(C)})},Ce=ge({mutationFn:ue=>en.update($,ue,C??y),onSuccess:fe}),le=ge({mutationFn:ue=>en.update($,{archivedAt:ue?new Date().toISOString():null},C??y),onSuccess:(ue,Be)=>{fe();const be=(ue==null?void 0:ue.name)??(M==null?void 0:M.name)??"Project";Be?(u({title:`"${be}" has been archived`,tone:"success"}),m("/dashboard")):u({title:`"${be}" has been unarchived`,tone:"success"})},onError:(ue,Be)=>{u({title:Be?"Failed to archive project":"Failed to unarchive project",tone:"error"})}}),Re=ge({mutationFn:async ue=>{if(!C)throw new Error("No company selected");return Aa.uploadImage(C,ue,`projects/${$||"draft"}`)}}),{data:Pe}=oe({queryKey:N.budgets.overview(C??"__none__"),queryFn:()=>Wa.overview(C),enabled:!!C,refetchInterval:3e4,staleTime:5e3});c.useEffect(()=>{l([{label:"Projects",href:"/projects"},{label:(M==null?void 0:M.name)??b??"Project"}])},[l,M,b]),c.useEffect(()=>{if(M&&b!==L){if(oc(S)){m(`/projects/${L}?tab=${encodeURIComponent(S)}`,{replace:!0});return}if(S==="overview"){m(`/projects/${L}/overview`,{replace:!0});return}if(S==="configuration"){m(`/projects/${L}/configuration`,{replace:!0});return}if(S==="budget"){m(`/projects/${L}/budget`,{replace:!0});return}if(S==="workspaces"){m(`/projects/${L}/workspaces`,{replace:!0});return}if(S==="list"){if(s){m(`/projects/${L}/issues/${s}`,{replace:!0});return}m(`/projects/${L}/issues`,{replace:!0});return}m(`/projects/${L}`,{replace:!0})}},[M,b,L,S,s,m]),c.useEffect(()=>(i(),()=>i()),[i]),c.useEffect(()=>()=>{Object.values(j.current).forEach(ue=>{ue&&clearTimeout(ue)})},[]);const Fe=c.useCallback((ue,Be)=>{f(be=>({...be,[ue]:Be}))},[]),pe=c.useCallback((ue,Be)=>{const be=j.current[ue];be&&clearTimeout(be),j.current[ue]=setTimeout(()=>{f(he=>{const Se={...he};return delete Se[ue],Se}),delete j.current[ue]},Be)},[]),Le=c.useCallback(async(ue,Be)=>{const be=(h.current[ue]??0)+1;h.current[ue]=be,Fe(ue,"saving");try{if(await en.update($,Be,C??y),fe(),h.current[ue]!==be)return;Fe(ue,"saved"),pe(ue,1800)}catch(he){if(h.current[ue]!==be)return;throw Fe(ue,"error"),pe(ue,3e3),he}},[fe,y,$,C,pe,Fe]),q=c.useMemo(()=>{const ue=Pe==null?void 0:Pe.policies.find(Be=>Be.scopeType==="project"&&Be.scopeId===((M==null?void 0:M.id)??b));return ue||{policyId:"",companyId:C??"",scopeType:"project",scopeId:(M==null?void 0:M.id)??b,scopeName:(M==null?void 0:M.name)??"Project",metric:"billed_cents",windowKind:"lifetime",amount:0,observedAmount:0,remainingAmount:0,utilizationPercent:0,warnPercent:80,hardStopEnabled:!0,notifyEnabled:!0,isActive:!1,status:"ok",paused:!!(M!=null&&M.pausedAt),pauseReason:(M==null?void 0:M.pauseReason)??null,windowStart:new Date,windowEnd:new Date}},[Pe==null?void 0:Pe.policies,M,C,b]),D=ge({mutationFn:ue=>Wa.upsertPolicy(C,{scopeType:"project",scopeId:(M==null?void 0:M.id)??b,amount:ue,windowKind:"lifetime"}),onSuccess:()=>{C&&(d.invalidateQueries({queryKey:N.budgets.overview(C)}),d.invalidateQueries({queryKey:N.projects.detail(b)}),d.invalidateQueries({queryKey:N.projects.detail($)}),d.invalidateQueries({queryKey:N.projects.list(C)}),d.invalidateQueries({queryKey:N.dashboard(C)}))}});if(E&&!T&&!w)return e.jsx(Zt,{to:`/projects/${L}/issues`,replace:!0});if(S==="workspaces"&&Y&&!J)return e.jsx(Zt,{to:`/projects/${L}/issues`,replace:!0});if(b&&S===null){let ue=null;if(M!=null&&M.id)try{ue=localStorage.getItem(`crewspace:project-tab:${M.id}`)}catch{}return ue==="overview"?e.jsx(Zt,{to:`/projects/${L}/overview`,replace:!0}):ue==="configuration"?e.jsx(Zt,{to:`/projects/${L}/configuration`,replace:!0}):ue==="budget"?e.jsx(Zt,{to:`/projects/${L}/budget`,replace:!0}):ue==="workspaces"&&Y&&J?e.jsx(Zt,{to:`/projects/${L}/workspaces`,replace:!0}):ue==="workspaces"&&!Y?e.jsx(mn,{variant:"detail"}):oc(ue)?e.jsx(Zt,{to:`/projects/${L}?tab=${encodeURIComponent(ue)}`,replace:!0}):e.jsx(Zt,{to:`/projects/${L}/issues`,replace:!0})}if(B)return e.jsx(mn,{variant:"detail"});if(k)return e.jsx("p",{className:"text-sm text-destructive",children:k.message});if(!M)return null;const ie=ue=>{if(M!=null&&M.id)try{localStorage.setItem(`crewspace:project-tab:${M.id}`,ue)}catch{}if(oc(ue)){m(`/projects/${L}?tab=${encodeURIComponent(ue)}`);return}m(ue==="overview"?`/projects/${L}/overview`:ue==="workspaces"?`/projects/${L}/workspaces`:ue==="budget"?`/projects/${L}/budget`:ue==="configuration"?`/projects/${L}/configuration`:`/projects/${L}/issues`)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-7 flex items-center",children:e.jsx(kq,{currentColor:M.color??"#6366f1",onSelect:ue=>Ce.mutate({color:ue})})}),e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx(kr,{value:M.name,onSave:ue=>Ce.mutate({name:ue}),as:"h2",className:"text-xl font-bold"}),M.pauseReason==="budget"?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-red-500/30 bg-red-500/10 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-red-200",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-400"}),"Paused by budget hard stop"]}):null]})]}),e.jsx(Vr,{slotTypes:["toolbarButton","contextMenuItem"],entityType:"project",context:{companyId:C??null,companyPrefix:t??null,projectId:M.id,projectRef:L,entityId:M.id,entityType:"project"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex",missingBehavior:"placeholder"}),e.jsx($x,{placementZones:["toolbarButton"],entityType:"project",context:{companyId:C??null,companyPrefix:t??null,projectId:M.id,projectRef:L,entityId:M.id,entityType:"project"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex"}),e.jsx(Ss,{value:S??"list",onValueChange:ue=>ie(ue),children:e.jsx(Ca,{items:[{value:"list",label:"Issues"},{value:"overview",label:"Overview"},...J?[{value:"workspaces",label:"Workspaces"}]:[],{value:"configuration",label:"Configuration"},{value:"budget",label:"Budget"},...z.map(ue=>({value:ue.value,label:ue.label}))],align:"start",value:S??"list",onValueChange:ue=>ie(ue)})}),S==="overview"&&e.jsx(Nq,{project:M,onUpdate:ue=>Ce.mutate(ue),imageUploadHandler:async ue=>(await Re.mutateAsync(ue)).contentPath}),S==="list"&&(M==null?void 0:M.id)&&C&&e.jsx(Cq,{projectId:M.id,companyId:C}),S==="workspaces"?Y?de?e.jsx("p",{className:"text-sm text-destructive",children:de.message}):e.jsx(Sq,{companyId:C,projectId:M.id,projectRef:L,summaries:W}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading workspaces..."}):null,S==="configuration"&&e.jsx("div",{className:"max-w-4xl",children:e.jsx(eq,{project:M,onUpdate:ue=>Ce.mutate(ue),onFieldUpdate:Le,getFieldSaveState:ue=>x[ue]??"idle",onArchive:ue=>le.mutate(ue),archivePending:le.isPending})}),S==="budget"&&C?e.jsx("div",{className:"max-w-3xl",children:e.jsx(rf,{summary:q,variant:"plain",isSaving:D.isPending,onSave:ue=>D.mutate(ue)})}):null,w&&e.jsx(vi,{slot:w.slot,context:{companyId:C,companyPrefix:t??null,projectId:M.id,projectRef:L,entityId:M.id,entityType:"project"},missingBehavior:"placeholder"})]})}const _g=[{value:"local_path",label:"Local git checkout",description:"A local path CrewSpace can use directly."},{value:"non_git_path",label:"Local non-git path",description:"A local folder without git semantics."},{value:"git_repo",label:"Remote git repo",description:"A repo URL with optional refs and local checkout."},{value:"remote_managed",label:"Remote-managed workspace",description:"A hosted workspace tracked by external reference."}],Iq=[{value:"default",label:"Default"},{value:"advanced",label:"Advanced"}];function _q(t){if(!t)return!1;try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function Aq(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}function Lr(t){return t??""}function Eq(t){return!t||Object.keys(t).length===0?"":JSON.stringify(t,null,2)}function Ag(t){var n;return{name:t.name,sourceType:t.sourceType,cwd:Lr(t.cwd),repoUrl:Lr(t.repoUrl),repoRef:Lr(t.repoRef),defaultRef:Lr(t.defaultRef),visibility:t.visibility,setupCommand:Lr(t.setupCommand),cleanupCommand:Lr(t.cleanupCommand),remoteProvider:Lr(t.remoteProvider),remoteWorkspaceRef:Lr(t.remoteWorkspaceRef),sharedWorkspaceKey:Lr(t.sharedWorkspaceKey),runtimeConfig:Eq((n=t.runtimeConfig)==null?void 0:n.workspaceRuntime)}}function $s(t){const n=t.trim();return n.length>0?n:null}function xN(t){const n=t.trim();if(!n)return{ok:!0,value:null};try{const s=JSON.parse(n);return!s||typeof s!="object"||Array.isArray(s)?{ok:!1,error:"Runtime services JSON must be a JSON object."}:{ok:!0,value:s}}catch(s){return{ok:!1,error:s instanceof Error?s.message:"Invalid JSON."}}}function Tq(t,n){const s={},r=(a,o)=>{const i=t[a],l=n[a];i!==l&&(s[a]=o?o(l):l)};if(r("name",$s),r("sourceType"),r("cwd",$s),r("repoUrl",$s),r("repoRef",$s),r("defaultRef",$s),r("visibility"),r("setupCommand",$s),r("cleanupCommand",$s),r("remoteProvider",$s),r("remoteWorkspaceRef",$s),r("sharedWorkspaceKey",$s),t.runtimeConfig!==n.runtimeConfig){const a=xN(n.runtimeConfig);if(!a.ok)throw new Error(a.error);s.runtimeConfig={workspaceRuntime:a.value}}return s}function Rq(t){const n=$s(t.cwd),s=$s(t.repoUrl),r=$s(t.remoteWorkspaceRef);if(t.sourceType==="remote_managed"){if(!r&&!s)return"Remote-managed workspaces require a remote workspace ref or repo URL."}else if(!n&&!s)return"Workspace requires at least one local path or repo URL.";if(n&&(t.sourceType==="local_path"||t.sourceType==="non_git_path")&&!Aq(n))return"Local workspace path must be absolute.";if(s)try{new URL(s)}catch{return"Repo URL must be a valid URL."}const a=xN(t.runtimeConfig);return a.ok?null:a.error}function Ts({label:t,hint:n,children:s}){return e.jsxs("label",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-3",children:[e.jsx("span",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:t}),n?e.jsx("span",{className:"text-[11px] leading-relaxed text-muted-foreground sm:text-right",children:n}):null]}),s]})}function _o({label:t,children:n}){return e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 sm:flex-row sm:items-start sm:gap-3",children:[e.jsx("div",{className:"shrink-0 text-xs text-muted-foreground sm:w-28",children:t}),e.jsx("div",{className:"min-w-0 flex-1 text-sm",children:n})]})}function Pq(){var z,w,F,A;const{companyPrefix:t,projectId:n,workspaceId:s}=Xn(),{companies:r,selectedCompanyId:a,setSelectedCompanyId:o}=et(),{setBreadcrumbs:i}=Ft(),l=Sn(),u=at(),[d,m]=c.useState(null),[p,x]=c.useState(null),[f,h]=c.useState(null),j=n??"",b=s??"",y=c.useMemo(()=>{var Q;if(!t)return null;const R=t.toUpperCase();return((Q=r.find(H=>H.issuePrefix.toUpperCase()===R))==null?void 0:Q.id)??null},[r,t])??a??void 0,v=j.length>0&&(qd(j)||!!y),_=oe({queryKey:[...N.projects.detail(j),y??null],queryFn:()=>en.get(j,y),enabled:v}),E=_.data??null,S=c.useMemo(()=>(E==null?void 0:E.workspaces.find(R=>R.id===b))??null,[E,b]),M=E?Al(E):j,B=c.useMemo(()=>S?Ag(S):null,[S]),k=!!(d&&B&&JSON.stringify(d)!==JSON.stringify(B));c.useEffect(()=>{!(E!=null&&E.companyId)||E.companyId===a||o(E.companyId,{source:"route_sync"})},[E==null?void 0:E.companyId,a,o]),c.useEffect(()=>{S&&(m(Ag(S)),x(null))},[S]),c.useEffect(()=>{E&&i([{label:"Projects",href:"/projects"},{label:E.name,href:`/projects/${M}`},{label:"Workspaces",href:`/projects/${M}/workspaces`},{label:(S==null?void 0:S.name)??b}])},[i,E,M,S==null?void 0:S.name,b]),c.useEffect(()=>{E&&j!==M&&l(Ud(E,b),{replace:!0})},[E,j,M,b,l]);const L=()=>{E&&(u.invalidateQueries({queryKey:N.projects.detail(E.id)}),u.invalidateQueries({queryKey:N.projects.detail(E.urlKey)}),y&&u.invalidateQueries({queryKey:N.projects.list(y)}))},$=ge({mutationFn:R=>en.updateWorkspace(E.id,b,R,y),onSuccess:()=>{L(),x(null)},onError:R=>{x(R instanceof Error?R.message:"Failed to save workspace.")}}),C=ge({mutationFn:()=>en.updateWorkspace(E.id,b,{isPrimary:!0},y),onSuccess:()=>{L(),x(null)},onError:R=>{x(R instanceof Error?R.message:"Failed to update workspace.")}}),I=ge({mutationFn:R=>en.controlWorkspaceRuntimeServices(E.id,b,R,y),onSuccess:(R,Q)=>{L(),x(null),h(Q==="stop"?"Runtime services stopped.":Q==="restart"?"Runtime services restarted.":"Runtime services started.")},onError:R=>{h(null),x(R instanceof Error?R.message:"Failed to control runtime services.")}});if(_.isLoading)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading workspace…"});if(_.error)return e.jsx("p",{className:"text-sm text-destructive",children:_.error instanceof Error?_.error.message:"Failed to load workspace"});if(!E||!S||!d||!B)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Workspace not found for this project."});const K=()=>{const R=Rq(d);if(R){x(R);return}const Q=Tq(B,d);Object.keys(Q).length!==0&&$.mutate(Q)},T=((z=_g.find(R=>R.value===d.sourceType))==null?void 0:z.description)??null;return e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(Oe,{to:`/projects/${M}/workspaces`,children:[e.jsx(fo,{className:"mr-1 h-4 w-4"}),"Back to workspaces"]})}),e.jsx("div",{className:"inline-flex items-center rounded-full border border-border bg-background px-2.5 py-1 text-xs text-muted-foreground",children:S.isPrimary?"Primary workspace":"Secondary workspace"})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1.4fr)_minmax(18rem,0.9fr)]",children:[e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Project workspace"}),e.jsx("h1",{className:"text-2xl font-semibold",children:S.name}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Configure the concrete workspace CrewSpace attaches to this project. These values drive per-workspace checkout behavior, default runtime services for child execution workspaces, and let you override setup or cleanup commands when one workspace needs special handling."})]}),S.isPrimary?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-xl border border-emerald-500/25 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-700 dark:text-emerald-300 sm:max-w-sm",children:[e.jsx(xo,{className:"h-4 w-4"}),"This is the project’s primary codebase workspace."]}):e.jsxs(G,{variant:"outline",className:"w-full sm:w-auto",disabled:C.isPending,onClick:()=>C.mutate(),children:[C.isPending?e.jsx(kn,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Nn,{className:"mr-2 h-4 w-4"}),"Make primary"]})]}),e.jsx(yn,{className:"my-5"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ts,{label:"Workspace name",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none",value:d.name,onChange:R=>m(Q=>Q&&{...Q,name:R.target.value}),placeholder:"Workspace name"})}),e.jsx(Ts,{label:"Visibility",children:e.jsx("select",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none",value:d.visibility,onChange:R=>m(Q=>Q&&{...Q,visibility:R.target.value}),children:Iq.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))})})]}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(Ts,{label:"Source type",hint:T??void 0,children:e.jsx("select",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none",value:d.sourceType,onChange:R=>m(Q=>Q&&{...Q,sourceType:R.target.value}),children:_g.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsx(Ts,{label:"Local path",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.cwd,onChange:R=>m(Q=>Q&&{...Q,cwd:R.target.value}),placeholder:"/absolute/path/to/workspace"})}),e.jsx("div",{className:"flex items-end",children:e.jsx(pr,{})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ts,{label:"Repo URL",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none",value:d.repoUrl,onChange:R=>m(Q=>Q&&{...Q,repoUrl:R.target.value}),placeholder:"https://github.com/org/repo"})}),e.jsx(Ts,{label:"Repo ref",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.repoRef,onChange:R=>m(Q=>Q&&{...Q,repoRef:R.target.value}),placeholder:"origin/main"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ts,{label:"Default ref",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.defaultRef,onChange:R=>m(Q=>Q&&{...Q,defaultRef:R.target.value}),placeholder:"origin/main"})}),e.jsx(Ts,{label:"Shared workspace key",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.sharedWorkspaceKey,onChange:R=>m(Q=>Q&&{...Q,sharedWorkspaceKey:R.target.value}),placeholder:"frontend"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ts,{label:"Remote provider",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none",value:d.remoteProvider,onChange:R=>m(Q=>Q&&{...Q,remoteProvider:R.target.value}),placeholder:"codespaces"})}),e.jsx(Ts,{label:"Remote workspace ref",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.remoteWorkspaceRef,onChange:R=>m(Q=>Q&&{...Q,remoteWorkspaceRef:R.target.value}),placeholder:"workspace-123"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ts,{label:"Setup command",hint:"Runs when this workspace needs custom bootstrap",children:e.jsx("textarea",{className:"min-h-28 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.setupCommand,onChange:R=>m(Q=>Q&&{...Q,setupCommand:R.target.value}),placeholder:"pnpm install && pnpm dev"})}),e.jsx(Ts,{label:"Cleanup command",hint:"Runs before project-level execution workspace teardown",children:e.jsx("textarea",{className:"min-h-28 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.cleanupCommand,onChange:R=>m(Q=>Q&&{...Q,cleanupCommand:R.target.value}),placeholder:"pkill -f vite || true"})})]}),e.jsx(Ts,{label:"Runtime services JSON",hint:"Default runtime services for this workspace. Execution workspaces inherit this config unless they set an override. If you do not know the commands yet, ask your CEO to configure them for you.",children:e.jsx("textarea",{className:"min-h-36 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:d.runtimeConfig,onChange:R=>m(Q=>Q&&{...Q,runtimeConfig:R.target.value}),placeholder:`{
|
|
93
|
+
"services": [
|
|
94
|
+
{
|
|
95
|
+
"name": "web",
|
|
96
|
+
"command": "pnpm dev",
|
|
97
|
+
"cwd": ".",
|
|
98
|
+
"port": { "type": "auto" },
|
|
99
|
+
"readiness": {
|
|
100
|
+
"type": "http",
|
|
101
|
+
"urlTemplate": "http://127.0.0.1:\${port}"
|
|
102
|
+
},
|
|
103
|
+
"expose": {
|
|
104
|
+
"type": "url",
|
|
105
|
+
"urlTemplate": "http://127.0.0.1:\${port}"
|
|
106
|
+
},
|
|
107
|
+
"lifecycle": "shared",
|
|
108
|
+
"reuseScope": "project_workspace"
|
|
109
|
+
}
|
|
110
|
+
]
|
|
111
|
+
}`})})]}),e.jsxs("div",{className:"mt-5 flex flex-col items-stretch gap-3 sm:flex-row sm:flex-wrap sm:items-center",children:[e.jsxs(G,{className:"w-full sm:w-auto",disabled:!k||$.isPending,onClick:K,children:[$.isPending?e.jsx(kn,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Save changes"]}),e.jsx(G,{variant:"outline",className:"w-full sm:w-auto",disabled:!k||$.isPending,onClick:()=>{m(B),x(null)},children:"Reset"}),p?e.jsx("p",{className:"text-sm text-destructive",children:p}):null,!p&&f?e.jsx("p",{className:"text-sm text-muted-foreground",children:f}):null,!p&&!k?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No unsaved changes."}):null]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Workspace facts"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Current state"})]}),e.jsx(yn,{className:"my-4"}),e.jsx(_o,{label:"Project",children:e.jsx(Oe,{to:`/projects/${M}`,className:"hover:underline",children:E.name})}),e.jsx(_o,{label:"Workspace ID",children:e.jsx("span",{className:"break-all font-mono text-xs",children:S.id})}),e.jsx(_o,{label:"Local path",children:e.jsx("span",{className:"break-all font-mono text-xs",children:S.cwd??"None"})}),e.jsx(_o,{label:"Repo",children:S.repoUrl&&_q(S.repoUrl)?e.jsxs("a",{href:S.repoUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 hover:underline",children:[S.repoUrl,e.jsx(Is,{className:"h-3 w-3"})]}):S.repoUrl?e.jsx("span",{className:"break-all font-mono text-xs",children:S.repoUrl}):"None"}),e.jsx(_o,{label:"Default ref",children:S.defaultRef??"None"}),e.jsx(_o,{label:"Updated",children:new Date(S.updatedAt).toLocaleString()})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Runtime services"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Attached services"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Shared services for this project workspace. Execution workspaces inherit this config unless they override it."})]}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:flex-wrap",children:[e.jsxs(G,{variant:"outline",size:"sm",className:"w-full sm:w-auto",disabled:I.isPending||!((w=S.runtimeConfig)!=null&&w.workspaceRuntime)||!S.cwd,onClick:()=>I.mutate("start"),children:[I.isPending?e.jsx(kn,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):null,"Start"]}),e.jsx(G,{variant:"outline",size:"sm",className:"w-full sm:w-auto",disabled:I.isPending||!S.cwd,onClick:()=>I.mutate("restart"),children:"Restart"}),e.jsx(G,{variant:"outline",size:"sm",className:"w-full sm:w-auto",disabled:I.isPending||(((F=S.runtimeServices)==null?void 0:F.length)??0)===0,onClick:()=>I.mutate("stop"),children:"Stop"})]})]}),e.jsx(yn,{className:"my-4"}),S.runtimeServices&&S.runtimeServices.length>0?e.jsx("div",{className:"space-y-3",children:S.runtimeServices.map(R=>e.jsx("div",{className:"rounded-xl border border-border/80 bg-background px-3 py-2",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm font-medium",children:R.serviceName}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[R.url?e.jsxs("a",{href:R.url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 hover:underline",children:[R.url,e.jsx(Is,{className:"h-3 w-3"})]}):null,R.port?e.jsxs("div",{children:["Port ",R.port]}):null,e.jsx("div",{children:R.command??"No command recorded"}),R.cwd?e.jsx("div",{className:"break-all font-mono",children:R.cwd}):null]})]}),e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground sm:text-right",children:[R.status," · ",R.healthStatus]})]})},R.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=S.runtimeConfig)!=null&&A.workspaceRuntime?"No runtime services are currently running for this workspace.":"No runtime-service default is configured for this workspace yet."})]})]})]})]})}function Mq(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),s=fn(),[r]=ui(),a=at(),o=r.get("q")??"",i=r.get("participantAgentId")??void 0,l=c.useCallback(g=>{const y=g.trim();if((new URLSearchParams(window.location.search).get("q")??"")===y)return;const _=new URL(window.location.href);y?_.searchParams.set("q",y):_.searchParams.delete("q");const E=`${_.pathname}${_.search}${_.hash}`;window.history.replaceState(window.history.state,"",E)},[]),{data:u}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),{data:d}=oe({queryKey:N.projects.list(t),queryFn:()=>en.list(t),enabled:!!t}),{data:m}=oe({queryKey:N.liveRuns(t),queryFn:()=>Yt.liveRunsForCompany(t),enabled:!!t,refetchInterval:5e3}),p=c.useMemo(()=>{const g=new Set;for(const y of m??[])y.issueId&&g.add(y.issueId);return g},[m]),x=c.useMemo(()=>dN("Issues",`${s.pathname}${s.search}${s.hash}`,"issues"),[s.pathname,s.search,s.hash]);c.useEffect(()=>{n([{label:"Issues"}])},[n]);const{data:f,isLoading:h,error:j}=oe({queryKey:[...N.issues.list(t),"participant-agent",i??"__all__"],queryFn:()=>nt.list(t,{participantAgentId:i}),enabled:!!t}),b=ge({mutationFn:({id:g,data:y})=>nt.update(g,y),onSuccess:()=>{a.invalidateQueries({queryKey:N.issues.list(t)})}});return t?e.jsx(pN,{issues:f??[],isLoading:h,error:j,agents:u,projects:d,liveIssueIds:p,viewStateKey:"crewspace:issues-view",issueLinkState:x,initialAssignees:r.get("assignee")?[r.get("assignee")]:void 0,initialSearch:o,onSearchChange:l,onUpdateIssue:(g,y)=>b.mutate({id:g,data:y}),searchFilters:i?{participantAgentId:i}:void 0}):e.jsx(tn,{icon:rs,message:"Select a company to view issues."})}function pd(t){return new Date(t).getTime()}function $q(){var n,s;const t=(s=(n=globalThis.crypto)==null?void 0:n.randomUUID)==null?void 0:s.call(n);return t?`optimistic-${t}`:`optimistic-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function cp(t){return[...t].sort((n,s)=>{const r=pd(n.createdAt)-pd(s.createdAt);return r!==0?r:n.id.localeCompare(s.id)})}function Eg(t){const n=new Date,s=$q();return{id:s,clientId:s,companyId:t.companyId,issueId:t.issueId,authorAgentId:null,authorUserId:t.authorUserId,body:t.body,clientStatus:t.clientStatus??"pending",queueTargetRunId:t.queueTargetRunId??null,createdAt:n,updatedAt:n}}function Dq(t){return t.runId||t.interruptedRunId?!1:t.comment.clientStatus==="queued"?!0:t.activeRunStartedAt?pd(t.comment.createdAt)>=pd(t.activeRunStartedAt):!1}function Tg(t,n){const s=[...t??[]],r=new Set(s.map(a=>a.id));for(const a of n)r.has(a.id)||s.push(a);return cp(s)}function Rg(t,n){const s=t??[],r=s.findIndex(o=>o.id===n.id);if(r===-1)return cp([...s,n]);const a=[...s];return a[r]=n,cp(a)}function Pg(t,n){if(!t)return t;const s={...t};return n.reopen===!0&&(t.status==="done"||t.status==="cancelled")&&(s.status="todo"),n.reassignment&&(s.assigneeAgentId=n.reassignment.assigneeAgentId,s.assigneeUserId=n.reassignment.assigneeUserId),s}function Oq(t){return t.currentBody.trim()?t.currentBody:t.submittedBody}const Lq=800;function Fq(t){try{return localStorage.getItem(t)??""}catch{return""}}function qq(t,n){try{n.trim()?localStorage.setItem(t,n):localStorage.removeItem(t)}catch{}}function Uq(t){try{localStorage.removeItem(t)}catch{}}function Bq(t){if(!t||t==="__none__")return{assigneeAgentId:null,assigneeUserId:null};if(t.startsWith("agent:")){const n=t.slice(6);return n?{assigneeAgentId:n,assigneeUserId:null}:null}if(t.startsWith("user:")){const n=t.slice(5);return n?{assigneeAgentId:null,assigneeUserId:n}:null}return null}function Kq({text:t}){const[n,s]=c.useState(!1);return e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground transition-colors",title:"Copy as markdown",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)})},children:n?e.jsx(Nn,{className:"h-3 w-3"}):e.jsx(_s,{className:"h-3 w-3"})})}function fN({comment:t,agentMap:n,companyId:s,projectId:r,highlightCommentId:a,queued:o=!1}){var d;const i=a===t.id,l=t.clientStatus==="pending",u=o||t.queueState==="queued"||t.clientStatus==="queued";return e.jsxs("div",{id:`comment-${t.id}`,className:`border p-3 overflow-hidden min-w-0 rounded-sm transition-colors duration-1000 ${u?"border-amber-300/70 bg-amber-50/70 dark:border-amber-500/40 dark:bg-amber-500/10":i?"border-primary/50 bg-primary/5":"border-border"} ${l?"opacity-80":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.authorAgentId?e.jsx(Zi,{to:`/agents/${t.authorAgentId}`,className:"hover:underline",children:e.jsx(Ut,{name:((d=n==null?void 0:n.get(t.authorAgentId))==null?void 0:d.name)??t.authorAgentId.slice(0,8),size:"sm"})}):e.jsx(Ut,{name:"You",size:"sm"}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[u?e.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-400/60 bg-amber-100/70 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-amber-800 dark:border-amber-400/40 dark:bg-amber-500/20 dark:text-amber-200",children:"Queued"}):null,s&&!l?e.jsx(Vr,{slotTypes:["commentContextMenuItem"],entityType:"comment",context:{companyId:s,projectId:r??null,entityId:t.id,entityType:"comment",parentEntityId:t.issueId},className:"flex flex-wrap items-center gap-1.5",itemClassName:"inline-flex",missingBehavior:"placeholder"}):null,l?e.jsx("span",{className:"text-xs text-muted-foreground",children:u?"Queueing...":"Sending..."}):e.jsx("a",{href:`#comment-${t.id}`,className:"text-xs text-muted-foreground hover:text-foreground hover:underline transition-colors",children:js(t.createdAt)}),e.jsx(Kq,{text:t.body})]})]}),e.jsx(Xs,{className:"text-sm",children:t.body}),s&&!l?e.jsx("div",{className:"mt-2 space-y-2",children:e.jsx(Vr,{slotTypes:["commentAnnotation"],entityType:"comment",context:{companyId:s,projectId:r??null,entityId:t.id,entityType:"comment",parentEntityId:t.issueId},className:"space-y-2",itemClassName:"rounded-md",missingBehavior:"placeholder"})}):null,t.runId&&!l?e.jsx("div",{className:"mt-2 pt-2 border-t border-border/60",children:t.runAgentId?e.jsxs(Zi,{to:`/agents/${t.runAgentId}/runs/${t.runId}`,className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors",children:["run ",t.runId.slice(0,8)]}):e.jsxs("span",{className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground",children:["run ",t.runId.slice(0,8)]})}):null]},t.id)}const zq=c.memo(function({timeline:n,agentMap:s,companyId:r,projectId:a,highlightCommentId:o}){return n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No comments or runs yet."}):e.jsx("div",{className:"space-y-3",children:n.map(i=>{var u;if(i.kind==="run"){const d=i.run;return e.jsxs("div",{className:"border border-border bg-accent/20 p-3 overflow-hidden min-w-0 rounded-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Zi,{to:`/agents/${d.agentId}`,className:"hover:underline",children:e.jsx(Ut,{name:((u=s==null?void 0:s.get(d.agentId))==null?void 0:u.name)??d.agentId.slice(0,8),size:"sm"})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:js(d.startedAt??d.createdAt)})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Run"}),e.jsx(Zi,{to:`/agents/${d.agentId}/runs/${d.runId}`,className:"inline-flex items-center rounded-md border border-border bg-accent/40 px-2 py-1 font-mono text-muted-foreground hover:text-foreground hover:bg-accent/60 transition-colors",children:d.runId.slice(0,8)}),e.jsx(Dt,{status:d.status})]})]},`run:${d.runId}`)}const l=i.comment;return e.jsx(fN,{comment:l,agentMap:s,companyId:r,projectId:a,highlightCommentId:o},l.id)})})});function Wq({comments:t,queuedComments:n=[],linkedRuns:s=[],companyId:r,projectId:a,onAdd:o,agentMap:i,imageUploadHandler:l,onAttachImage:u,draftKey:d,liveRunSlot:m,enableReassign:p=!1,reassignOptions:x=[],currentAssigneeValue:f="",suggestedAssigneeValue:h,mentions:j,onInterruptQueued:b,interruptingQueuedRunId:g=null}){var V;const[y,v]=c.useState(""),[_,E]=c.useState(!0),[S,M]=c.useState(!1),[B,k]=c.useState(!1),L=h??f,[$,C]=c.useState(L),[I,K]=c.useState(null),T=c.useRef(null),z=c.useRef(null),w=c.useRef(null),F=fn(),A=c.useRef(!1),R=c.useMemo(()=>{const W=t.map(Y=>({kind:"comment",id:Y.id,createdAtMs:new Date(Y.createdAt).getTime(),comment:Y})),J=s.map(Y=>({kind:"run",id:Y.runId,createdAtMs:new Date(Y.startedAt??Y.createdAt).getTime(),run:Y}));return[...W,...J].sort((Y,de)=>Y.createdAtMs!==de.createdAtMs?Y.createdAtMs-de.createdAtMs:Y.kind===de.kind?Y.id.localeCompare(de.id):Y.kind==="comment"?-1:1)},[t,s]),Q=c.useMemo(()=>j||(i?Array.from(i.values()).filter(W=>W.status!=="terminated").map(W=>({id:`agent:${W.id}`,name:W.name,kind:"agent",agentId:W.id,agentIcon:W.icon})):[]),[i,j]);c.useEffect(()=>{d&&v(Fq(d))},[d]),c.useEffect(()=>{d&&(w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{qq(d,y)},Lq))},[y,d]),c.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),c.useEffect(()=>{C(L)},[L]),c.useEffect(()=>{const W=F.hash;if(!W.startsWith("#comment-")||t.length+n.length===0)return;const J=W.slice(9);if(A.current)return;const Y=document.getElementById(`comment-${J}`);if(Y){A.current=!0,K(J),Y.scrollIntoView({behavior:"smooth",block:"center"});const de=setTimeout(()=>K(null),3e3);return()=>clearTimeout(de)}},[F.hash,t,n]);async function H(){const W=y.trim();if(!W)return;const Y=p&&$!==f?Bq($):null,de=W;M(!0),v("");try{await o(de,_?!0:void 0,Y??void 0),d&&Uq(d),E(!0),C(L)}catch{v(fe=>Oq({currentBody:fe,submittedBody:de}))}finally{M(!1)}}async function U(W){var Y;const J=(Y=W.target.files)==null?void 0:Y[0];if(J){k(!0);try{if(l){const de=await l(J),Ce=`![${J.name.replace(/[[\]]/g,"\\$&")}](${de})`;v(le=>le?`${le}
|
|
112
|
+
|
|
113
|
+
${Ce}`:Ce)}else u&&await u(J)}finally{k(!1),z.current&&(z.current.value="")}}}const Z=!S&&!!y.trim();return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",R.length+n.length,")"]}),R.length>0?e.jsx(zq,{timeline:R,agentMap:i,companyId:r,projectId:a,highlightCommentId:I}):null,m,n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-[0.14em] text-amber-700 dark:text-amber-300",children:["Queued Comments (",n.length,")"]}),b&&((V=n[0])!=null&&V.queueTargetRunId)?e.jsx(G,{size:"sm",variant:"outline",className:"border-red-300 text-red-700 hover:bg-red-50 hover:text-red-800 dark:border-red-500/40 dark:text-red-300 dark:hover:bg-red-500/10",disabled:g===n[0].queueTargetRunId,onClick:()=>void b(n[0].queueTargetRunId),children:g===n[0].queueTargetRunId?"Interrupting...":"Interrupt"}):null]}),e.jsx("div",{className:"space-y-3",children:n.map(W=>e.jsx(fN,{comment:W,agentMap:i,companyId:r,projectId:a,highlightCommentId:I,queued:!0},W.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ps,{ref:T,value:y,onChange:v,placeholder:"Leave a comment...",mentions:Q,onSubmit:H,imageUploadHandler:l,contentClassName:"min-h-[60px] text-sm"}),e.jsxs("div",{className:"flex items-center justify-end gap-3",children:[(l||u)&&e.jsxs("div",{className:"mr-auto flex items-center gap-3",children:[e.jsx("input",{ref:z,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:U}),e.jsx(G,{variant:"ghost",size:"icon-sm",onClick:()=>{var W;return(W=z.current)==null?void 0:W.click()},disabled:B,title:"Attach image",children:e.jsx(ai,{className:"h-4 w-4"})})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:_,onChange:W=>E(W.target.checked),className:"rounded border-border"}),"Re-open"]}),p&&x.length>0&&e.jsx(ba,{value:$,options:x,placeholder:"Assignee",noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:C,className:"text-xs h-8",renderTriggerValue:W=>{if(!W)return e.jsx("span",{className:"text-muted-foreground",children:"Assignee"});const J=W.id.startsWith("agent:")?W.id.slice(6):null,Y=J?i==null?void 0:i.get(J):null;return e.jsxs(e.Fragment,{children:[Y?e.jsx(Cn,{icon:Y.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,e.jsx("span",{className:"truncate",children:W.label})]})},renderOption:W=>{if(!W.id)return e.jsx("span",{className:"truncate",children:W.label});const J=W.id.startsWith("agent:")?W.id.slice(6):null,Y=J?i==null?void 0:i.get(J):null;return e.jsxs(e.Fragment,{children:[Y?e.jsx(Cn,{icon:Y.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,e.jsx("span",{className:"truncate",children:W.label})]})}}),e.jsx(G,{size:"sm",disabled:!Z,onClick:H,children:S?"Posting...":"Comment"})]})]})]})}const Hq=900,Mg=/^[a-z0-9][a-z0-9_-]*$/,hN=t=>`crewspace:issue-document-folds:${t}`;function $g(t){if(typeof window>"u")return[];try{const n=window.localStorage.getItem(hN(t));if(!n)return[];const s=JSON.parse(n);return Array.isArray(s)?s.filter(r=>typeof r=="string"):[]}catch{return[]}}function Dg(t,n){typeof window>"u"||window.localStorage.setItem(hN(t),JSON.stringify(n))}function im(t,n){return e.jsx(Xs,{className:n,children:t})}function $a(t){return t.trim().toLowerCase()==="plan"}function Vq(t,n){return(t??"").trim().toLowerCase()===n.trim().toLowerCase()}function Qq(t){return t instanceof Qr&&t.status===409}function Gq(t,n){const s=new Blob([n],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=`${t}.md`,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(r)}function Jq(t){return t.createdByUserId?"board":t.createdByAgentId?"agent":"system"}function Zq(t,n){return!n||n.isNew||n.key!==t.key?!1:n.body!==t.body||(t.title??"")!==n.title}function Yq({issue:t,canDeleteDocuments:n,mentions:s,imageUploadHandler:r,extraActions:a}){const o=at(),i=fn(),[l,u]=c.useState(null),[d,m]=c.useState(null),[p,x]=c.useState(null),[f,h]=c.useState(null),[j,b]=c.useState(()=>$g(t.id)),[g,y]=c.useState(null),[v,_]=c.useState(null),[E,S]=c.useState(null),[M,B]=c.useState(null),[k,L]=c.useState({}),$=c.useRef(null),C=c.useRef(null),I=c.useRef(!1),{state:K,markDirty:T,reset:z,runSave:w}=aN(),{data:F}=oe({queryKey:N.issues.documents(t.id),queryFn:()=>nt.listDocuments(t.id)}),{data:A,isFetching:R}=oe({queryKey:M?N.issues.documentRevisions(t.id,M):["issues","document-revisions",t.id,"__idle__"],queryFn:async()=>M?nt.listDocumentRevisions(t.id,M):[],enabled:!!M}),Q=c.useCallback(()=>{o.invalidateQueries({queryKey:N.issues.detail(t.id)}),o.invalidateQueries({queryKey:N.issues.documents(t.id)}),o.invalidateQueries({predicate:ee=>Array.isArray(ee.queryKey)&&ee.queryKey[0]==="issues"&&ee.queryKey[1]==="document-revisions"&&ee.queryKey[2]===t.id})},[t.id,o]),H=ge({mutationFn:async ee=>nt.upsertDocument(t.id,ee.key,{title:$a(ee.key)?null:ee.title.trim()||null,format:"markdown",body:ee.body,baseRevisionId:ee.baseRevisionId})}),U=ge({mutationFn:ee=>nt.deleteDocument(t.id,ee),onSuccess:()=>{m(null),u(null),Q()},onError:ee=>{m(ee instanceof Error?ee.message:"Failed to delete document")}}),Z=ge({mutationFn:({key:ee,revisionId:me})=>nt.restoreDocumentRevision(t.id,ee,me),onSuccess:(ee,me)=>{L(ye=>({...ye,[me.key]:null})),x(ye=>(ye==null?void 0:ye.key)===me.key?null:ye),h(ye=>(ye==null?void 0:ye.key)===me.key?null:ye),de(),m(null),Q()},onError:ee=>{m(ee instanceof Error?ee.message:"Failed to restore document revision")}}),V=c.useMemo(()=>[...F??[]].sort((ee,me)=>ee.key==="plan"&&me.key!=="plan"?-1:ee.key!=="plan"&&me.key==="plan"?1:new Date(me.updatedAt).getTime()-new Date(ee.updatedAt).getTime()),[F]),W=V.some(ee=>ee.key==="plan"),J=V.length===0&&!t.legacyPlanDocument,Y=p!=null&&p.isNew&&p.key.trim().length>0&&!Mg.test(p.key.trim())?"Use lowercase letters, numbers, -, or _, and start with a letter or number.":null,de=c.useCallback(()=>{y(null),z()},[z]),fe=c.useCallback(ee=>{y(ee),T()},[T]),Ce=()=>{de(),h(null),x({key:"",title:"",body:"",baseRevisionId:null,isNew:!0}),m(null)},le=ee=>{const me=V.find(Ke=>Ke.key===ee);if(!me)return;const ye=(f==null?void 0:f.key)===ee?f.localDraft:null;b(Ke=>Ke.filter(qe=>qe!==ee)),de(),h(Ke=>(Ke==null?void 0:Ke.key)===ee?Ke:null),x({key:(ye==null?void 0:ye.key)??me.key,title:(ye==null?void 0:ye.title)??me.title??"",body:(ye==null?void 0:ye.body)??me.body,baseRevisionId:(ye==null?void 0:ye.baseRevisionId)??me.latestRevisionId,isNew:!1}),m(null)},Re=()=>{$.current&&clearTimeout($.current),de(),h(null),x(null),m(null)},Pe=c.useCallback(async(ee,me)=>{if(!ee||H.isPending)return!1;const ye=ee.key.trim().toLowerCase(),Ke=ee.body.trim(),qe=ee.title.trim(),se=(f==null?void 0:f.key)===ye?f:null;if(se&&!(me!=null&&me.overrideConflict))return me!=null&&me.trackAutosave&&de(),!1;if(!ye||!Ke)return ee.isNew?m("Document key and body are required"):Ke||m("Document body cannot be empty"),me!=null&&me.trackAutosave&&de(),!1;if(!Mg.test(ye))return m("Document key must start with a letter or number and use only lowercase letters, numbers, -, or _."),me!=null&&me.trackAutosave&&de(),!1;const ce=V.find(ae=>ae.key===ye);if(!ee.isNew&&ce&&ce.body===ee.body&&(ce.title??"")===ee.title)return me!=null&&me.clearAfterSave&&x(ae=>(ae==null?void 0:ae.key)===ye?null:ae),me!=null&&me.trackAutosave&&de(),!0;const Te=async()=>{const ae=await H.mutateAsync({...ee,key:ye,title:$a(ye)?"":qe,body:ee.body,baseRevisionId:me!=null&&me.overrideConflict?(se==null?void 0:se.serverDocument.latestRevisionId)??ee.baseRevisionId:ee.baseRevisionId});m(null),h(je=>(je==null?void 0:je.key)===ye?null:je),x(je=>!je||je.key!==ye?je:me!=null&&me.clearAfterSave?null:{key:ae.key,title:ae.title??"",body:ae.body,baseRevisionId:ae.latestRevisionId,isNew:!1}),Q()};try{return me!=null&&me.trackAutosave?(y(ye),await w(Te)):await Te(),!0}catch(ae){if(Qq(ae))try{const je=await nt.getDocument(t.id,ye);return h({key:ye,serverDocument:je,localDraft:{key:ye,title:$a(ye)?"":qe,body:ee.body,baseRevisionId:ee.baseRevisionId,isNew:!1},showRemote:!0}),b(ke=>ke.filter(Xe=>Xe!==ye)),m(null),de(),!1}catch{return m("Document changed remotely and the latest version could not be loaded"),!1}return m(ae instanceof Error?ae.message:"Failed to save document"),!1}},[f,Q,t.id,de,w,V,H]),Fe=c.useCallback(ee=>{if((f==null?void 0:f.key)!==ee)return;const me=f.serverDocument;x({key:me.key,title:me.title??"",body:me.body,baseRevisionId:me.latestRevisionId,isNew:!1}),h(null),de(),m(null)},[f,de]),pe=c.useCallback(async ee=>{if((f==null?void 0:f.key)!==ee)return;const me=p&&p.key===ee&&!p.isNew?p:f.localDraft;await Pe({...me,baseRevisionId:f.serverDocument.latestRevisionId},{clearAfterSave:!1,trackAutosave:!0,overrideConflict:!0})},[Pe,f,p]),Le=c.useCallback(ee=>{(f==null?void 0:f.key)===ee&&(x(f.localDraft),h(me=>(me==null?void 0:me.key)===ee?{...me,showRemote:!1}:me),m(null))},[f]),q=c.useCallback(async(ee,me)=>{try{await navigator.clipboard.writeText(me),_(ee),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{_(ye=>ye===ee?null:ye)},1400)}catch{m("Could not copy document")}},[]),D=c.useCallback(ee=>{const me=o.getQueryData(N.issues.documentRevisions(t.id,ee));return me||(M===ee?A??[]:[])},[A,t.id,o,M]),ie=c.useCallback(ee=>{L(me=>({...me,[ee]:null})),m(null)},[]),Ie=c.useCallback((ee,me)=>{const Ke=D(ee.key).find(qe=>qe.id===me);if(Ke){if(Ke.id===ee.latestRevisionId){ie(ee.key);return}if((f==null?void 0:f.key)===ee.key||Zq(ee,p)){m("Save or cancel your local changes before viewing an older revision.");return}de(),x(qe=>(qe==null?void 0:qe.key)===ee.key?null:qe),h(qe=>(qe==null?void 0:qe.key)===ee.key?null:qe),b(qe=>qe.filter(se=>se!==ee.key)),L(qe=>({...qe,[ee.key]:Ke.id})),m(null)}},[f,p,D,de,ie]),ue=async ee=>{ee.currentTarget.contains(ee.relatedTarget)||($.current&&clearTimeout($.current),await Pe(p,{clearAfterSave:!0,trackAutosave:!0}))},Be=async ee=>{if(ee.key==="Escape"){ee.preventDefault(),Re();return}(ee.metaKey||ee.ctrlKey)&&ee.key==="Enter"&&(ee.preventDefault(),$.current&&clearTimeout($.current),await Pe(p,{clearAfterSave:!1,trackAutosave:!0}))};c.useEffect(()=>{b($g(t.id))},[t.id]),c.useEffect(()=>{I.current=!1},[t.id,i.hash]),c.useEffect(()=>{const ee=new Set(V.map(me=>me.key));b(me=>{const ye=me.filter(Ke=>ee.has(Ke));return ye.length!==me.length&&Dg(t.id,ye),ye})},[t.id,V]),c.useEffect(()=>{Dg(t.id,j)},[j,t.id]),c.useEffect(()=>{if(!f)return;const ee=V.find(me=>me.key===f.key);!ee||ee.latestRevisionId===f.serverDocument.latestRevisionId||h(me=>(me==null?void 0:me.key)===ee.key?{...me,serverDocument:ee}:me)},[f,V]),c.useEffect(()=>{const ee=i.hash;if(!ee.startsWith("#document-"))return;const me=decodeURIComponent(ee.slice(10));if(!(V.some(se=>se.key===me)||me==="plan"&&!!t.legacyPlanDocument)||I.current)return;b(se=>se.filter(ce=>ce!==me));const Ke=document.getElementById(`document-${me}`);if(!Ke)return;I.current=!0,S(me),Ke.scrollIntoView({behavior:"smooth",block:"center"});const qe=setTimeout(()=>S(se=>se===me?null:se),3e3);return()=>clearTimeout(qe)},[t.legacyPlanDocument,i.hash,V]),c.useEffect(()=>()=>{$.current&&clearTimeout($.current),C.current&&clearTimeout(C.current)},[]),c.useEffect(()=>{if(!p||p.isNew||(f==null?void 0:f.key)===p.key)return;const ee=V.find(ye=>ye.key===p.key);if(!ee)return;if(!(ee.body!==p.body||(ee.title??"")!==p.title)){K!=="saved"&&de();return}return fe(p.key),$.current&&clearTimeout($.current),$.current=setTimeout(()=>{Pe(p,{clearAfterSave:!1,trackAutosave:!0})},Hq),()=>{$.current&&clearTimeout($.current)}},[K,Pe,f,p,fe,de,V]);const be="mt-3 overflow-hidden rounded-md",he="",Se="crewspace-edit-in-place-content min-h-[220px] text-[15px] leading-7",we=ee=>{b(me=>me.includes(ee)?me.filter(ye=>ye!==ee):[...me,ee])};return e.jsxs("div",{className:"space-y-3",children:[J&&!(p!=null&&p.isNew)?e.jsxs("div",{className:"flex items-center justify-end gap-2 min-w-0",children:[a,e.jsxs(G,{variant:"outline",size:"sm",onClick:Ce,className:"shrink-0",children:[e.jsx(Ot,{className:"mr-1.5 h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"New document"}),e.jsx("span",{className:"sm:hidden",children:"New"})]})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground shrink-0",children:"Documents"}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a,e.jsxs(G,{variant:"outline",size:"sm",onClick:Ce,className:"shrink-0",children:[e.jsx(Ot,{className:"mr-1.5 h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"New document"}),e.jsx("span",{className:"sm:hidden",children:"New"})]})]})]}),d&&e.jsx("p",{className:"text-xs text-destructive",children:d}),(p==null?void 0:p.isNew)&&e.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-accent/10 p-3",onBlurCapture:ue,onKeyDown:Be,children:[e.jsx(Xt,{autoFocus:!0,value:p.key,onChange:ee=>x(me=>me&&{...me,key:ee.target.value.toLowerCase()}),placeholder:"Document key"}),Y&&e.jsx("p",{className:"text-xs text-destructive",children:Y}),!$a(p.key)&&e.jsx(Xt,{value:p.title,onChange:ee=>x(me=>me&&{...me,title:ee.target.value}),placeholder:"Optional title"}),e.jsx(ps,{value:p.body,onChange:ee=>x(me=>me&&{...me,body:ee}),placeholder:"Markdown body",bordered:!1,className:"bg-transparent",contentClassName:"min-h-[220px] text-[15px] leading-7",mentions:s,imageUploadHandler:r,onSubmit:()=>void Pe(p,{clearAfterSave:!1,trackAutosave:!1})}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:Re,children:[e.jsx(zt,{className:"mr-1.5 h-3.5 w-3.5"}),"Cancel"]}),e.jsx(G,{size:"sm",onClick:()=>void Pe(p,{clearAfterSave:!1,trackAutosave:!1}),disabled:H.isPending,children:H.isPending?"Saving...":"Create document"})]})]}),!W&&t.legacyPlanDocument?e.jsxs("div",{id:"document-plan",className:O("rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 transition-colors duration-1000",E==="plan"&&"border-primary/50 bg-primary/5"),children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(Id,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"rounded-full border border-amber-500/30 px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-amber-700 dark:text-amber-300",children:"PLAN"})]}),e.jsx("div",{className:he,children:im(t.legacyPlanDocument.body,Se)})]}):null,e.jsx("div",{className:"space-y-3",children:V.map(ee=>{var It;const me=(p==null?void 0:p.key)===ee.key&&!p.isNew?p:null,ye=(f==null?void 0:f.key)===ee.key?f:null,Ke=j.includes(ee.key),qe=D(ee.key),se=k[ee.key]??null,ce=se?qe.find(Ue=>Ue.id===se)??null:null,Te=!!ce,ae=ce?ce.title??"":(me==null?void 0:me.title)??ee.title??"",je=(ce==null?void 0:ce.body)??(me==null?void 0:me.body)??ee.body,ke=(ce==null?void 0:ce.revisionNumber)??ee.latestRevisionNumber,Xe=(ce==null?void 0:ce.createdAt)??ee.updatedAt,lt=!$a(ee.key)&&!!ae.trim()&&!Vq(ae,ee.key);return e.jsxs("div",{id:`document-${ee.key}`,className:O("rounded-lg border border-border p-3 transition-colors duration-1000",E===ee.key&&"border-primary/50 bg-primary/5"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("button",{type:"button",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground",onClick:()=>we(ee.key),"aria-label":Ke?`Expand ${ee.key} document`:`Collapse ${ee.key} document`,"aria-expanded":!Ke,children:Ke?e.jsx(sn,{className:"h-3.5 w-3.5"}):e.jsx(rn,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"shrink-0 rounded-full border border-border px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:ee.key}),e.jsxs(gl,{open:M===ee.key,onOpenChange:Ue=>B(Ue?ee.key:null),children:[e.jsx(bl,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:O("h-auto px-1.5 py-0 text-[11px] font-normal text-muted-foreground hover:text-foreground",Te&&"text-amber-300 hover:text-amber-200"),children:["rev ",ke,e.jsx(rn,{className:"h-3 w-3"})]})}),e.jsxs(yl,{align:"start",className:"w-72",children:[e.jsx(qL,{children:"Revision history"}),M===ee.key&&R&&qe.length===0?e.jsx(Os,{disabled:!0,children:"Loading revisions..."}):qe.length>0?e.jsx(LL,{value:se??ee.latestRevisionId??"",children:qe.map(Ue=>{const pt=Ue.id===ee.latestRevisionId;return e.jsx(FL,{value:Ue.id,onSelect:()=>Ie(ee,Ue.id),className:"items-start",children:e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:["rev ",Ue.revisionNumber]}),pt?e.jsx("span",{className:"rounded-full border border-border px-1.5 py-0.5 text-[10px] uppercase tracking-[0.12em] text-muted-foreground",children:"Current"}):null]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[os(Ue.createdAt)," • ",Jq(Ue)]})]})},Ue.id)})}):e.jsx(Os,{disabled:!0,children:"No revisions yet"})]})]}),e.jsxs("a",{href:`#document-${encodeURIComponent(ee.key)}`,className:"truncate text-[11px] text-muted-foreground transition-colors hover:text-foreground hover:underline",children:["updated ",os(Xe)]})]}),lt&&e.jsx("p",{className:"mt-2 text-sm font-medium",children:ae})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(G,{variant:"ghost",size:"icon-xs",className:O("text-muted-foreground transition-colors",v===ee.key&&"text-foreground"),title:v===ee.key?"Copied":"Copy document",onClick:()=>void q(ee.key,je),children:v===ee.key?e.jsx(Nn,{className:"h-3.5 w-3.5"}):e.jsx(_s,{className:"h-3.5 w-3.5"})}),e.jsxs(gl,{children:[e.jsx(bl,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",title:"Document actions",children:e.jsx(xi,{className:"h-3.5 w-3.5"})})}),e.jsxs(yl,{align:"end",children:[e.jsxs(Os,{onClick:()=>Gq(ee.key,je),children:[e.jsx(ei,{className:"h-3.5 w-3.5"}),"Download document"]}),n?e.jsx(au,{}):null,n?e.jsxs(Os,{variant:"destructive",onClick:()=>u(ee.key),children:[e.jsx(Ls,{className:"h-3.5 w-3.5"}),"Delete document"]}):null]})]})]})]}),Ke?null:e.jsxs("div",{className:"mt-3 space-y-3",onFocusCapture:Te?void 0:()=>{me||le(ee.key)},onBlurCapture:Te?void 0:async Ue=>{me&&await ue(Ue)},onKeyDown:Te?void 0:async Ue=>{me&&await Be(Ue)},children:[Te&&ce&&e.jsx("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-sm font-medium text-amber-200",children:["Viewing revision ",ce.revisionNumber]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is a historical preview. Restoring it creates a new latest revision and keeps history append-only."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>ie(ee.key),children:"Return to latest"}),e.jsx(G,{size:"sm",onClick:()=>Z.mutate({key:ee.key,revisionId:ce.id}),disabled:Z.isPending,children:Z.isPending&&((It=Z.variables)==null?void 0:It.key)===ee.key?"Restoring...":"Restore this revision"})]})]})}),ye&&!Te&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-200",children:"Out of date"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This document changed while you were editing. Your local draft is preserved and autosave is paused."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>h(Ue=>(Ue==null?void 0:Ue.key)===ee.key?{...Ue,showRemote:!Ue.showRemote}:Ue),children:ye.showRemote?"Hide remote":"Review remote"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>Le(ee.key),children:"Keep my draft"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>Fe(ee.key),children:"Reload remote"}),e.jsx(G,{size:"sm",onClick:()=>void pe(ee.key),disabled:H.isPending,children:H.isPending?"Saving...":"Overwrite remote"})]})]}),ye.showRemote&&e.jsxs("div",{className:"mt-3 rounded-md border border-border/70 bg-background/60 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:["Remote revision ",ye.serverDocument.latestRevisionNumber]}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:["updated ",os(ye.serverDocument.updatedAt)]})]}),!$a(ee.key)&&ye.serverDocument.title?e.jsx("p",{className:"mb-2 text-sm font-medium",children:ye.serverDocument.title}):null,im(ye.serverDocument.body,"text-[14px] leading-7")]})]}),me&&!$a(ee.key)&&!Te&&e.jsx(Xt,{value:me.title,onChange:Ue=>{fe(ee.key),x(pt=>pt&&{...pt,title:Ue.target.value})},placeholder:"Optional title"}),e.jsx("div",{className:`${be} ${he} ${me||Te?"":"hover:bg-accent/10"}`,children:Te?e.jsx("div",{className:"rounded-md border border-amber-500/20 bg-background/50 p-3",children:im(je,Se)}):e.jsx(ps,{value:je,onChange:Ue=>{fe(ee.key),x(pt=>pt&&pt.key===ee.key&&!pt.isNew?{...pt,body:Ue}:{key:ee.key,title:ee.title??"",body:Ue,baseRevisionId:ee.latestRevisionId,isNew:!1})},placeholder:"Markdown body",bordered:!1,className:"bg-transparent",contentClassName:Se,mentions:s,imageUploadHandler:r,onSubmit:()=>void Pe(me??p,{clearAfterSave:!1,trackAutosave:!0})})}),e.jsx("div",{className:"flex min-h-4 items-center justify-end px-1",children:e.jsx("span",{className:`text-[11px] transition-opacity duration-150 ${Te||ye?"text-amber-300":K==="error"?"text-destructive":"text-muted-foreground"} ${me||Te?"opacity-100":"opacity-0"}`,children:Te?"Viewing historical revision":me?ye?"Out of date":g===ee.key?K==="saving"?"Autosaving...":K==="saved"?"Saved":K==="error"?"Could not save":"":"":""})})]}),l===ee.key&&e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-md border border-destructive/20 bg-destructive/5 px-4 py-3",children:[e.jsx("p",{className:"text-sm text-destructive font-medium",children:"Delete this document? This cannot be undone."}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>u(null),disabled:U.isPending,children:"Cancel"}),e.jsx(G,{variant:"destructive",size:"sm",onClick:()=>U.mutate(ee.key),disabled:U.isPending,children:U.isPending?"Deleting...":"Delete"})]})]})]},ee.id)})})]})}function Xq(t){var n,s,r,a,o;return t?((n=t.executionWorkspacePolicy)==null?void 0:n.defaultProjectWorkspaceId)??((r=(s=t.workspaces)==null?void 0:s.find(i=>i.isPrimary))==null?void 0:r.id)??((o=(a=t.workspaces)==null?void 0:a[0])==null?void 0:o.id)??null:null}function eU(t){var s;const n=(s=t==null?void 0:t.executionWorkspacePolicy)!=null&&s.enabled?t.executionWorkspacePolicy.defaultMode:null;return n==="isolated_workspace"||n==="operator_branch"?n:n==="adapter_default"?"agent_default":"shared_workspace"}function sr({label:t,children:n}){return e.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-20",children:t}),e.jsx("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:n})]})}function lm({inline:t,label:n,open:s,onOpenChange:r,triggerContent:a,triggerClassName:o,popoverClassName:i,popoverAlign:l="end",extra:u,children:d}){const m=O("inline-flex items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",o);return t?e.jsxs("div",{children:[e.jsxs(sr,{label:n,children:[e.jsx("button",{className:m,onClick:()=>r(!s),children:a}),u]}),s&&e.jsx("div",{className:O("rounded-md border border-border bg-popover p-1 mb-2",i),children:d})]}):e.jsxs(sr,{label:n,children:[e.jsxs(Ht,{open:s,onOpenChange:r,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:m,children:a})}),e.jsx(Qt,{className:O("p-1",i),align:l,collisionPadding:16,children:d})]}),u]})}function Og({issue:t,onUpdate:n,inline:s}){var Ce,le,Re,Pe,Fe,pe,Le;const{selectedCompanyId:r}=et(),a=at(),o=t.companyId??r,[i,l]=c.useState(!1),[u,d]=c.useState(""),[m,p]=c.useState(!1),[x,f]=c.useState(""),[h,j]=c.useState(!1),[b,g]=c.useState(""),[y,v]=c.useState(""),[_,E]=c.useState("#6366f1"),{data:S}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),M=((Ce=S==null?void 0:S.user)==null?void 0:Ce.id)??((le=S==null?void 0:S.session)==null?void 0:le.userId),{data:B}=oe({queryKey:N.agents.list(o),queryFn:()=>We.list(o),enabled:!!o}),{data:k}=oe({queryKey:N.projects.list(o),queryFn:()=>en.list(o),enabled:!!o}),L=c.useMemo(()=>(k??[]).filter(q=>!q.archivedAt||q.id===t.projectId),[k,t.projectId]),{orderedProjects:$}=$l({projects:L,companyId:o,userId:M}),{data:C}=oe({queryKey:N.issues.labels(o),queryFn:()=>nt.listLabels(o),enabled:!!o}),I=ge({mutationFn:q=>nt.createLabel(o,q),onSuccess:async q=>{await a.invalidateQueries({queryKey:N.issues.labels(o)}),n({labelIds:[...t.labelIds??[],q.id]}),v("")}}),K=ge({mutationFn:q=>nt.deleteLabel(q),onSuccess:()=>{a.invalidateQueries({queryKey:N.issues.labels(o)}),a.invalidateQueries({queryKey:N.issues.list(o)}),a.invalidateQueries({queryKey:N.issues.detail(t.id)})}}),T=q=>{const D=t.labelIds??[],ie=D.includes(q)?D.filter(Ie=>Ie!==q):[...D,q];n({labelIds:ie})},z=q=>{if(!q||!B)return null;const D=B.find(ie=>ie.id===q);return(D==null?void 0:D.name)??q.slice(0,8)},w=q=>{if(!q)return(q==null?void 0:q.slice(0,8))??"None";const D=$.find(ie=>ie.id===q);return(D==null?void 0:D.name)??q.slice(0,8)};t.projectId&&$.find(q=>q.id===t.projectId);const F=q=>{if(!q)return null;const D=(k==null?void 0:k.find(ie=>ie.id===q))??null;return D?El(D):`/projects/${q}`},A=c.useMemo(()=>Ol(),[i]),R=c.useMemo(()=>eu((B??[]).filter(q=>q.status!=="terminated"),A),[B,A]),Q=t.assigneeAgentId?B==null?void 0:B.find(q=>q.id===t.assigneeAgentId):null,H=q=>Gm(q,M),U=H(t.assigneeUserId),Z=H(t.createdByUserId),V=(t.labels??[]).length>0?e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[(t.labels??[]).slice(0,3).map(q=>e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium border",style:{borderColor:q.color,backgroundColor:`${q.color}22`,color:Yd(q.color,.13)},children:q.name},q.id)),(t.labels??[]).length>3&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",(t.labels??[]).length-3]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Gb,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"No labels"})]}),W=e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search labels...",value:b,onChange:q=>g(q.target.value),autoFocus:!s}),e.jsx("div",{className:"max-h-44 overflow-y-auto overscroll-contain space-y-0.5",children:(C??[]).filter(q=>b.trim()?q.name.toLowerCase().includes(b.toLowerCase()):!0).map(q=>{const D=(t.labelIds??[]).includes(q.id);return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{className:O("flex items-center gap-2 flex-1 px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",D&&"bg-accent"),onClick:()=>T(q.id),children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:q.color}}),e.jsx("span",{className:"truncate",children:q.name})]}),e.jsx("button",{type:"button",className:"p-1 text-muted-foreground hover:text-destructive rounded",onClick:()=>K.mutate(q.id),title:`Delete ${q.name}`,children:e.jsx(Ls,{className:"h-3 w-3"})})]},q.id)})}),e.jsxs("div",{className:"mt-2 border-t border-border pt-2 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{className:"h-7 w-7 p-0 rounded bg-transparent",type:"color",value:_,onChange:q=>E(q.target.value)}),e.jsx("input",{className:"flex-1 px-2 py-1.5 text-xs bg-transparent outline-none rounded placeholder:text-muted-foreground/50",placeholder:"New label",value:y,onChange:q=>v(q.target.value)})]}),e.jsxs("button",{className:"flex items-center justify-center gap-1.5 w-full px-2 py-1.5 text-xs rounded border border-border hover:bg-accent/50 disabled:opacity-50",disabled:!y.trim()||I.isPending,onClick:()=>I.mutate({name:y.trim(),color:_}),children:[e.jsx(Ot,{className:"h-3 w-3"}),I.isPending?"Creating…":"Create label"]})]})]}),J=Q?e.jsx(Ut,{name:Q.name,size:"sm"}):U?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:U})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Unassigned"})]}),Y=e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search assignees...",value:u,onChange:q=>d(q.target.value),autoFocus:!s}),e.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!t.assigneeAgentId&&!t.assigneeUserId&&"bg-accent"),onClick:()=>{n({assigneeAgentId:null,assigneeUserId:null}),l(!1)},children:"No assignee"}),M&&e.jsxs("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",t.assigneeUserId===M&&"bg-accent"),onClick:()=>{n({assigneeAgentId:null,assigneeUserId:M}),l(!1)},children:[e.jsx(Ns,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),"Assign to me"]}),t.createdByUserId&&t.createdByUserId!==M&&e.jsxs("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",t.assigneeUserId===t.createdByUserId&&"bg-accent"),onClick:()=>{n({assigneeAgentId:null,assigneeUserId:t.createdByUserId}),l(!1)},children:[e.jsx(Ns,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),Z?`Assign to ${Z}`:"Assign to requester"]}),R.filter(q=>{if(!u.trim())return!0;const D=u.toLowerCase();return q.name.toLowerCase().includes(D)}).map(q=>e.jsxs("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",q.id===t.assigneeAgentId&&"bg-accent"),onClick:()=>{Xd(q.id),n({assigneeAgentId:q.id,assigneeUserId:null}),l(!1)},children:[e.jsx(Cn,{icon:q.icon,className:"shrink-0 h-3 w-3 text-muted-foreground"}),q.name]},q.id))]})]}),de=t.projectId?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:((Re=$.find(q=>q.id===t.projectId))==null?void 0:Re.color)??"#6366f1"}}),e.jsx("span",{className:"text-sm truncate",children:w(t.projectId)})]}):e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"No project"})]}),fe=e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search projects...",value:x,onChange:q=>f(q.target.value),autoFocus:!s}),e.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",!t.projectId&&"bg-accent"),onClick:()=>{n({projectId:null,projectWorkspaceId:null,executionWorkspaceId:null,executionWorkspacePreference:null,executionWorkspaceSettings:null}),p(!1)},children:"No project"}),$.filter(q=>{if(!x.trim())return!0;const D=x.toLowerCase();return q.name.toLowerCase().includes(D)}).map(q=>e.jsxs("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",q.id===t.projectId&&"bg-accent"),onClick:()=>{var ie;const D=eU(q);n({projectId:q.id,projectWorkspaceId:Xq(q),executionWorkspaceId:null,executionWorkspacePreference:D,executionWorkspaceSettings:(ie=q.executionWorkspacePolicy)!=null&&ie.enabled?{mode:D}:null}),p(!1)},children:[e.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:q.color??"#6366f1"}}),q.name]},q.id))]})]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(sr,{label:"Status",children:e.jsx(Pn,{status:t.status,onChange:q=>n({status:q}),showLabel:!0})}),e.jsx(sr,{label:"Priority",children:e.jsx(vs,{priority:t.priority,onChange:q=>n({priority:q}),showLabel:!0})}),e.jsx(lm,{inline:s,label:"Labels",open:h,onOpenChange:q=>{j(q),q||g("")},triggerContent:V,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-64",children:W}),e.jsx(lm,{inline:s,label:"Assignee",open:i,onOpenChange:q=>{l(q),q||d("")},triggerContent:J,popoverClassName:"w-52",extra:t.assigneeAgentId?e.jsx(Oe,{to:`/agents/${t.assigneeAgentId}`,className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:q=>q.stopPropagation(),children:e.jsx(ti,{className:"h-3 w-3"})}):void 0,children:Y}),e.jsx(lm,{inline:s,label:"Project",open:m,onOpenChange:q=>{p(q),q||f("")},triggerContent:de,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-fit min-w-[11rem]",extra:t.projectId?e.jsx(Oe,{to:F(t.projectId),className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:q=>q.stopPropagation(),children:e.jsx(ti,{className:"h-3 w-3"})}):void 0,children:fe}),t.parentId&&e.jsx(sr,{label:"Parent",children:e.jsx(Oe,{to:`/issues/${((Fe=(Pe=t.ancestors)==null?void 0:Pe[0])==null?void 0:Fe.identifier)??t.parentId}`,className:"text-sm hover:underline",children:((Le=(pe=t.ancestors)==null?void 0:pe[0])==null?void 0:Le.title)??t.parentId.slice(0,8)})}),t.requestDepth>0&&e.jsx(sr,{label:"Depth",children:e.jsx("span",{className:"text-sm font-mono",children:t.requestDepth})})]}),e.jsx(yn,{}),e.jsxs("div",{className:"space-y-1",children:[(t.createdByAgentId||t.createdByUserId)&&e.jsx(sr,{label:"Created by",children:t.createdByAgentId?e.jsx(Oe,{to:`/agents/${t.createdByAgentId}`,className:"hover:underline",children:e.jsx(Ut,{name:z(t.createdByAgentId)??t.createdByAgentId.slice(0,8),size:"sm"})}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:Z??"User"})]})}),t.startedAt&&e.jsx(sr,{label:"Started",children:e.jsx("span",{className:"text-sm",children:xs(t.startedAt)})}),t.completedAt&&e.jsx(sr,{label:"Completed",children:e.jsx("span",{className:"text-sm",children:xs(t.completedAt)})}),e.jsx(sr,{label:"Created",children:e.jsx("span",{className:"text-sm",children:xs(t.createdAt)})}),e.jsx(sr,{label:"Updated",children:e.jsx("span",{className:"text-sm",children:as(t.updatedAt)})})]})]})}const tU=[{value:"shared_workspace",label:"Project default"},{value:"isolated_workspace",label:"New isolated workspace"},{value:"reuse_existing",label:"Reuse existing workspace"}];function nU(t){return t==="isolated_workspace"||t==="operator_branch"||t==="shared_workspace"?t:t==="adapter_managed"||t==="cloud_sandbox"?"agent_default":"shared_workspace"}function sU(t){var s,r;const n=((s=t.currentExecutionWorkspace)==null?void 0:s.mode)??((r=t.executionWorkspaceSettings)==null?void 0:r.mode)??t.executionWorkspacePreference;return!!(t.executionWorkspaceId&&(n==="isolated_workspace"||n==="operator_branch"))}function rU(t){var s;const n=(s=t==null?void 0:t.executionWorkspacePolicy)!=null&&s.enabled?t.executionWorkspacePolicy.defaultMode:null;return n==="isolated_workspace"||n==="operator_branch"?n:n==="adapter_default"?"agent_default":"shared_workspace"}function Ui({text:t}){const n=[],s=t.split(new RegExp("(?<=[\\/-])"));for(let r=0;r<s.length;r++)r>0&&n.push(e.jsx("wbr",{},r)),n.push(s[r]);return e.jsx(e.Fragment,{children:n})}function cm({value:t,label:n,mono:s}){const[r,a]=c.useState(!1),o=c.useRef(void 0),i=c.useCallback(async()=>{try{await navigator.clipboard.writeText(t),a(!0),clearTimeout(o.current),o.current=setTimeout(()=>a(!1),1500)}catch{}},[t]);return e.jsxs("span",{className:"inline-flex items-center gap-1 group/copy",children:[n&&e.jsx("span",{className:"text-muted-foreground",children:n}),e.jsx("span",{className:O("min-w-0",s&&"font-mono"),style:{overflowWrap:"anywhere"},children:e.jsx(Ui,{text:t})}),e.jsx("button",{type:"button",className:"shrink-0 p-0.5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground opacity-0 group-hover/copy:opacity-100 focus:opacity-100",onClick:i,title:r?"Copied!":"Copy",children:r?e.jsx(Nn,{className:"h-3 w-3 text-green-500"}):e.jsx(_s,{className:"h-3 w-3"})})]})}function aU(t){switch(t){case"isolated_workspace":return"Isolated workspace";case"operator_branch":return"Operator branch";case"cloud_sandbox":return"Cloud sandbox";case"adapter_managed":return"Adapter managed";default:return"Workspace"}}function oU(t,n){switch(t){case"isolated_workspace":return"New isolated workspace";case"reuse_existing":return(n==null?void 0:n.mode)==="isolated_workspace"?"Existing isolated workspace":"Reuse existing workspace";default:return"Project default"}}function iU(t){return!t.projectId||!t.projectWorkspaceId?null:Ud({id:t.projectId,urlKey:t.projectId},t.projectWorkspaceId)}function Lg(t){var s,r;const n=((s=t.workspace)==null?void 0:s.projectWorkspaceId)??t.issueProjectWorkspaceId??null;return((r=t.workspace)==null?void 0:r.mode)==="shared_workspace"?iU({projectId:t.projectId,projectWorkspaceId:n}):t.workspace?`/execution-workspaces/${t.workspace.id}`:null}function Fg(t){const n={active:"bg-green-500/15 text-green-700 dark:text-green-400",idle:"bg-muted text-muted-foreground",in_review:"bg-blue-500/15 text-blue-700 dark:text-blue-400",archived:"bg-muted text-muted-foreground"};return e.jsx("span",{className:O("text-[10px] px-1.5 py-0.5 rounded-full font-medium",n[t]??n.idle),children:t.replace(/_/g," ")})}function lU({issue:t,project:n,onUpdate:s}){var k,L;const{selectedCompanyId:r}=et(),a=t.companyId??r,[o,i]=c.useState(!1),{data:l}=oe({queryKey:N.instance.experimentalSettings,queryFn:()=>Rr.getExperimental()}),u=(l==null?void 0:l.enableIsolatedWorkspaces)===!0&&!!((k=n==null?void 0:n.executionWorkspacePolicy)!=null&&k.enabled),d=t.currentExecutionWorkspace,{data:m}=oe({queryKey:N.executionWorkspaces.list(a,{projectId:t.projectId??void 0,projectWorkspaceId:t.projectWorkspaceId??void 0,reuseEligible:!0}),queryFn:()=>or.list(a,{projectId:t.projectId??void 0,projectWorkspaceId:t.projectWorkspaceId??void 0,reuseEligible:!0}),enabled:!!a&&!!t.projectId&&o}),p=c.useMemo(()=>{const $=m??[],C=new Map;for(const I of $){const K=I.cwd??I.id,T=C.get(K);(!T||new Date(I.lastUsedAt)>new Date(T.lastUsedAt))&&C.set(K,I)}return Array.from(C.values())},[m]),x=p.find($=>$.id===t.executionWorkspaceId)??d??null,f=sU(t)?"reuse_existing":t.executionWorkspacePreference??((L=t.executionWorkspaceSettings)==null?void 0:L.mode)??rU(n),[h,j]=c.useState(f),[b,g]=c.useState(t.executionWorkspaceId??"");c.useEffect(()=>{o||(j(f),g(t.executionWorkspaceId??""))},[f,o,t.executionWorkspaceId]);const y=!!(d&&d.mode!=="shared_workspace"),v=p.find($=>$.id===b)??(b===t.executionWorkspaceId?x:null),_=Lg({projectId:n==null?void 0:n.id,issueProjectWorkspaceId:t.projectWorkspaceId,workspace:x}),E=Lg({projectId:n==null?void 0:n.id,issueProjectWorkspaceId:t.projectWorkspaceId,workspace:d}),S=h!=="reuse_existing"||b.length>0,M=c.useCallback(()=>{S&&(s({executionWorkspacePreference:h,executionWorkspaceId:h==="reuse_existing"&&b||null,executionWorkspaceSettings:{mode:h==="reuse_existing"?nU(v==null?void 0:v.mode):h}}),i(!1))},[S,v==null?void 0:v.mode,b,h,s]),B=c.useCallback(()=>{j(f),g(t.executionWorkspaceId??""),i(!1)},[f,t.executionWorkspaceId]);return!u||!n?null:e.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-foreground",children:[e.jsx(Yo,{className:"h-3.5 w-3.5 text-muted-foreground"}),y&&d?aU(d.mode):oU(f,x),Fg(d?d.status:"idle")]}),e.jsx("div",{className:"flex items-center gap-1",children:o?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground",onClick:B,children:[e.jsx(zt,{className:"h-3 w-3 mr-1"}),"Cancel"]}),e.jsx(G,{size:"sm",className:"h-6 px-2 text-xs",onClick:M,disabled:!S,children:"Save"})]}):e.jsxs(G,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground",onClick:()=>i(!0),children:[e.jsx(Cc,{className:"h-3 w-3 mr-1"}),"Edit"]})})]}),!o&&e.jsxs("div",{className:"space-y-1.5 text-xs",children:[(d==null?void 0:d.branchName)&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Yo,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx(cm,{value:d.branchName,mono:!0})]}),(d==null?void 0:d.cwd)&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(kl,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx(cm,{value:d.cwd,mono:!0})]}),(d==null?void 0:d.repoUrl)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx("span",{className:"text-[11px]",children:"Repo:"}),e.jsx(cm,{value:d.repoUrl,mono:!0})]}),!d&&e.jsx("div",{className:"text-muted-foreground",children:f==="isolated_workspace"?"A fresh isolated workspace will be created when this issue runs.":f==="reuse_existing"?"This issue will reuse an existing workspace when it runs.":"This issue will use the project default workspace configuration when it runs."}),f==="reuse_existing"&&x&&e.jsxs("div",{className:"text-muted-foreground",style:{overflowWrap:"anywhere"},children:["Reusing:"," ",_?e.jsx(Oe,{to:_,className:"hover:text-foreground hover:underline",children:e.jsx(Ui,{text:x.name})}):e.jsx(Ui,{text:x.name})]}),d&&E&&e.jsx("div",{className:"pt-0.5",children:e.jsx(Oe,{to:E,className:"text-[11px] text-muted-foreground hover:text-foreground hover:underline",children:"View workspace details →"})})]}),o&&e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:h,onChange:$=>{const C=$.target.value;j(C),C!=="reuse_existing"?g(""):!b&&t.executionWorkspaceId&&g(t.executionWorkspaceId)},children:tU.map($=>e.jsx("option",{value:$.value,children:$.value==="reuse_existing"&&(v==null?void 0:v.mode)==="isolated_workspace"?"Existing isolated workspace":$.label},$.value))}),h==="reuse_existing"&&e.jsxs("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:b,onChange:$=>{g($.target.value)},children:[e.jsx("option",{value:"",children:"Choose an existing workspace"}),p.map($=>e.jsxs("option",{value:$.id,children:[$.name," · ",$.status," · ",$.branchName??$.cwd??$.id.slice(0,8)]},$.id))]}),d&&e.jsx("div",{className:"text-[11px] text-muted-foreground space-y-0.5 pt-1 border-t border-border/50",children:e.jsxs("div",{style:{overflowWrap:"anywhere"},children:["Current:"," ",E?e.jsx(Oe,{to:E,className:"hover:text-foreground hover:underline",children:e.jsx(Ui,{text:d.name})}):e.jsx(Ui,{text:d.name})," · ",d.status]})})]})]})}function dm(t){return t?typeof t=="string"?t:t.toISOString():null}function cU(t){return t==="queued"||t==="running"}function gN({issueId:t,companyId:n}){const s=at(),[r,a]=c.useState(new Set),{data:o}=oe({queryKey:N.issues.liveRuns(t),queryFn:()=>Yt.liveRunsForIssue(t),enabled:!!t,refetchInterval:3e3}),{data:i}=oe({queryKey:N.issues.activeRun(t),queryFn:()=>Yt.activeRunForIssue(t),enabled:!!t,refetchInterval:3e3}),l=c.useMemo(()=>{const p=new Map;for(const x of o??[])p.set(x.id,x);return i&&p.set(i.id,{id:i.id,status:i.status,invocationSource:i.invocationSource,triggerDetail:i.triggerDetail,startedAt:dm(i.startedAt),finishedAt:dm(i.finishedAt),createdAt:dm(i.createdAt)??new Date().toISOString(),agentId:i.agentId,agentName:i.agentName,adapterType:i.adapterType,issueId:t}),[...p.values()].sort((x,f)=>new Date(f.createdAt).getTime()-new Date(x.createdAt).getTime())},[i,t,o]),{transcriptByRun:u,hasOutputForRun:d}=Fw({runs:l,companyId:n}),m=async p=>{a(x=>new Set(x).add(p));try{await Yt.cancel(p),s.invalidateQueries({queryKey:N.issues.liveRuns(t)}),s.invalidateQueries({queryKey:N.issues.activeRun(t)})}finally{a(x=>{const f=new Set(x);return f.delete(p),f})}};return l.length===0?null:e.jsxs("div",{className:"overflow-hidden rounded-xl border border-cyan-500/25 bg-background/80 shadow-[0_18px_50px_rgba(6,182,212,0.08)]",children:[e.jsxs("div",{className:"border-b border-border/60 bg-cyan-500/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700 dark:text-cyan-300",children:"Live Runs"}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"Streamed with the same transcript UI used on the full run detail page."})]}),e.jsx("div",{className:"divide-y divide-border/60",children:l.map(p=>{const x=cU(p.status),f=u.get(p.id)??[];return e.jsxs("section",{className:"px-4 py-4",children:[e.jsxs("div",{className:"mb-3 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Oe,{to:`/agents/${p.agentId}`,className:"inline-flex hover:underline",children:e.jsx(Ut,{name:p.agentName,size:"sm"})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Oe,{to:`/agents/${p.agentId}/runs/${p.id}`,className:"inline-flex items-center rounded-full border border-border/70 bg-background/70 px-2 py-1 font-mono hover:border-cyan-500/30 hover:text-foreground",children:p.id.slice(0,8)}),e.jsx(Dt,{status:p.status}),e.jsx("span",{children:js(p.startedAt??p.createdAt)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[x&&e.jsxs("button",{onClick:()=>m(p.id),disabled:r.has(p.id),className:"inline-flex items-center gap-1 rounded-full border border-red-500/20 bg-red-500/[0.06] px-2.5 py-1 text-[11px] font-medium text-red-700 transition-colors hover:bg-red-500/[0.12] dark:text-red-300 disabled:opacity-50",children:[e.jsx(A1,{className:"h-2.5 w-2.5",fill:"currentColor"}),r.has(p.id)?"Stopping…":"Stop"]}),e.jsxs(Oe,{to:`/agents/${p.agentId}/runs/${p.id}`,className:"inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2.5 py-1 text-[11px] font-medium text-cyan-700 transition-colors hover:border-cyan-500/30 hover:text-cyan-600 dark:text-cyan-300",children:["Open run",e.jsx(Is,{className:"h-3 w-3"})]})]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto pr-1",children:e.jsx(Ni,{entries:f,density:"compact",limit:8,streaming:x,collapseStdout:!0,emptyMessage:d(p.id)?"Waiting for transcript parsing...":"Waiting for run output..."})})]},p.id)})})]})}function bN({...t}){return e.jsx(bp,{"data-slot":"sheet",...t})}function dU({...t}){return e.jsx(Fb,{"data-slot":"sheet-trigger",...t})}function uU({...t}){return e.jsx(yp,{"data-slot":"sheet-portal",...t})}function mU({className:t,...n}){return e.jsx(vp,{"data-slot":"sheet-overlay",className:O("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...n})}function yN({className:t,children:n,side:s="right",showCloseButton:r=!0,...a}){return e.jsxs(uU,{children:[e.jsx(mU,{}),e.jsxs(jp,{"data-slot":"sheet-content",className:O("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",s==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",s==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",s==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",s==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",t),...a,children:[n,r&&e.jsxs(Nd,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[e.jsx(zt,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function vN({className:t,...n}){return e.jsx("div",{"data-slot":"sheet-header",className:O("flex flex-col gap-1.5 p-4",t),...n})}function pU({className:t,...n}){return e.jsx("div",{"data-slot":"sheet-footer",className:O("mt-auto flex flex-col gap-2 p-4",t),...n})}function jN({className:t,...n}){return e.jsx(Ob,{"data-slot":"sheet-title",className:O("text-foreground font-semibold",t),...n})}function xU({className:t,...n}){return e.jsx(Lb,{"data-slot":"sheet-description",className:O("text-muted-foreground text-sm",t),...n})}const qg={"issue.created":"created the issue","issue.updated":"updated the issue","issue.checked_out":"checked out the issue","issue.released":"released the issue","issue.comment_added":"added a comment","issue.attachment_added":"added an attachment","issue.attachment_removed":"removed an attachment","issue.document_created":"created a document","issue.document_updated":"updated a document","issue.document_deleted":"deleted a document","issue.deleted":"deleted the issue","agent.created":"created an agent","agent.updated":"updated the agent","agent.paused":"paused the agent","agent.resumed":"resumed the agent","agent.terminated":"terminated the agent","heartbeat.invoked":"invoked a heartbeat","heartbeat.cancelled":"cancelled a heartbeat","approval.created":"requested approval","approval.approved":"approved","approval.rejected":"rejected"};function Ao(t){return typeof t!="string"?String(t??"none"):t.replace(/_/g," ")}function Ug(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function um(t,...n){if(!t)return 0;for(const s of n){const r=t[s];if(typeof r=="number"&&Number.isFinite(r))return r}return 0}function Bg(t){const n=t.name.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||t.type==="text/markdown"}function fU(t){return t.replace(/\.[^.]+$/,"")}function hU(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"document"}function gU(t){return t.split(/[-_ ]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function bU(t,n){if(t==="issue.updated"&&n){const s=n._previous??{},r=[];if(n.status!==void 0){const a=s.status;r.push(a?`changed the status from ${Ao(a)} to ${Ao(n.status)}`:`changed the status to ${Ao(n.status)}`)}if(n.priority!==void 0){const a=s.priority;r.push(a?`changed the priority from ${Ao(a)} to ${Ao(n.priority)}`:`changed the priority to ${Ao(n.priority)}`)}if((n.assigneeAgentId!==void 0||n.assigneeUserId!==void 0)&&r.push(n.assigneeAgentId||n.assigneeUserId?"assigned the issue":"unassigned the issue"),n.title!==void 0&&r.push("updated the title"),n.description!==void 0&&r.push("updated the description"),r.length>0)return r.join(", ")}if((t==="issue.document_created"||t==="issue.document_updated"||t==="issue.document_deleted")&&n){const s=typeof n.key=="string"?n.key:"document",r=typeof n.title=="string"&&n.title?` (${n.title})`:"";return`${qg[t]??t} ${s}${r}`}return qg[t]??t.replace(/[._]/g," ")}function yU({evt:t,agentMap:n}){const s=t.actorId;if(t.actorType==="agent"){const r=n.get(s);return e.jsx(Ut,{name:(r==null?void 0:r.name)??s.slice(0,8),size:"sm"})}return t.actorType==="system"?e.jsx(Ut,{name:"System",size:"sm"}):t.actorType==="user"?e.jsx(Ut,{name:"Board",size:"sm"}):e.jsx(Ut,{name:s||"Unknown",size:"sm"})}function vU(){var ln,yt,hn,pn;const{issueId:t}=Xn(),{selectedCompanyId:n}=et(),{openPanel:s,closePanel:r,panelVisible:a,setPanelVisible:o}=ji(),{setBreadcrumbs:i}=Ft(),l=at(),u=Sn(),d=fn(),{pushToast:m}=ds(),[p,x]=c.useState(!1),[f,h]=c.useState(!1),[j,b]=c.useState(!1),[g,y]=c.useState("comments"),[v,_]=c.useState({approvals:!1}),[E,S]=c.useState(null),[M,B]=c.useState(!1),[k,L]=c.useState([]),$=c.useRef(null),C=c.useRef(null),{data:I,isLoading:K,error:T}=oe({queryKey:N.issues.detail(t),queryFn:()=>nt.get(t),enabled:!!t}),z=(I==null?void 0:I.companyId)??n,{data:w}=oe({queryKey:N.issues.comments(t),queryFn:()=>nt.listComments(t),enabled:!!t}),{data:F}=oe({queryKey:N.issues.activity(t),queryFn:()=>ya.forIssue(t),enabled:!!t}),{data:A}=oe({queryKey:N.issues.runs(t),queryFn:()=>ya.runsForIssue(t),enabled:!!t,refetchInterval:5e3}),{data:R}=oe({queryKey:N.issues.approvals(t),queryFn:()=>nt.listApprovals(t),enabled:!!t}),{data:Q}=oe({queryKey:N.issues.attachments(t),queryFn:()=>nt.listAttachments(t),enabled:!!t}),{data:H}=oe({queryKey:N.issues.liveRuns(t),queryFn:()=>Yt.liveRunsForIssue(t),enabled:!!t,refetchInterval:3e3}),{data:U}=oe({queryKey:N.issues.activeRun(t),queryFn:()=>Yt.activeRunForIssue(t),enabled:!!t,refetchInterval:3e3}),Z=(H??[]).length>0||!!U,V=c.useMemo(()=>(U==null?void 0:U.status)==="running"?U:(H??[]).find(re=>re.status==="running")??null,[U,H]),W=c.useMemo(()=>oq(d.state,d.search)??{label:"Issues",href:"/issues"},[d.state,d.search]),J=c.useMemo(()=>{const re=new Set;for(const $e of H??[])re.add($e.id);return U&&re.add(U.id),re.size===0?A??[]:(A??[]).filter($e=>!re.has($e.runId))},[A,H,U]),{data:Y}=oe({queryKey:N.issues.list(n),queryFn:()=>nt.list(n),enabled:!!n}),{data:de}=oe({queryKey:N.agents.list(n),queryFn:()=>We.list(n),enabled:!!n}),{data:fe}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),{data:Ce}=oe({queryKey:N.projects.list(n),queryFn:()=>en.list(n),enabled:!!n}),le=((ln=fe==null?void 0:fe.user)==null?void 0:ln.id)??((yt=fe==null?void 0:fe.session)==null?void 0:yt.userId)??null,{orderedProjects:Re}=$l({projects:Ce??[],companyId:n,userId:le}),{slots:Pe}=yi({slotTypes:["detailTab"],entityType:"issue",enabled:!!z}),Fe=c.useMemo(()=>Pe.map(re=>({value:`plugin:${re.pluginKey}:${re.id}`,label:re.displayName,slot:re})),[Pe]),pe=Fe.find(re=>re.value===g)??null,Le=c.useMemo(()=>{const re=new Map;for(const $e of de??[])re.set($e.id,$e);return re},[de]),q=c.useMemo(()=>{const re=[],$e=[...de??[]].filter(Ee=>Ee.status!=="terminated").sort((Ee,He)=>Ee.name.localeCompare(He.name));for(const Ee of $e)re.push({id:`agent:${Ee.id}`,name:Ee.name,kind:"agent",agentId:Ee.id,agentIcon:Ee.icon});for(const Ee of Re)re.push({id:`project:${Ee.id}`,name:Ee.name,kind:"project",projectId:Ee.id,projectColor:Ee.color});return re},[de,Re]),D=c.useMemo(()=>!Y||!I?[]:Y.filter(re=>re.parentId===I.id).sort((re,$e)=>new Date(re.createdAt).getTime()-new Date($e.createdAt).getTime()),[Y,I]),ie=c.useMemo(()=>{const re=[],$e=[...de??[]].filter(Ee=>Ee.status!=="terminated").sort((Ee,He)=>Ee.name.localeCompare(He.name));for(const Ee of $e)re.push({id:`agent:${Ee.id}`,label:Ee.name});return le&&re.push({id:`user:${le}`,label:"Me"}),re},[de,le]),Ie=c.useMemo(()=>Ds(I??{}),[I]),ue=c.useMemo(()=>a3(I??{},Tg(w??[],k),le),[I,w,k,le]),Be=c.useMemo(()=>Tg(w??[],k),[w,k]),be=c.useMemo(()=>{const re=(V==null?void 0:V.startedAt)??(V==null?void 0:V.createdAt)??null,$e=new Map,Ee=new Map;for(const He of A??[])Ee.set(He.runId,He.agentId);for(const He of F??[]){if(He.action!=="issue.comment_added"||!He.runId)continue;const rt=He.details??{},xt=typeof rt.commentId=="string"?rt.commentId:null;if(!xt||$e.has(xt))continue;const Pt=typeof rt.interruptedRunId=="string"?rt.interruptedRunId:null;$e.set(xt,{runId:He.runId,runAgentId:He.agentId??Ee.get(He.runId)??null,interruptedRunId:Pt})}return Be.map(He=>{const rt=$e.get(He.id),xt=rt?{...He,...rt}:{...He};return Dq({comment:xt,activeRunStartedAt:re,runId:(rt==null?void 0:rt.runId)??xt.runId??null,interruptedRunId:(rt==null?void 0:rt.interruptedRunId)??xt.interruptedRunId??null})?{...xt,queueState:"queued",queueTargetRunId:(V==null?void 0:V.id)??xt.queueTargetRunId??null}:xt})},[F,Be,A,V]),he=c.useMemo(()=>be.filter(re=>re.queueState==="queued"),[be]),Se=c.useMemo(()=>be.filter(re=>re.queueState!=="queued"),[be]),we=c.useMemo(()=>{let re=0,$e=0,Ee=0,He=0,rt=!1,xt=!1;for(const Pt of A??[]){const gn=Ug(Pt.usageJson),$n=Ug(Pt.resultJson),Ne=um(gn,"inputTokens","input_tokens"),te=um(gn,"outputTokens","output_tokens"),Ae=um(gn,"cachedInputTokens","cached_input_tokens","cache_read_input_tokens"),Je=cj(gn,$n);Je>0&&(rt=!0),Ne+te+Ae>0&&(xt=!0),re+=Ne,$e+=te,Ee+=Ae,He+=Je}return{input:re,output:$e,cached:Ee,cost:He,totalTokens:re+$e,hasCost:rt,hasTokens:xt}},[A]),ee=()=>{l.invalidateQueries({queryKey:N.issues.detail(t)}),l.invalidateQueries({queryKey:N.issues.activity(t)}),l.invalidateQueries({queryKey:N.issues.runs(t)}),l.invalidateQueries({queryKey:N.issues.approvals(t)}),l.invalidateQueries({queryKey:N.issues.attachments(t)}),l.invalidateQueries({queryKey:N.issues.documents(t)}),l.invalidateQueries({queryKey:N.issues.liveRuns(t)}),l.invalidateQueries({queryKey:N.issues.activeRun(t)}),n&&(l.invalidateQueries({queryKey:N.issues.list(n)}),l.invalidateQueries({queryKey:N.issues.listMineByMe(n)}),l.invalidateQueries({queryKey:N.issues.listTouchedByMe(n)}),l.invalidateQueries({queryKey:N.issues.listUnreadTouchedByMe(n)}),l.invalidateQueries({queryKey:N.sidebarBadges(n)}))},me=ge({mutationFn:re=>nt.markRead(re),onSuccess:()=>{n&&(l.invalidateQueries({queryKey:N.issues.listMineByMe(n)}),l.invalidateQueries({queryKey:N.issues.listTouchedByMe(n)}),l.invalidateQueries({queryKey:N.issues.listUnreadTouchedByMe(n)}),l.invalidateQueries({queryKey:N.sidebarBadges(n)}))}}),ye=ge({mutationFn:re=>nt.update(t,re),onSuccess:()=>{ee()}}),Ke=ge({mutationFn:({body:re,reopen:$e,interrupt:Ee})=>nt.addComment(t,re,$e,Ee),onMutate:async({body:re,reopen:$e,interrupt:Ee})=>{await l.cancelQueries({queryKey:N.issues.comments(t)}),await l.cancelQueries({queryKey:N.issues.detail(t)});const He=l.getQueryData(N.issues.detail(t)),rt=!Ee&&V,xt=I?Eg({companyId:I.companyId,issueId:I.id,body:re,authorUserId:le,clientStatus:rt?"queued":"pending",queueTargetRunId:rt?V.id:null}):null;return xt&&L(Pt=>[...Pt,xt]),He&&l.setQueryData(N.issues.detail(t),Pg(He,{reopen:$e})),{optimisticCommentId:(xt==null?void 0:xt.clientId)??null,previousIssue:He}},onSuccess:(re,$e,Ee)=>{Ee!=null&&Ee.optimisticCommentId&&L(He=>He.filter(rt=>rt.clientId!==Ee.optimisticCommentId)),l.setQueryData(N.issues.comments(t),He=>Rg(He,re))},onError:(re,$e,Ee)=>{Ee!=null&&Ee.optimisticCommentId&&L(He=>He.filter(rt=>rt.clientId!==Ee.optimisticCommentId)),Ee!=null&&Ee.previousIssue&&l.setQueryData(N.issues.detail(t),Ee.previousIssue),m({title:"Comment failed",body:re instanceof Error?re.message:"Unable to post comment",tone:"error"})},onSettled:()=>{ee(),l.invalidateQueries({queryKey:N.issues.comments(t)})}}),qe=ge({mutationFn:({body:re,reopen:$e,interrupt:Ee,reassignment:He})=>nt.update(t,{comment:re,assigneeAgentId:He.assigneeAgentId,assigneeUserId:He.assigneeUserId,...$e?{status:"todo"}:{},...Ee?{interrupt:Ee}:{}}),onMutate:async({body:re,reopen:$e,reassignment:Ee,interrupt:He})=>{await l.cancelQueries({queryKey:N.issues.comments(t)}),await l.cancelQueries({queryKey:N.issues.detail(t)});const rt=l.getQueryData(N.issues.detail(t)),xt=!He&&V,Pt=I?Eg({companyId:I.companyId,issueId:I.id,body:re,authorUserId:le,clientStatus:xt?"queued":"pending",queueTargetRunId:xt?V.id:null}):null;return Pt&&L(gn=>[...gn,Pt]),rt&&l.setQueryData(N.issues.detail(t),Pg(rt,{reopen:$e,reassignment:Ee})),{optimisticCommentId:(Pt==null?void 0:Pt.clientId)??null,previousIssue:rt}},onSuccess:(re,$e,Ee)=>{Ee!=null&&Ee.optimisticCommentId&&L(xt=>xt.filter(Pt=>Pt.clientId!==Ee.optimisticCommentId));const{comment:He,...rt}=re;l.setQueryData(N.issues.detail(t),rt),He&&l.setQueryData(N.issues.comments(t),xt=>Rg(xt,He))},onError:(re,$e,Ee)=>{Ee!=null&&Ee.optimisticCommentId&&L(He=>He.filter(rt=>rt.clientId!==Ee.optimisticCommentId)),Ee!=null&&Ee.previousIssue&&l.setQueryData(N.issues.detail(t),Ee.previousIssue),m({title:"Comment failed",body:re instanceof Error?re.message:"Unable to post comment",tone:"error"})},onSettled:()=>{ee(),l.invalidateQueries({queryKey:N.issues.comments(t)})}}),se=ge({mutationFn:re=>Yt.cancel(re),onSuccess:()=>{ee(),m({title:"Interrupt requested",body:"The active run is stopping so queued comments can continue next.",tone:"success"})},onError:re=>{m({title:"Interrupt failed",body:re instanceof Error?re.message:"Unable to interrupt the active run",tone:"error"})}}),ce=ge({mutationFn:async re=>{if(!n)throw new Error("No company selected");return nt.uploadAttachment(n,t,re)},onSuccess:()=>{S(null),l.invalidateQueries({queryKey:N.issues.attachments(t)}),ee()},onError:re=>{S(re instanceof Error?re.message:"Upload failed")}}),Te=ge({mutationFn:async re=>{const $e=fU(re.name),Ee=hU($e),He=((I==null?void 0:I.documentSummaries)??[]).find(gn=>gn.key===Ee)??null,rt=await re.text(),xt=gU($e),Pt=(He==null?void 0:He.title)??xt??null;return nt.upsertDocument(t,Ee,{title:Ee==="plan"?null:Pt,format:"markdown",body:rt,baseRevisionId:(He==null?void 0:He.latestRevisionId)??null})},onSuccess:()=>{S(null),ee()},onError:re=>{S(re instanceof Error?re.message:"Document import failed")}}),ae=ge({mutationFn:re=>nt.deleteAttachment(re),onSuccess:()=>{S(null),l.invalidateQueries({queryKey:N.issues.attachments(t)}),ee()},onError:re=>{S(re instanceof Error?re.message:"Delete failed")}});c.useEffect(()=>{const re=(I==null?void 0:I.title)??t??"Issue";i([W,{label:Z?`🔵 ${re}`:re}])},[i,W,I,t,Z]),c.useEffect(()=>{I!=null&&I.identifier&&t!==I.identifier&&u(Gi(I.identifier,d.state,d.search),{replace:!0,state:d.state})},[I,t,u,d.state,d.search]),c.useEffect(()=>{I!=null&&I.id&&C.current!==I.id&&(C.current=I.id,me.mutate(I.id))},[I==null?void 0:I.id]),c.useEffect(()=>(I&&s(e.jsx(Og,{issue:I,onUpdate:re=>ye.mutate(re)})),()=>r()),[I]);const je=async()=>{if(!I)return;const re=rt=>{const xt=document.createElement("textarea");return xt.innerHTML=rt,xt.value},$e=re(I.title),Ee=re(I.description??""),He=`# ${I.identifier}: ${$e}
|
|
114
|
+
|
|
115
|
+
${Ee}`.trimEnd();await navigator.clipboard.writeText(He),h(!0),m({title:"Copied to clipboard",tone:"success"}),setTimeout(()=>h(!1),2e3)};if(K)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."});if(T)return e.jsx("p",{className:"text-sm text-destructive",children:T.message});if(!I)return null;const ke=I.ancestors??[],Xe=async re=>{const $e=re.target.files;if(!(!$e||$e.length===0)){for(const Ee of Array.from($e))Bg(Ee)?await Te.mutateAsync(Ee):await ce.mutateAsync(Ee);$.current&&($.current.value="")}},lt=async re=>{re.preventDefault(),B(!1);const $e=re.dataTransfer.files;if(!(!$e||$e.length===0))for(const Ee of Array.from($e))Bg(Ee)?await Te.mutateAsync(Ee):await ce.mutateAsync(Ee)},It=re=>re.contentType.startsWith("image/"),Ue=Q??[],pt=Ue.length>0,ht=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:$,type:"file",accept:"image/*,application/pdf,text/plain,text/markdown,application/json,text/csv,text/html,.md,.markdown",className:"hidden",onChange:Xe,multiple:!0}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{var re;return(re=$.current)==null?void 0:re.click()},disabled:ce.isPending||Te.isPending,className:O("shadow-none",M&&"border-primary bg-primary/5"),children:[e.jsx(ai,{className:"h-3.5 w-3.5 mr-1.5"}),ce.isPending||Te.isPending?"Uploading...":e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden sm:inline",children:"Upload attachment"}),e.jsx("span",{className:"sm:hidden",children:"Upload"})]})]})]});return e.jsxs("div",{className:"max-w-2xl space-y-6",children:[ke.length>0&&e.jsxs("nav",{className:"flex items-center gap-1 text-xs text-muted-foreground flex-wrap",children:[[...ke].reverse().map((re,$e)=>e.jsxs("span",{className:"flex items-center gap-1",children:[$e>0&&e.jsx(sn,{className:"h-3 w-3 shrink-0"}),e.jsx(Oe,{to:Gi(re.identifier??re.id,d.state,d.search),state:d.state,className:"hover:text-foreground transition-colors truncate max-w-[200px]",title:re.title,children:re.title})]},re.id)),e.jsx(sn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"text-foreground/60 truncate max-w-[200px]",children:I.title})]}),I.hiddenAt&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[e.jsx(al,{className:"h-4 w-4 shrink-0"}),"This issue is hidden"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-wrap",children:[e.jsx(Pn,{status:I.status,onChange:re=>ye.mutate({status:re})}),e.jsx(vs,{priority:I.priority,onChange:re=>ye.mutate({priority:re})}),e.jsx("span",{className:"text-sm font-mono text-muted-foreground shrink-0",children:I.identifier??I.id.slice(0,8)}),Z&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-cyan-500/10 border border-cyan-500/30 px-2 py-0.5 text-[10px] font-medium text-cyan-600 dark:text-cyan-400 shrink-0",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-cyan-400"})]}),"Live"]}),I.originKind==="routine_execution"&&I.originId&&e.jsxs(Oe,{to:`/routines/${I.originId}`,className:"inline-flex items-center gap-1 rounded-full bg-violet-500/10 border border-violet-500/30 px-2 py-0.5 text-[10px] font-medium text-violet-600 dark:text-violet-400 shrink-0 hover:bg-violet-500/20 transition-colors",children:[e.jsx(nl,{className:"h-3 w-3"}),"Routine"]}),I.projectId?e.jsxs(Oe,{to:`/projects/${I.projectId}`,className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors rounded px-1 -mx-1 py-0.5 min-w-0",children:[e.jsx(Sr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:((hn=(Ce??[]).find(re=>re.id===I.projectId))==null?void 0:hn.name)??I.projectId.slice(0,8)})]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground opacity-50 px-1 -mx-1 py-0.5",children:[e.jsx(Sr,{className:"h-3 w-3 shrink-0"}),"No project"]}),(I.labels??[]).length>0&&e.jsxs("div",{className:"hidden sm:flex items-center gap-1",children:[(I.labels??[]).slice(0,4).map(re=>e.jsx("span",{className:"inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium",style:{borderColor:re.color,color:Yd(re.color,.12),backgroundColor:`${re.color}1f`},children:re.name},re.id)),(I.labels??[]).length>4&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",(I.labels??[]).length-4]})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-0.5 md:hidden shrink-0",children:[e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:je,title:"Copy issue as markdown",children:f?e.jsx(Nn,{className:"h-4 w-4 text-green-500"}):e.jsx(_s,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:()=>b(!0),title:"Properties",children:e.jsx(rl,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"hidden md:flex items-center md:ml-auto shrink-0",children:[e.jsx(G,{variant:"ghost",size:"icon-xs",onClick:je,title:"Copy issue as markdown",children:f?e.jsx(Nn,{className:"h-4 w-4 text-green-500"}):e.jsx(_s,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon-xs",className:O("shrink-0 transition-opacity duration-200",a?"opacity-0 pointer-events-none w-0 overflow-hidden":"opacity-100"),onClick:()=>o(!0),title:"Show properties",children:e.jsx(rl,{className:"h-4 w-4"})}),e.jsxs(Ht,{open:p,onOpenChange:x,children:[e.jsx(Vt,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon-xs",className:"shrink-0",children:e.jsx(xi,{className:"h-4 w-4"})})}),e.jsx(Qt,{className:"w-44 p-1",align:"end",children:e.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-destructive",onClick:()=>{ye.mutate({hiddenAt:new Date().toISOString()},{onSuccess:()=>u("/issues/all")}),x(!1)},children:[e.jsx(al,{className:"h-3 w-3"}),"Hide this Issue"]})})]})]})]}),e.jsx(kr,{value:I.title,onSave:re=>ye.mutateAsync({title:re}),as:"h2",className:"text-xl font-bold"}),e.jsx(kr,{value:I.description??"",onSave:re=>ye.mutateAsync({description:re}),as:"p",className:"text-[15px] leading-7 text-foreground",placeholder:"Add a description...",multiline:!0,mentions:q,imageUploadHandler:async re=>(await ce.mutateAsync(re)).contentPath})]}),e.jsx(Vr,{slotTypes:["toolbarButton","contextMenuItem"],entityType:"issue",context:{companyId:I.companyId,projectId:I.projectId??null,entityId:I.id,entityType:"issue"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex",missingBehavior:"placeholder"}),e.jsx($x,{placementZones:["toolbarButton"],entityType:"issue",context:{companyId:I.companyId,projectId:I.projectId??null,entityId:I.id,entityType:"issue"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex"}),e.jsx(Vr,{slotTypes:["taskDetailView"],entityType:"issue",context:{companyId:I.companyId,projectId:I.projectId??null,entityId:I.id,entityType:"issue"},className:"space-y-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"}),e.jsx(Yq,{issue:I,canDeleteDocuments:!!((pn=fe==null?void 0:fe.user)!=null&&pn.id),mentions:q,imageUploadHandler:async re=>(await ce.mutateAsync(re)).contentPath,extraActions:pt?void 0:ht}),pt?e.jsxs("div",{className:O("space-y-3 rounded-lg transition-colors"),onDragEnter:re=>{re.preventDefault(),B(!0)},onDragOver:re=>{re.preventDefault(),B(!0)},onDragLeave:re=>{re.currentTarget.contains(re.relatedTarget)||B(!1)},onDrop:re=>void lt(re),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Attachments"}),ht]}),E&&e.jsx("p",{className:"text-xs text-destructive",children:E}),e.jsx("div",{className:"space-y-2",children:Ue.map(re=>e.jsxs("div",{className:"border border-border rounded-md p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("a",{href:re.contentPath,target:"_blank",rel:"noreferrer",className:"text-xs hover:underline truncate",title:re.originalFilename??re.id,children:re.originalFilename??re.id}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-destructive",onClick:()=>ae.mutate(re.id),disabled:ae.isPending,title:"Delete attachment",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[re.contentType," · ",(re.byteSize/1024).toFixed(1)," KB"]}),It(re)&&e.jsx("a",{href:re.contentPath,target:"_blank",rel:"noreferrer",children:e.jsx("img",{src:re.contentPath,alt:re.originalFilename??"attachment",className:"mt-2 max-h-56 rounded border border-border object-contain bg-accent/10",loading:"lazy"})})]},re.id))})]}):null,e.jsx(lU,{issue:I,project:Re.find(re=>re.id===I.projectId)??null,onUpdate:re=>ye.mutate(re)}),e.jsx(yn,{}),e.jsxs(Ss,{value:g,onValueChange:y,className:"space-y-3",children:[e.jsxs(co,{variant:"line",className:"w-full justify-start gap-1",children:[e.jsxs(An,{value:"comments",className:"gap-1.5",children:[e.jsx(zb,{className:"h-3.5 w-3.5"}),"Comments"]}),e.jsxs(An,{value:"subissues",className:"gap-1.5",children:[e.jsx(E1,{className:"h-3.5 w-3.5"}),"Sub-issues"]}),e.jsxs(An,{value:"activity",className:"gap-1.5",children:[e.jsx(ny,{className:"h-3.5 w-3.5"}),"Activity"]}),Fe.map(re=>e.jsx(An,{value:re.value,children:re.label},re.value))]}),e.jsx(on,{value:"comments",children:e.jsx(Wq,{comments:Se,queuedComments:he,linkedRuns:J,companyId:I.companyId,projectId:I.projectId,issueStatus:I.status,agentMap:Le,draftKey:`crewspace:issue-comment-draft:${I.id}`,enableReassign:!0,reassignOptions:ie,currentAssigneeValue:Ie,suggestedAssigneeValue:ue,mentions:q,onInterruptQueued:async re=>{await se.mutateAsync(re)},interruptingQueuedRunId:se.isPending?(V==null?void 0:V.id)??null:null,onAdd:async(re,$e,Ee)=>{if(Ee){await qe.mutateAsync({body:re,reopen:$e,reassignment:Ee});return}await Ke.mutateAsync({body:re,reopen:$e})},imageUploadHandler:async re=>(await ce.mutateAsync(re)).contentPath,onAttachImage:async re=>{await ce.mutateAsync(re)},liveRunSlot:e.jsx(gN,{issueId:t,companyId:I.companyId})})}),e.jsx(on,{value:"subissues",children:D.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No sub-issues."}):e.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:D.map(re=>e.jsxs(Oe,{to:Gi(re.identifier??re.id,d.state,d.search),state:d.state,className:"flex items-center justify-between px-3 py-2 text-sm hover:bg-accent/20 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Pn,{status:re.status}),e.jsx(vs,{priority:re.priority}),e.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:re.identifier??re.id.slice(0,8)}),e.jsx("span",{className:"truncate",children:re.title})]}),re.assigneeAgentId&&(()=>{var Ee;const $e=(Ee=Le.get(re.assigneeAgentId))==null?void 0:Ee.name;return $e?e.jsx(Ut,{name:$e,size:"sm"}):e.jsx("span",{className:"text-muted-foreground font-mono",children:re.assigneeAgentId.slice(0,8)})})()]},re.id))})}),e.jsxs(on,{value:"activity",children:[A&&A.length>0&&e.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg border border-border",children:[e.jsx("div",{className:"text-sm font-medium text-muted-foreground mb-1",children:"Cost Summary"}),!we.hasCost&&!we.hasTokens?e.jsx("div",{className:"text-xs text-muted-foreground",children:"No cost data yet."}):e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground tabular-nums",children:[we.hasCost&&e.jsxs("span",{className:"font-medium text-foreground",children:["$",we.cost.toFixed(4)]}),we.hasTokens&&e.jsxs("span",{children:["Tokens ",Et(we.totalTokens),we.cached>0?` (in ${Et(we.input)}, out ${Et(we.output)}, cached ${Et(we.cached)})`:` (in ${Et(we.input)}, out ${Et(we.output)})`]})]})]}),!F||F.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):e.jsx("div",{className:"space-y-1.5",children:F.slice(0,20).map(re=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(yU,{evt:re,agentMap:Le}),e.jsx("span",{children:bU(re.action,re.details)}),e.jsx("span",{className:"ml-auto shrink-0",children:os(re.createdAt)})]},re.id))})]}),pe&&e.jsx(on,{value:pe.value,children:e.jsx(vi,{slot:pe.slot,context:{companyId:I.companyId,projectId:I.projectId??null,entityId:I.id,entityType:"issue"},missingBehavior:"placeholder"})})]}),R&&R.length>0&&e.jsxs(Sa,{open:v.approvals,onOpenChange:re=>_($e=>({...$e,approvals:re})),className:"rounded-lg border border-border",children:[e.jsxs(Ia,{className:"flex w-full items-center justify-between px-3 py-2 text-left",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Linked Approvals (",R.length,")"]}),e.jsx(rn,{className:O("h-4 w-4 text-muted-foreground transition-transform",v.approvals&&"rotate-180")})]}),e.jsx(_a,{children:e.jsx("div",{className:"border-t border-border divide-y divide-border",children:R.map(re=>e.jsxs(Oe,{to:`/approvals/${re.id}`,className:"flex items-center justify-between px-3 py-2 text-xs hover:bg-accent/20 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{status:re.status}),e.jsx("span",{className:"font-medium",children:re.type.replace(/_/g," ").replace(/\b\w/g,$e=>$e.toUpperCase())}),e.jsx("span",{className:"font-mono text-muted-foreground",children:re.id.slice(0,8)})]}),e.jsx("span",{className:"text-muted-foreground",children:os(re.createdAt)})]},re.id))})})]}),e.jsx(bN,{open:j,onOpenChange:b,children:e.jsxs(yN,{side:"bottom",className:"max-h-[85dvh] pb-[env(safe-area-inset-bottom)]",children:[e.jsx(vN,{children:e.jsx(jN,{className:"text-sm",children:"Properties"})}),e.jsx(Dx,{className:"flex-1 overflow-y-auto",children:e.jsx("div",{className:"px-4 pb-4",children:e.jsx(Og,{issue:I,onUpdate:re=>ye.mutate(re),inline:!0})})})]})}),e.jsx(eN,{})]})}const ys={list:t=>ne.get(`/companies/${t}/routines`),create:(t,n)=>ne.post(`/companies/${t}/routines`,n),get:t=>ne.get(`/routines/${t}`),update:(t,n)=>ne.patch(`/routines/${t}`,n),listRuns:(t,n=50)=>ne.get(`/routines/${t}/runs?limit=${n}`),createTrigger:(t,n)=>ne.post(`/routines/${t}/triggers`,n),updateTrigger:(t,n)=>ne.patch(`/routine-triggers/${t}`,n),deleteTrigger:t=>ne.delete(`/routine-triggers/${t}`),rotateTriggerSecret:t=>ne.post(`/routine-triggers/${t}/rotate-secret`,{}),run:(t,n)=>ne.post(`/routines/${t}/run`,n??{}),activity:async(t,n,s)=>{const r=[ya.list(t,{entityType:"routine",entityId:n}),...((s==null?void 0:s.triggerIds)??[]).map(i=>ya.list(t,{entityType:"routine_trigger",entityId:i})),...((s==null?void 0:s.runIds)??[]).map(i=>ya.list(t,{entityType:"routine_run",entityId:i}))],a=(await Promise.all(r)).flat();return[...new Map(a.map(i=>[i.id,i])).values()].sort((i,l)=>new Date(l.createdAt).getTime()-new Date(i.createdAt).getTime())}};function Hn({...t}){return e.jsx(MC,{"data-slot":"select",...t})}function Vn({...t}){return e.jsx(OC,{"data-slot":"select-value",...t})}function Qn({className:t,size:n="default",children:s,...r}){return e.jsxs($C,{"data-slot":"select-trigger","data-size":n,className:O("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r,children:[s,e.jsx(DC,{asChild:!0,children:e.jsx(rn,{className:"size-4 opacity-50"})})]})}function Gn({className:t,children:n,position:s="item-aligned",align:r="center",...a}){return e.jsx(LC,{children:e.jsxs(FC,{"data-slot":"select-content",className:O("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,align:r,...a,children:[e.jsx(jU,{}),e.jsx(qC,{className:O("p-1",s==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:n}),e.jsx(wU,{})]})})}function Mt({className:t,children:n,...s}){return e.jsxs(UC,{"data-slot":"select-item",className:O("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...s,children:[e.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(BC,{children:e.jsx(Nn,{className:"size-4"})})}),e.jsx(KC,{children:n})]})}function jU({className:t,...n}){return e.jsx(zC,{"data-slot":"select-scroll-up-button",className:O("flex cursor-default items-center justify-center py-1",t),...n,children:e.jsx(sy,{className:"size-4"})})}function wU({className:t,...n}){return e.jsx(WC,{"data-slot":"select-scroll-down-button",className:O("flex cursor-default items-center justify-center py-1",t),...n,children:e.jsx(rn,{className:"size-4"})})}const NU=["coalesce_if_active","always_enqueue","skip_if_active"],kU=["skip_missed","enqueue_missed_with_cap"],CU={coalesce_if_active:"If a run is already active, keep just one follow-up run queued.",always_enqueue:"Queue every trigger occurrence, even if the routine is already running.",skip_if_active:"Drop new trigger occurrences while a run is still active."},SU={skip_missed:"Ignore windows that were missed while the scheduler or routine was paused.",enqueue_missed_with_cap:"Catch up missed schedule windows in capped batches after recovery."};function Kg(t){t&&(t.style.height="auto",t.style.height=`${t.scrollHeight}px`)}function IU(t){return t?new Date(t).toLocaleString():"Never"}function _U(t,n){return t==="archived"&&n||n?"active":"paused"}function AU(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),s=at(),r=Sn(),{pushToast:a}=ds(),o=c.useRef(null),i=c.useRef(null),l=c.useRef(null),u=c.useRef(null),[d,m]=c.useState(null),[p,x]=c.useState(null),[f,h]=c.useState(!1),[j,b]=c.useState(!1),[g,y]=c.useState({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed"});c.useEffect(()=>{n([{label:"Routines"}])},[n]);const{data:v,isLoading:_,error:E}=oe({queryKey:N.routines.list(t),queryFn:()=>ys.list(t),enabled:!!t}),{data:S}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),{data:M}=oe({queryKey:N.projects.list(t),queryFn:()=>en.list(t),enabled:!!t});c.useEffect(()=>{Kg(i.current)},[g.title,f]);const B=ge({mutationFn:()=>ys.create(t,{...g,description:g.description.trim()||null}),onSuccess:async F=>{y({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed"}),h(!1),b(!1),await s.invalidateQueries({queryKey:N.routines.list(t)}),a({title:"Routine created",body:"Add the first trigger to turn it into a live workflow.",tone:"success"}),r(`/routines/${F.id}?tab=triggers`)}}),k=ge({mutationFn:({id:F,status:A})=>ys.update(F,{status:A}),onMutate:({id:F})=>{x(F)},onSuccess:async(F,A)=>{await Promise.all([s.invalidateQueries({queryKey:N.routines.list(t)}),s.invalidateQueries({queryKey:N.routines.detail(A.id)})])},onSettled:()=>{x(null)},onError:F=>{a({title:"Failed to update routine",body:F instanceof Error?F.message:"CrewSpace could not update the routine.",tone:"error"})}}),L=ge({mutationFn:F=>ys.run(F),onMutate:F=>{m(F)},onSuccess:async(F,A)=>{await Promise.all([s.invalidateQueries({queryKey:N.routines.list(t)}),s.invalidateQueries({queryKey:N.routines.detail(A)})])},onSettled:()=>{m(null)},onError:F=>{a({title:"Routine run failed",body:F instanceof Error?F.message:"CrewSpace could not start the routine run.",tone:"error"})}}),$=c.useMemo(()=>Ol(),[f]),C=c.useMemo(()=>eu((S??[]).filter(F=>F.status!=="terminated"),$).map(F=>({id:F.id,label:F.name,searchText:`${F.name} ${F.role} ${F.title??""}`})),[S,$]),I=c.useMemo(()=>(M??[]).map(F=>({id:F.id,label:F.name,searchText:F.description??""})),[M]),K=c.useMemo(()=>new Map((S??[]).map(F=>[F.id,F])),[S]),T=c.useMemo(()=>new Map((M??[]).map(F=>[F.id,F])),[M]),z=g.assigneeAgentId?K.get(g.assigneeAgentId)??null:null,w=g.projectId?T.get(g.projectId)??null:null;return t?_?e.jsx(mn,{variant:"issues-list"}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("h1",{className:"text-2xl font-semibold tracking-tight flex items-center gap-2",children:["Routines",e.jsx("span",{className:"rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Recurring work definitions that materialize into auditable execution issues."})]}),e.jsxs(G,{onClick:()=>h(!0),children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),"Create routine"]})]}),e.jsx(Cs,{open:f,onOpenChange:F=>{B.isPending||h(F)},children:e.jsxs(Fs,{showCloseButton:!1,className:"flex max-h-[calc(100dvh-2rem)] max-w-3xl flex-col gap-0 overflow-hidden p-0",children:[e.jsxs("div",{className:"shrink-0 flex flex-wrap items-center justify-between gap-3 border-b border-border/60 px-5 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"New routine"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Define the recurring work first. Trigger setup comes next on the detail page."})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{h(!1),b(!1)},disabled:B.isPending,children:"Cancel"})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[e.jsx("div",{className:"px-5 pt-5 pb-3",children:e.jsx("textarea",{ref:i,className:"w-full resize-none overflow-hidden bg-transparent text-xl font-semibold outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:g.title,onChange:F=>{y(A=>({...A,title:F.target.value})),Kg(F.target)},onKeyDown:F=>{var A,R,Q,H;if(F.key==="Enter"&&!F.metaKey&&!F.ctrlKey&&!F.nativeEvent.isComposing){F.preventDefault(),(A=o.current)==null||A.focus();return}F.key==="Tab"&&!F.shiftKey&&(F.preventDefault(),g.assigneeAgentId?g.projectId?(R=o.current)==null||R.focus():(Q=u.current)==null||Q.focus():(H=l.current)==null||H.focus())},autoFocus:!0})}),e.jsx("div",{className:"px-5 pb-3",children:e.jsx("div",{className:"overflow-x-auto overscroll-x-contain",children:e.jsxs("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[e.jsx("span",{children:"For"}),e.jsx(ba,{ref:l,value:g.assigneeAgentId,options:C,placeholder:"Assignee",noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:F=>{F&&Xd(F),y(A=>({...A,assigneeAgentId:F}))},onConfirm:()=>{var F,A;g.projectId?(F=o.current)==null||F.focus():(A=u.current)==null||A.focus()},renderTriggerValue:F=>F?z?e.jsxs(e.Fragment,{children:[e.jsx(Cn,{icon:z.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:F.label})]}):e.jsx("span",{className:"truncate",children:F.label}):e.jsx("span",{className:"text-muted-foreground",children:"Assignee"}),renderOption:F=>{if(!F.id)return e.jsx("span",{className:"truncate",children:F.label});const A=K.get(F.id);return e.jsxs(e.Fragment,{children:[A?e.jsx(Cn,{icon:A.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,e.jsx("span",{className:"truncate",children:F.label})]})}}),e.jsx("span",{children:"in"}),e.jsx(ba,{ref:u,value:g.projectId,options:I,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:F=>y(A=>({...A,projectId:F})),onConfirm:()=>{var F;return(F=o.current)==null?void 0:F.focus()},renderTriggerValue:F=>F&&w?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:w.color??"#64748b"}}),e.jsx("span",{className:"truncate",children:F.label})]}):e.jsx("span",{className:"text-muted-foreground",children:"Project"}),renderOption:F=>{if(!F.id)return e.jsx("span",{className:"truncate",children:F.label});const A=T.get(F.id);return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:(A==null?void 0:A.color)??"#64748b"}}),e.jsx("span",{className:"truncate",children:F.label})]})}})]})})}),e.jsx("div",{className:"border-t border-border/60 px-5 py-4",children:e.jsx(ps,{ref:o,value:g.description,onChange:F=>y(A=>({...A,description:F})),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-[160px] text-sm text-muted-foreground",onSubmit:()=>{!B.isPending&&g.title.trim()&&g.projectId&&g.assigneeAgentId&&B.mutate()}})}),e.jsx("div",{className:"border-t border-border/60 px-5 py-3",children:e.jsxs(Sa,{open:j,onOpenChange:b,children:[e.jsxs(Ia,{className:"flex w-full items-center justify-between text-left",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Advanced delivery settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Keep policy controls secondary to the work definition."})]}),j?e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(sn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(_a,{className:"pt-3",children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Concurrency"}),e.jsxs(Hn,{value:g.concurrencyPolicy,onValueChange:F=>y(A=>({...A,concurrencyPolicy:F})),children:[e.jsx(Qn,{children:e.jsx(Vn,{})}),e.jsx(Gn,{children:NU.map(F=>e.jsx(Mt,{value:F,children:F.replaceAll("_"," ")},F))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:CU[g.concurrencyPolicy]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Catch-up"}),e.jsxs(Hn,{value:g.catchUpPolicy,onValueChange:F=>y(A=>({...A,catchUpPolicy:F})),children:[e.jsx(Qn,{children:e.jsx(Vn,{})}),e.jsx(Gn,{children:kU.map(F=>e.jsx(Mt,{value:F,children:F.replaceAll("_"," ")},F))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:SU[g.catchUpPolicy]})]})]})})]})})]}),e.jsxs("div",{className:"shrink-0 flex flex-col gap-3 border-t border-border/60 px-5 py-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"After creation, CrewSpace takes you straight to trigger setup for schedules, webhooks, or internal runs."}),e.jsxs("div",{className:"flex flex-col gap-2 sm:items-end",children:[e.jsxs(G,{onClick:()=>B.mutate(),disabled:B.isPending||!g.title.trim()||!g.projectId||!g.assigneeAgentId,children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),B.isPending?"Creating...":"Create routine"]}),B.isError?e.jsx("p",{className:"text-sm text-destructive",children:B.error instanceof Error?B.error.message:"Failed to create routine"}):null]})]})]})}),E?e.jsx(jn,{children:e.jsx(wn,{className:"pt-6 text-sm text-destructive",children:E instanceof Error?E.message:"Failed to load routines"})}):null,e.jsx("div",{children:(v??[]).length===0?e.jsx("div",{className:"py-12",children:e.jsx(tn,{icon:nl,message:"No routines yet. Use Create routine to define the first recurring workflow."})}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-xs text-muted-foreground border-b border-border",children:[e.jsx("th",{className:"px-3 py-2 font-medium",children:"Name"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Project"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Agent"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Last run"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Enabled"}),e.jsx("th",{className:"w-12 px-3 py-2"})]})}),e.jsx("tbody",{children:(v??[]).map(F=>{var H,U,Z;const A=F.status==="active",R=F.status==="archived",Q=p===F.id;return e.jsxs("tr",{className:"align-middle border-b border-border transition-colors hover:bg-accent/50 last:border-b-0 cursor-pointer",onClick:()=>r(`/routines/${F.id}`),children:[e.jsx("td",{className:"px-3 py-2.5",children:e.jsxs("div",{className:"min-w-[180px]",children:[e.jsx("span",{className:"font-medium",children:F.title}),(R||F.status==="paused")&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:R?"archived":"paused"})]})}),e.jsx("td",{className:"px-3 py-2.5",children:F.projectId?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:((H=T.get(F.projectId))==null?void 0:H.color)??"#6366f1"}}),e.jsx("span",{className:"truncate",children:((U=T.get(F.projectId))==null?void 0:U.name)??"Unknown"})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx("td",{className:"px-3 py-2.5",children:F.assigneeAgentId?(()=>{const V=K.get(F.assigneeAgentId);return V?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Cn,{icon:V.icon,className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:V.name})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Unknown"})})():e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"px-3 py-2.5 text-muted-foreground",children:[e.jsx("div",{children:IU((Z=F.lastRun)==null?void 0:Z.triggeredAt)}),F.lastRun?e.jsx("div",{className:"mt-1 text-xs",children:F.lastRun.status.replaceAll("_"," ")}):null]}),e.jsx("td",{className:"px-3 py-2.5",onClick:V=>V.stopPropagation(),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":A,"aria-label":A?`Disable ${F.title}`:`Enable ${F.title}`,disabled:Q||R,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${A?"bg-foreground":"bg-muted"} ${Q||R?"cursor-not-allowed opacity-50":""}`,onClick:()=>k.mutate({id:F.id,status:_U(F.status,!A)}),children:e.jsx("span",{className:`inline-block h-5 w-5 rounded-full bg-background shadow-sm transition-transform ${A?"translate-x-5":"translate-x-0.5"}`})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:R?"Archived":A?"On":"Off"})]})}),e.jsx("td",{className:"px-3 py-2.5 text-right",onClick:V=>V.stopPropagation(),children:e.jsxs(gl,{children:[e.jsx(bl,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon-sm","aria-label":`More actions for ${F.title}`,children:e.jsx(xi,{className:"h-4 w-4"})})}),e.jsxs(yl,{align:"end",children:[e.jsx(Os,{onClick:()=>r(`/routines/${F.id}`),children:"Edit"}),e.jsx(Os,{disabled:d===F.id||R,onClick:()=>L.mutate(F.id),children:d===F.id?"Running...":"Run now"}),e.jsx(au,{}),e.jsx(Os,{onClick:()=>k.mutate({id:F.id,status:A?"paused":"active"}),disabled:Q||R,children:A?"Pause":"Enable"}),e.jsx(Os,{onClick:()=>k.mutate({id:F.id,status:F.status==="archived"?"active":"archived"}),disabled:Q,children:F.status==="archived"?"Restore":"Archive"})]})]})})]},F.id)})})]})})})]}):e.jsx(tn,{icon:nl,message:"Select a company to view routines."})}function EU(t,n,s){const r={label:n.label.trim()||null};return t.kind==="schedule"&&(r.cronExpression=n.cronExpression.trim(),r.timezone=t.timezone??s),t.kind==="webhook"&&(r.signingMode=n.signingMode,r.replayWindowSec=Number(n.replayWindowSec||"300")),r}const TU=[{value:"every_minute",label:"Every minute"},{value:"every_hour",label:"Every hour"},{value:"every_day",label:"Every day"},{value:"weekdays",label:"Weekdays"},{value:"weekly",label:"Weekly"},{value:"monthly",label:"Monthly"},{value:"custom",label:"Custom (cron)"}],RU=Array.from({length:24},(t,n)=>({value:String(n),label:n===0?"12 AM":n<12?`${n} AM`:n===12?"12 PM":`${n-12} PM`})),zg=Array.from({length:12},(t,n)=>({value:String(n*5),label:String(n*5).padStart(2,"0")})),PU=[{value:"1",label:"Mon"},{value:"2",label:"Tue"},{value:"3",label:"Wed"},{value:"4",label:"Thu"},{value:"5",label:"Fri"},{value:"6",label:"Sat"},{value:"0",label:"Sun"}],MU=Array.from({length:31},(t,n)=>({value:String(n+1),label:String(n+1)}));function Wg(t){const n={hour:"10",minute:"0",dayOfWeek:"1",dayOfMonth:"1"};if(!t||!t.trim())return{preset:"every_day",...n};const s=t.trim().split(/\s+/);if(s.length!==5)return{preset:"custom",...n};const[r,a,o,,i]=s;return r==="*"&&a==="*"&&o==="*"&&i==="*"?{preset:"every_minute",...n}:a==="*"&&o==="*"&&i==="*"?{preset:"every_hour",...n,minute:r==="*"?"0":r}:o==="*"&&i==="*"&&a!=="*"?{preset:"every_day",...n,hour:a,minute:r==="*"?"0":r}:o==="*"&&i==="1-5"&&a!=="*"?{preset:"weekdays",...n,hour:a,minute:r==="*"?"0":r}:o==="*"&&/^\d$/.test(i)&&a!=="*"?{preset:"weekly",...n,hour:a,minute:r==="*"?"0":r,dayOfWeek:i}:/^\d{1,2}$/.test(o)&&i==="*"&&a!=="*"?{preset:"monthly",...n,hour:a,minute:r==="*"?"0":r,dayOfMonth:o}:{preset:"custom",...n}}function $U(t,n,s,r,a){switch(t){case"every_minute":return"* * * * *";case"every_hour":return`${s} * * * *`;case"every_day":return`${s} ${n} * * *`;case"weekdays":return`${s} ${n} * * 1-5`;case"weekly":return`${s} ${n} * * ${r}`;case"monthly":return`${s} ${n} ${a} * *`;case"custom":return""}}function wN({value:t,onChange:n}){const s=c.useMemo(()=>Wg(t),[t]),[r,a]=c.useState(s.preset),[o,i]=c.useState(s.hour),[l,u]=c.useState(s.minute),[d,m]=c.useState(s.dayOfWeek),[p,x]=c.useState(s.dayOfMonth),[f,h]=c.useState(r==="custom"?t:"");c.useEffect(()=>{const g=Wg(t);a(g.preset),i(g.hour),u(g.minute),m(g.dayOfWeek),x(g.dayOfMonth),g.preset==="custom"&&h(t)},[t]);const j=c.useCallback((g,y,v,_,E,S)=>{n(g==="custom"?S:$U(g,y,v,_,E))},[n]),b=g=>{a(g),g==="custom"?h(t):j(g,o,l,d,p,f)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Hn,{value:r,onValueChange:g=>b(g),children:[e.jsx(Qn,{className:"w-full",children:e.jsx(Vn,{placeholder:"Choose frequency..."})}),e.jsx(Gn,{children:TU.map(g=>e.jsx(Mt,{value:g.value,children:g.label},g.value))})]}),r==="custom"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Xt,{value:f,onChange:g=>{h(g.target.value),j("custom",o,l,d,p,g.target.value)},placeholder:"0 10 * * *",className:"font-mono text-sm"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Five fields: minute hour day-of-month month day-of-week"})]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r!=="every_minute"&&r!=="every_hour"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"at"}),e.jsxs(Hn,{value:o,onValueChange:g=>{i(g),j(r,g,l,d,p,f)},children:[e.jsx(Qn,{className:"w-[120px]",children:e.jsx(Vn,{})}),e.jsx(Gn,{children:RU.map(g=>e.jsx(Mt,{value:g.value,children:g.label},g.value))})]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:":"}),e.jsxs(Hn,{value:l,onValueChange:g=>{u(g),j(r,o,g,d,p,f)},children:[e.jsx(Qn,{className:"w-[80px]",children:e.jsx(Vn,{})}),e.jsx(Gn,{children:zg.map(g=>e.jsx(Mt,{value:g.value,children:g.label},g.value))})]})]}),r==="every_hour"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"at minute"}),e.jsxs(Hn,{value:l,onValueChange:g=>{u(g),j(r,o,g,d,p,f)},children:[e.jsx(Qn,{className:"w-[80px]",children:e.jsx(Vn,{})}),e.jsx(Gn,{children:zg.map(g=>e.jsxs(Mt,{value:g.value,children:[":",g.label]},g.value))})]})]}),r==="weekly"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"on"}),e.jsx("div",{className:"flex gap-1",children:PU.map(g=>e.jsx(G,{type:"button",variant:d===g.value?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{m(g.value),j(r,o,l,g.value,p,f)},children:g.label},g.value))})]}),r==="monthly"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"on day"}),e.jsxs(Hn,{value:p,onValueChange:g=>{x(g),j(r,o,l,d,g,f)},children:[e.jsx(Qn,{className:"w-[80px]",children:e.jsx(Vn,{})}),e.jsx(Gn,{children:MU.map(g=>e.jsx(Mt,{value:g.value,children:g.label},g.value))})]})]})]})]})}function En({className:t,...n}){return e.jsx(AI,{"data-slot":"label",className:O("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...n})}const DU=Cp("inline-flex items-center justify-center rounded-full border border-transparent px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",ghost:"[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",link:"text-primary underline-offset-4 [a&]:hover:underline"}},defaultVariants:{variant:"default"}});function Wt({className:t,variant:n="default",asChild:s=!1,...r}){const a=s?gp:"span";return e.jsx(a,{"data-slot":"badge","data-variant":n,className:O(DU({variant:n}),t),...r})}const OU=["coalesce_if_active","always_enqueue","skip_if_active"],LU=["skip_missed","enqueue_missed_with_cap"],FU=["schedule","webhook"],NN=["bearer","hmac_sha256"],qU=["triggers","runs","activity"],UU={coalesce_if_active:"Keep one follow-up run queued while an active run is still working.",always_enqueue:"Queue every trigger occurrence, even if several runs stack up.",skip_if_active:"Drop overlapping trigger occurrences while the routine is already active."},BU={skip_missed:"Ignore schedule windows that were missed while the routine or scheduler was paused.",enqueue_missed_with_cap:"Catch up missed schedule windows in capped batches after recovery."},KU={bearer:"Expect a shared bearer token in the Authorization header.",hmac_sha256:"Expect an HMAC SHA-256 signature over the request using the shared secret."};function Hg(t){t&&(t.style.height="auto",t.style.height=`${t.scrollHeight}px`)}function kN(t){return t!==null&&qU.includes(t)}function zU(t){const n=new URLSearchParams(t).get("tab");return kN(n)?n:"triggers"}function CN(t){if(t===null)return"null";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":t.map(n=>CN(n)).join(", ");try{return JSON.stringify(t)}catch{return"[unserializable]"}}function SN(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function WU({trigger:t,onSave:n,onRotate:s,onDelete:r}){const[a,o]=c.useState({label:t.label??"",cronExpression:t.cronExpression??"",signingMode:t.signingMode??"bearer",replayWindowSec:String(t.replayWindowSec??300)});return c.useEffect(()=>{o({label:t.label??"",cronExpression:t.cronExpression??"",signingMode:t.signingMode??"bearer",replayWindowSec:String(t.replayWindowSec??300)})},[t]),e.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[t.kind==="schedule"?e.jsx(Nl,{className:"h-3.5 w-3.5"}):t.kind==="webhook"?e.jsx(ry,{className:"h-3.5 w-3.5"}):e.jsx(Xo,{className:"h-3.5 w-3.5"}),t.label??t.kind]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:t.kind==="schedule"&&t.nextRunAt?`Next: ${new Date(t.nextRunAt).toLocaleString()}`:t.kind==="webhook"?"Webhook":"API"})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Label"}),e.jsx(Xt,{value:a.label,onChange:i=>o(l=>({...l,label:i.target.value}))})]}),t.kind==="schedule"&&e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Schedule"}),e.jsx(wN,{value:a.cronExpression,onChange:i=>o(l=>({...l,cronExpression:i}))})]}),t.kind==="webhook"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Signing mode"}),e.jsxs(Hn,{value:a.signingMode,onValueChange:i=>o(l=>({...l,signingMode:i})),children:[e.jsx(Qn,{children:e.jsx(Vn,{})}),e.jsx(Gn,{children:NN.map(i=>e.jsx(Mt,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Replay window (seconds)"}),e.jsx(Xt,{value:a.replayWindowSec,onChange:i=>o(l=>({...l,replayWindowSec:i.target.value}))})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.lastResult&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last: ",t.lastResult]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[t.kind==="webhook"&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>s(t.id),children:[e.jsx(Za,{className:"mr-1.5 h-3.5 w-3.5"}),"Rotate secret"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>n(t.id,EU(t,a,SN())),children:[e.jsx(Lp,{className:"mr-1.5 h-3.5 w-3.5"}),"Save"]}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-destructive",onClick:()=>r(t.id),children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]})]})}function HU(){var q;const{routineId:t}=Xn(),{selectedCompanyId:n}=et(),{setBreadcrumbs:s}=Ft(),r=at(),a=Sn(),o=fn(),{pushToast:i}=ds(),l=c.useRef(null),u=c.useRef(null),d=c.useRef(null),m=c.useRef(null),p=c.useRef(null),[x,f]=c.useState(null),[h,j]=c.useState(!1),[b,g]=c.useState({kind:"schedule",cronExpression:"0 10 * * *",signingMode:"bearer",replayWindowSec:"300"}),[y,v]=c.useState({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed"}),_=c.useMemo(()=>zU(o.search),[o.search]),{data:E,isLoading:S,error:M}=oe({queryKey:N.routines.detail(t),queryFn:()=>ys.get(t),enabled:!!t}),B=(q=E==null?void 0:E.activeIssue)==null?void 0:q.id,{data:k}=oe({queryKey:N.issues.liveRuns(B),queryFn:()=>Yt.liveRunsForIssue(B),enabled:!!B,refetchInterval:3e3}),L=(k??[]).length>0,{data:$}=oe({queryKey:N.routines.runs(t),queryFn:()=>ys.listRuns(t),enabled:!!t,refetchInterval:L?3e3:!1}),C=c.useMemo(()=>({triggerIds:(E==null?void 0:E.triggers.map(D=>D.id))??[],runIds:($==null?void 0:$.map(D=>D.id))??[]}),[E==null?void 0:E.triggers,$]),{data:I}=oe({queryKey:[...N.routines.activity(n,t),C.triggerIds.join(","),C.runIds.join(",")],queryFn:()=>ys.activity(n,t,C),enabled:!!n&&!!t&&!!E}),{data:K}=oe({queryKey:N.agents.list(n),queryFn:()=>We.list(n),enabled:!!n}),{data:T}=oe({queryKey:N.projects.list(n),queryFn:()=>en.list(n),enabled:!!n}),z=c.useMemo(()=>E?{title:E.title,description:E.description??"",projectId:E.projectId,assigneeAgentId:E.assigneeAgentId,priority:E.priority,concurrencyPolicy:E.concurrencyPolicy,catchUpPolicy:E.catchUpPolicy}:null,[E]),w=c.useMemo(()=>z?y.title!==z.title||y.description!==z.description||y.projectId!==z.projectId||y.assigneeAgentId!==z.assigneeAgentId||y.priority!==z.priority||y.concurrencyPolicy!==z.concurrencyPolicy||y.catchUpPolicy!==z.catchUpPolicy:!1,[y,z]);c.useEffect(()=>{if(!E||(s([{label:"Routines",href:"/routines"},{label:E.title}]),!z))return;(l.current!==E.id||!w)&&(v(z),l.current=E.id)},[E,z,w,s]),c.useEffect(()=>{Hg(u.current)},[y.title,E==null?void 0:E.id]);const F=async(D,ie)=>{try{await navigator.clipboard.writeText(ie),i({title:`${D} copied`,tone:"success"})}catch(Ie){i({title:`Failed to copy ${D.toLowerCase()}`,body:Ie instanceof Error?Ie.message:"Clipboard access was denied.",tone:"error"})}},A=D=>{if(!t||!kN(D))return;const ie=new URLSearchParams(o.search);D==="triggers"?ie.delete("tab"):ie.set("tab",D);const Ie=ie.toString();a({pathname:o.pathname,search:Ie?`?${Ie}`:""},{replace:!0})},R=ge({mutationFn:()=>ys.update(t,{...y,description:y.description.trim()||null}),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:N.routines.detail(t)}),r.invalidateQueries({queryKey:N.routines.list(n)}),r.invalidateQueries({queryKey:N.routines.activity(n,t)})])},onError:D=>{i({title:"Failed to save routine",body:D instanceof Error?D.message:"CrewSpace could not save the routine.",tone:"error"})}}),Q=ge({mutationFn:()=>ys.run(t),onSuccess:async()=>{i({title:"Routine run started",tone:"success"}),A("runs"),await Promise.all([r.invalidateQueries({queryKey:N.routines.detail(t)}),r.invalidateQueries({queryKey:N.routines.runs(t)}),r.invalidateQueries({queryKey:N.routines.list(n)}),r.invalidateQueries({queryKey:N.routines.activity(n,t)})])},onError:D=>{i({title:"Routine run failed",body:D instanceof Error?D.message:"CrewSpace could not start the routine run.",tone:"error"})}}),H=ge({mutationFn:D=>ys.update(t,{status:D}),onSuccess:async(D,ie)=>{i({title:"Routine saved",body:ie==="paused"?"Automation paused.":"Automation enabled.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:N.routines.detail(t)}),r.invalidateQueries({queryKey:N.routines.list(n)})])},onError:D=>{i({title:"Failed to update routine",body:D instanceof Error?D.message:"CrewSpace could not update the routine.",tone:"error"})}}),U=ge({mutationFn:async()=>{const D=((E==null?void 0:E.triggers)??[]).filter(Ie=>Ie.kind===b.kind).length,ie=D>0?`${b.kind}-${D+1}`:b.kind;return ys.createTrigger(t,{kind:b.kind,label:ie,...b.kind==="schedule"?{cronExpression:b.cronExpression.trim(),timezone:SN()}:{},...b.kind==="webhook"?{signingMode:b.signingMode,replayWindowSec:Number(b.replayWindowSec||"300")}:{}})},onSuccess:async D=>{D.secretMaterial&&f({title:"Webhook trigger created",webhookUrl:D.secretMaterial.webhookUrl,webhookSecret:D.secretMaterial.webhookSecret}),await Promise.all([r.invalidateQueries({queryKey:N.routines.detail(t)}),r.invalidateQueries({queryKey:N.routines.list(n)}),r.invalidateQueries({queryKey:N.routines.activity(n,t)})])},onError:D=>{i({title:"Failed to add trigger",body:D instanceof Error?D.message:"CrewSpace could not create the trigger.",tone:"error"})}}),Z=ge({mutationFn:({id:D,patch:ie})=>ys.updateTrigger(D,ie),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:N.routines.detail(t)}),r.invalidateQueries({queryKey:N.routines.list(n)}),r.invalidateQueries({queryKey:N.routines.activity(n,t)})])},onError:D=>{i({title:"Failed to update trigger",body:D instanceof Error?D.message:"CrewSpace could not update the trigger.",tone:"error"})}}),V=ge({mutationFn:D=>ys.deleteTrigger(D),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:N.routines.detail(t)}),r.invalidateQueries({queryKey:N.routines.list(n)}),r.invalidateQueries({queryKey:N.routines.activity(n,t)})])},onError:D=>{i({title:"Failed to delete trigger",body:D instanceof Error?D.message:"CrewSpace could not delete the trigger.",tone:"error"})}}),W=ge({mutationFn:D=>ys.rotateTriggerSecret(D),onSuccess:async D=>{f({title:"Webhook secret rotated",webhookUrl:D.secretMaterial.webhookUrl,webhookSecret:D.secretMaterial.webhookSecret}),await Promise.all([r.invalidateQueries({queryKey:N.routines.detail(t)}),r.invalidateQueries({queryKey:N.routines.activity(n,t)})])},onError:D=>{i({title:"Failed to rotate webhook secret",body:D instanceof Error?D.message:"CrewSpace could not rotate the webhook secret.",tone:"error"})}}),J=c.useMemo(()=>new Map((K??[]).map(D=>[D.id,D])),[K]),Y=c.useMemo(()=>new Map((T??[]).map(D=>[D.id,D])),[T]),de=c.useMemo(()=>Ol(),[E==null?void 0:E.id]),fe=c.useMemo(()=>eu((K??[]).filter(D=>D.status!=="terminated"),de).map(D=>({id:D.id,label:D.name,searchText:`${D.name} ${D.role} ${D.title??""}`})),[K,de]),Ce=c.useMemo(()=>(T??[]).map(D=>({id:D.id,label:D.name,searchText:D.description??""})),[T]),le=y.assigneeAgentId?J.get(y.assigneeAgentId)??null:null,Re=y.projectId?Y.get(y.projectId)??null:null;if(!n)return e.jsx(tn,{icon:nl,message:"Select a company to view routines."});if(S)return e.jsx(mn,{variant:"issues-list"});if(M||!E)return e.jsx("p",{className:"pt-6 text-sm text-destructive",children:M instanceof Error?M.message:"Routine not found"});const Pe=E.status==="active",Fe=H.isPending||E.status==="archived",pe=E.status==="archived"?"Archived":Pe?"Active":"Paused",Le=E.status==="archived"?"text-muted-foreground":Pe?"text-emerald-400":"text-muted-foreground";return e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("textarea",{ref:u,className:"flex-1 min-w-0 resize-none overflow-hidden bg-transparent text-xl font-bold outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:y.title,onChange:D=>{v(ie=>({...ie,title:D.target.value})),Hg(D.target)},onKeyDown:D=>{var ie,Ie,ue,Be;if(D.key==="Enter"&&!D.metaKey&&!D.ctrlKey&&!D.nativeEvent.isComposing){D.preventDefault(),(ie=d.current)==null||ie.focus();return}D.key==="Tab"&&!D.shiftKey&&(D.preventDefault(),y.assigneeAgentId?y.projectId?(Ie=d.current)==null||Ie.focus():(ue=p.current)==null||ue.focus():(Be=m.current)==null||Be.focus())}}),e.jsxs("div",{className:"flex shrink-0 items-center gap-3 pt-1",children:[e.jsx(Zw,{onClick:()=>Q.mutate(),disabled:Q.isPending}),e.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":Pe,"aria-label":Pe?"Pause automatic triggers":"Enable automatic triggers",disabled:Fe,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${Pe?"bg-emerald-500":"bg-muted"} ${Fe?"cursor-not-allowed opacity-50":""}`,onClick:()=>H.mutate(Pe?"paused":"active"),children:e.jsx("span",{className:`inline-block h-5 w-5 rounded-full bg-background shadow-sm transition-transform ${Pe?"translate-x-5":"translate-x-0.5"}`})}),e.jsx("span",{className:`min-w-[3.75rem] text-sm font-medium ${Le}`,children:pe})]})]}),x&&e.jsxs("div",{className:"rounded-lg border border-blue-500/30 bg-blue-500/5 p-4 space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:x.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Save this now. CrewSpace will not show the secret value again."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{value:x.webhookUrl,readOnly:!0,className:"flex-1"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>F("Webhook URL",x.webhookUrl),children:[e.jsx(_s,{className:"h-3.5 w-3.5 mr-1"}),"URL"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{value:x.webhookSecret,readOnly:!0,className:"flex-1"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>F("Webhook secret",x.webhookSecret),children:[e.jsx(_s,{className:"h-3.5 w-3.5 mr-1"}),"Secret"]})]})]})]}),e.jsx("div",{className:"overflow-x-auto overscroll-x-contain",children:e.jsxs("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[e.jsx("span",{children:"For"}),e.jsx(ba,{ref:m,value:y.assigneeAgentId,options:fe,placeholder:"Assignee",noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:D=>{D&&Xd(D),v(ie=>({...ie,assigneeAgentId:D}))},onConfirm:()=>{var D,ie;y.projectId?(D=d.current)==null||D.focus():(ie=p.current)==null||ie.focus()},renderTriggerValue:D=>D?le?e.jsxs(e.Fragment,{children:[e.jsx(Cn,{icon:le.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:D.label})]}):e.jsx("span",{className:"truncate",children:D.label}):e.jsx("span",{className:"text-muted-foreground",children:"Assignee"}),renderOption:D=>{if(!D.id)return e.jsx("span",{className:"truncate",children:D.label});const ie=J.get(D.id);return e.jsxs(e.Fragment,{children:[ie?e.jsx(Cn,{icon:ie.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,e.jsx("span",{className:"truncate",children:D.label})]})}}),e.jsx("span",{children:"in"}),e.jsx(ba,{ref:p,value:y.projectId,options:Ce,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:D=>v(ie=>({...ie,projectId:D})),onConfirm:()=>{var D;return(D=d.current)==null?void 0:D.focus()},renderTriggerValue:D=>D&&Re?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:Re.color??"#64748b"}}),e.jsx("span",{className:"truncate",children:D.label})]}):e.jsx("span",{className:"text-muted-foreground",children:"Project"}),renderOption:D=>{if(!D.id)return e.jsx("span",{className:"truncate",children:D.label});const ie=Y.get(D.id);return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:(ie==null?void 0:ie.color)??"#64748b"}}),e.jsx("span",{className:"truncate",children:D.label})]})}})]})}),e.jsx(ps,{ref:d,value:y.description,onChange:D=>v(ie=>({...ie,description:D})),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-[120px] text-[15px] leading-7",onSubmit:()=>{!R.isPending&&y.title.trim()&&y.projectId&&y.assigneeAgentId&&R.mutate()}}),e.jsxs(Sa,{open:h,onOpenChange:j,children:[e.jsxs(Ia,{className:"flex w-full items-center justify-between text-left",children:[e.jsx("span",{className:"text-sm font-medium",children:"Advanced delivery settings"}),h?e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(sn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(_a,{className:"pt-3",children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Concurrency"}),e.jsxs(Hn,{value:y.concurrencyPolicy,onValueChange:D=>v(ie=>({...ie,concurrencyPolicy:D})),children:[e.jsx(Qn,{children:e.jsx(Vn,{})}),e.jsx(Gn,{children:OU.map(D=>e.jsx(Mt,{value:D,children:D.replaceAll("_"," ")},D))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:UU[y.concurrencyPolicy]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Catch-up"}),e.jsxs(Hn,{value:y.catchUpPolicy,onValueChange:D=>v(ie=>({...ie,catchUpPolicy:D})),children:[e.jsx(Qn,{children:e.jsx(Vn,{})}),e.jsx(Gn,{children:LU.map(D=>e.jsx(Mt,{value:D,children:D.replaceAll("_"," ")},D))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:BU[y.catchUpPolicy]})]})]})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[w?e.jsx("span",{className:"text-xs text-amber-600",children:"Unsaved changes"}):e.jsx("span",{}),e.jsxs(G,{onClick:()=>R.mutate(),disabled:R.isPending||!y.title.trim()||!y.projectId||!y.assigneeAgentId,children:[e.jsx(Lp,{className:"mr-2 h-4 w-4"}),"Save routine"]})]}),e.jsx(yn,{}),e.jsxs(Ss,{value:_,onValueChange:A,className:"space-y-3",children:[e.jsxs(co,{variant:"line",className:"w-full justify-start gap-1",children:[e.jsxs(An,{value:"triggers",className:"gap-1.5",children:[e.jsx(Nl,{className:"h-3.5 w-3.5"}),"Triggers"]}),e.jsxs(An,{value:"runs",className:"gap-1.5",children:[e.jsx(Dp,{className:"h-3.5 w-3.5"}),"Runs",L&&e.jsx("span",{className:"h-2 w-2 rounded-full bg-blue-500 animate-pulse"})]}),e.jsxs(An,{value:"activity",className:"gap-1.5",children:[e.jsx(ny,{className:"h-3.5 w-3.5"}),"Activity"]})]}),e.jsxs(on,{value:"triggers",className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Add trigger"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Kind"}),e.jsxs(Hn,{value:b.kind,onValueChange:D=>g(ie=>({...ie,kind:D})),children:[e.jsx(Qn,{children:e.jsx(Vn,{})}),e.jsx(Gn,{children:FU.map(D=>e.jsxs(Mt,{value:D,disabled:D==="webhook",children:[D,D==="webhook"?" — COMING SOON":""]},D))})]})]}),b.kind==="schedule"&&e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Schedule"}),e.jsx(wN,{value:b.cronExpression,onChange:D=>g(ie=>({...ie,cronExpression:D}))})]}),b.kind==="webhook"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Signing mode"}),e.jsxs(Hn,{value:b.signingMode,onValueChange:D=>g(ie=>({...ie,signingMode:D})),children:[e.jsx(Qn,{children:e.jsx(Vn,{})}),e.jsx(Gn,{children:NN.map(D=>e.jsx(Mt,{value:D,children:D},D))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:KU[b.signingMode]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(En,{className:"text-xs",children:"Replay window (seconds)"}),e.jsx(Xt,{value:b.replayWindowSec,onChange:D=>g(ie=>({...ie,replayWindowSec:D.target.value}))})]})]})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(G,{size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:U.isPending?"Adding...":"Add trigger"})})]}),E.triggers.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No triggers configured yet."}):e.jsx("div",{className:"space-y-3",children:E.triggers.map(D=>e.jsx(WU,{trigger:D,onSave:(ie,Ie)=>Z.mutate({id:ie,patch:Ie}),onRotate:ie=>W.mutate(ie),onDelete:ie=>V.mutate(ie)},D.id))})]}),e.jsxs(on,{value:"runs",className:"space-y-4",children:[L&&B&&E&&e.jsx(gN,{issueId:B,companyId:E.companyId}),($??[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No runs yet."}):e.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:($??[]).map(D=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Wt,{variant:"outline",className:"shrink-0",children:D.source}),e.jsx(Wt,{variant:D.status==="failed"?"destructive":"secondary",className:"shrink-0",children:D.status.replaceAll("_"," ")}),D.trigger&&e.jsx("span",{className:"text-muted-foreground truncate",children:D.trigger.label??D.trigger.kind}),D.linkedIssue&&e.jsx(Oe,{to:`/issues/${D.linkedIssue.identifier??D.linkedIssue.id}`,className:"text-muted-foreground hover:underline truncate",children:D.linkedIssue.identifier??D.linkedIssue.id.slice(0,8)})]}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0 ml-2",children:as(D.triggeredAt)})]},D.id))})]}),e.jsx(on,{value:"activity",children:(I??[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):e.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:(I??[]).map(D=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-xs gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"font-medium text-foreground/90 shrink-0",children:D.action.replaceAll("."," ")}),D.details&&Object.keys(D.details).length>0&&e.jsx("span",{className:"text-muted-foreground truncate",children:Object.entries(D.details).slice(0,3).map(([ie,Ie],ue)=>e.jsxs("span",{children:[ue>0&&e.jsx("span",{className:"mx-1 text-border",children:"·"}),e.jsxs("span",{className:"text-muted-foreground/70",children:[ie.replaceAll("_"," "),":"]})," ",CN(Ie)]},ie))})]}),e.jsx("span",{className:"text-muted-foreground/60 shrink-0",children:as(D.createdAt)})]},D.id))})})]})]})}function VU(t){if(!t)return!1;try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function ea(t){return t??""}function QU(t){return!t||Object.keys(t).length===0?"":JSON.stringify(t,null,2)}function yc(t){const n=t.trim();return n.length>0?n:null}function IN(t){const n=t.trim();if(!n)return{ok:!0,value:null};try{const s=JSON.parse(n);return!s||typeof s!="object"||Array.isArray(s)?{ok:!1,error:"Workspace runtime JSON must be a JSON object."}:{ok:!0,value:s}}catch(s){return{ok:!1,error:s instanceof Error?s.message:"Invalid JSON."}}}function Vg(t){var n,s,r,a,o;return{name:t.name,cwd:ea(t.cwd),repoUrl:ea(t.repoUrl),baseRef:ea(t.baseRef),branchName:ea(t.branchName),providerRef:ea(t.providerRef),provisionCommand:ea((n=t.config)==null?void 0:n.provisionCommand),teardownCommand:ea((s=t.config)==null?void 0:s.teardownCommand),cleanupCommand:ea((r=t.config)==null?void 0:r.cleanupCommand),inheritRuntime:!((a=t.config)!=null&&a.workspaceRuntime),workspaceRuntime:QU((o=t.config)==null?void 0:o.workspaceRuntime)}}function GU(t,n){const s={},r={},a=i=>{t[i]!==n[i]&&(s[i]=i==="name"?yc(n[i])??t.name:yc(n[i]))};a("name"),a("cwd"),a("repoUrl"),a("baseRef"),a("branchName"),a("providerRef");const o=i=>{t[i]!==n[i]&&(r[i]=yc(n[i]))};if(o("provisionCommand"),o("teardownCommand"),o("cleanupCommand"),t.inheritRuntime!==n.inheritRuntime||t.workspaceRuntime!==n.workspaceRuntime){const i=IN(n.workspaceRuntime);if(!i.ok)throw new Error(i.error);r.workspaceRuntime=n.inheritRuntime?null:i.value}return Object.keys(r).length>0&&(s.config=r),s}function JU(t){const n=yc(t.repoUrl);if(n)try{new URL(n)}catch{return"Repo URL must be a valid URL."}if(!t.inheritRuntime){const s=IN(t.workspaceRuntime);if(!s.ok)return s.error}return null}function fr({label:t,hint:n,children:s}){return e.jsxs("label",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-3",children:[e.jsx("span",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:t}),n?e.jsx("span",{className:"text-[11px] leading-relaxed text-muted-foreground sm:text-right",children:n}):null]}),s]})}function Rs({label:t,children:n}){return e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 sm:flex-row sm:items-start sm:gap-3",children:[e.jsx("div",{className:"shrink-0 text-xs text-muted-foreground sm:w-32",children:t}),e.jsx("div",{className:"min-w-0 flex-1 text-sm",children:n})]})}function Da({children:t,className:n}){return e.jsx("div",{className:O("inline-flex items-center rounded-full border border-border bg-background px-2.5 py-1 text-xs text-muted-foreground",n),children:t})}function Ks({value:t,copy:n}){return e.jsxs("div",{className:"inline-flex max-w-full items-start gap-2",children:[e.jsx("span",{className:"break-all font-mono text-xs",children:t}),n?e.jsx(uo,{text:t,className:"shrink-0 text-muted-foreground hover:text-foreground",copiedLabel:"Copied",children:e.jsx(_s,{className:"h-3.5 w-3.5"})}):null]})}function ZU({project:t,workspace:n}){return e.jsx(Oe,{to:Ud(t,n.id),className:"hover:underline",children:n.name})}function YU(){var F,A,R,Q,H;const{workspaceId:t}=Xn(),n=at(),{setBreadcrumbs:s}=Ft(),{selectedCompanyId:r,setSelectedCompanyId:a}=et(),[o,i]=c.useState(null),[l,u]=c.useState(!1),[d,m]=c.useState(null),[p,x]=c.useState(null),f=oe({queryKey:N.executionWorkspaces.detail(t),queryFn:()=>or.get(t),enabled:!!t}),h=f.data??null,b=oe({queryKey:h?[...N.projects.detail(h.projectId),h.companyId]:["projects","detail","__pending__"],queryFn:()=>en.get(h.projectId,h.companyId),enabled:!!(h!=null&&h.projectId)}).data??null,y=oe({queryKey:h!=null&&h.sourceIssueId?N.issues.detail(h.sourceIssueId):["issues","detail","__none__"],queryFn:()=>nt.get(h.sourceIssueId),enabled:!!(h!=null&&h.sourceIssueId)}).data??null,_=oe({queryKey:h!=null&&h.derivedFromExecutionWorkspaceId?N.executionWorkspaces.detail(h.derivedFromExecutionWorkspaceId):["execution-workspaces","detail","__none__"],queryFn:()=>or.get(h.derivedFromExecutionWorkspaceId),enabled:!!(h!=null&&h.derivedFromExecutionWorkspaceId)}).data??null,E=oe({queryKey:h?N.issues.listByExecutionWorkspace(h.companyId,h.id):["issues","__execution-workspace__","__none__"],queryFn:()=>nt.list(h.companyId,{executionWorkspaceId:h.id}),enabled:!!(h!=null&&h.companyId)}),S=E.data??[],M=c.useMemo(()=>(b==null?void 0:b.workspaces.find(U=>U.id===(h==null?void 0:h.projectWorkspaceId)))??null,[b,h==null?void 0:h.projectWorkspaceId]),B=((F=M==null?void 0:M.runtimeConfig)==null?void 0:F.workspaceRuntime)??null,k=((A=h==null?void 0:h.config)==null?void 0:A.workspaceRuntime)??B,L=(R=h==null?void 0:h.config)!=null&&R.workspaceRuntime?"execution_workspace":B?"project_workspace":"none",$=c.useMemo(()=>h?Vg(h):null,[h]),C=!!(o&&$&&JSON.stringify(o)!==JSON.stringify($)),I=b?Al(b):(h==null?void 0:h.projectId)??"";c.useEffect(()=>{!(h!=null&&h.companyId)||h.companyId===r||a(h.companyId,{source:"route_sync"})},[h==null?void 0:h.companyId,r,a]),c.useEffect(()=>{h&&(i(Vg(h)),m(null))},[h]),c.useEffect(()=>{if(!h)return;const U=[{label:"Projects",href:"/projects"},...b?[{label:b.name,href:`/projects/${I}`}]:[],...b?[{label:"Workspaces",href:`/projects/${I}/workspaces`}]:[],{label:h.name}];s(U)},[s,h,b,I]);const K=ge({mutationFn:U=>or.update(h.id,U),onSuccess:U=>{n.setQueryData(N.executionWorkspaces.detail(U.id),U),n.invalidateQueries({queryKey:N.executionWorkspaces.closeReadiness(U.id)}),n.invalidateQueries({queryKey:N.executionWorkspaces.workspaceOperations(U.id)}),b&&(n.invalidateQueries({queryKey:N.projects.detail(b.id)}),n.invalidateQueries({queryKey:N.projects.detail(b.urlKey)})),y&&n.invalidateQueries({queryKey:N.issues.detail(y.id)}),m(null)},onError:U=>{m(U instanceof Error?U.message:"Failed to save execution workspace.")}}),T=oe({queryKey:N.executionWorkspaces.workspaceOperations(t),queryFn:()=>or.listWorkspaceOperations(t),enabled:!!t}),z=ge({mutationFn:U=>or.controlRuntimeServices(h.id,U),onSuccess:(U,Z)=>{n.setQueryData(N.executionWorkspaces.detail(U.workspace.id),U.workspace),n.invalidateQueries({queryKey:N.executionWorkspaces.workspaceOperations(U.workspace.id)}),n.invalidateQueries({queryKey:N.projects.detail(U.workspace.projectId)}),m(null),x(Z==="stop"?"Runtime services stopped.":Z==="restart"?"Runtime services restarted.":"Runtime services started.")},onError:U=>{x(null),m(U instanceof Error?U.message:"Failed to control runtime services.")}});if(f.isLoading)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading workspace…"});if(f.error)return e.jsx("p",{className:"text-sm text-destructive",children:f.error instanceof Error?f.error.message:"Failed to load workspace"});if(!h||!o||!$)return null;const w=()=>{const U=JU(o);if(U){m(U);return}let Z;try{Z=GU($,o)}catch(V){m(V instanceof Error?V.message:"Failed to build workspace update.");return}Object.keys(Z).length!==0&&K.mutate(Z)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(Oe,{to:b?`/projects/${I}/workspaces`:"/projects",children:[e.jsx(fo,{className:"mr-1 h-4 w-4"}),"Back to all workspaces"]})}),e.jsx(Da,{children:h.mode}),e.jsx(Da,{children:h.providerType}),e.jsx(Da,{className:h.status==="active"?"border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300":void 0,children:h.status})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1.4fr)_minmax(18rem,0.95fr)]",children:[e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Execution workspace"}),e.jsx("h1",{className:"text-2xl font-semibold",children:h.name}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Configure the concrete runtime workspace that CrewSpace reuses for this issue flow. These settings stay attached to the execution workspace so future runs can keep local paths, repo refs, provisioning, teardown, and runtime-service behavior in sync with the actual workspace being reused."})]}),e.jsx("div",{className:"flex w-full shrink-0 items-center gap-2 sm:w-auto",children:e.jsx(G,{variant:"outline",className:"w-full sm:w-auto",onClick:()=>u(!0),disabled:h.status==="archived",children:h.status==="cleanup_failed"?"Retry close":"Close workspace"})})]}),e.jsx(yn,{className:"my-5"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(fr,{label:"Workspace name",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none",value:o.name,onChange:U=>i(Z=>Z&&{...Z,name:U.target.value}),placeholder:"Execution workspace name"})}),e.jsx(fr,{label:"Branch name",hint:"Useful for isolated worktrees",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:o.branchName,onChange:U=>i(Z=>Z&&{...Z,branchName:U.target.value}),placeholder:"PAP-946-workspace"})})]}),e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsx(fr,{label:"Working directory",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:o.cwd,onChange:U=>i(Z=>Z&&{...Z,cwd:U.target.value}),placeholder:"/absolute/path/to/workspace"})}),e.jsx(fr,{label:"Provider path / ref",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:o.providerRef,onChange:U=>i(Z=>Z&&{...Z,providerRef:U.target.value}),placeholder:"/path/to/worktree or provider ref"})})]}),e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsx(fr,{label:"Repo URL",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none",value:o.repoUrl,onChange:U=>i(Z=>Z&&{...Z,repoUrl:U.target.value}),placeholder:"https://github.com/org/repo"})}),e.jsx(fr,{label:"Base ref",children:e.jsx("input",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:o.baseRef,onChange:U=>i(Z=>Z&&{...Z,baseRef:U.target.value}),placeholder:"origin/main"})})]}),e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsx(fr,{label:"Provision command",hint:"Runs when CrewSpace prepares this execution workspace",children:e.jsx("textarea",{className:"min-h-28 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:o.provisionCommand,onChange:U=>i(Z=>Z&&{...Z,provisionCommand:U.target.value}),placeholder:"bash ./scripts/provision-worktree.sh"})}),e.jsx(fr,{label:"Teardown command",hint:"Runs when the execution workspace is archived or cleaned up",children:e.jsx("textarea",{className:"min-h-28 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:o.teardownCommand,onChange:U=>i(Z=>Z&&{...Z,teardownCommand:U.target.value}),placeholder:"bash ./scripts/teardown-worktree.sh"})})]}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(fr,{label:"Cleanup command",hint:"Workspace-specific cleanup before teardown",children:e.jsx("textarea",{className:"min-h-24 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none",value:o.cleanupCommand,onChange:U=>i(Z=>Z&&{...Z,cleanupCommand:U.target.value}),placeholder:"pkill -f vite || true"})}),e.jsx("div",{className:"rounded-xl border border-dashed border-border/70 bg-muted/20 px-3 py-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Runtime config source"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:L==="execution_workspace"?"This execution workspace currently overrides the project workspace runtime config.":L==="project_workspace"?"This execution workspace is inheriting the project workspace runtime config.":"No runtime config is currently defined on this execution workspace or its project workspace."})]}),e.jsx(G,{variant:"outline",className:"w-full sm:w-auto",size:"sm",disabled:!((Q=M==null?void 0:M.runtimeConfig)!=null&&Q.workspaceRuntime),onClick:()=>i(U=>U&&{...U,inheritRuntime:!0,workspaceRuntime:""}),children:"Reset to inherit"})]})}),e.jsxs(fr,{label:"Runtime services JSON",hint:"Concrete workspace runtime settings for this execution workspace. Leave this inheriting unless you need a one-off override. If you are missing the right commands, ask your CEO to set them up for you.",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("input",{id:"inherit-runtime-config",type:"checkbox",checked:o.inheritRuntime,onChange:U=>i(Z=>Z&&{...Z,inheritRuntime:U.target.checked})}),e.jsx("label",{htmlFor:"inherit-runtime-config",children:"Inherit project workspace runtime config"})]}),e.jsx("textarea",{className:"min-h-48 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none disabled:cursor-not-allowed disabled:opacity-60",value:o.workspaceRuntime,onChange:U=>i(Z=>Z&&{...Z,workspaceRuntime:U.target.value}),disabled:o.inheritRuntime,placeholder:`{
|
|
116
|
+
"services": [
|
|
117
|
+
{
|
|
118
|
+
"name": "web",
|
|
119
|
+
"command": "pnpm dev",
|
|
120
|
+
"port": 3100
|
|
121
|
+
}
|
|
122
|
+
]
|
|
123
|
+
}`})]})]}),e.jsxs("div",{className:"mt-5 flex flex-col items-stretch gap-3 sm:flex-row sm:flex-wrap sm:items-center",children:[e.jsxs(G,{className:"w-full sm:w-auto",disabled:!C||K.isPending,onClick:w,children:[K.isPending?e.jsx(kn,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Save changes"]}),e.jsx(G,{variant:"outline",className:"w-full sm:w-auto",disabled:!C||K.isPending,onClick:()=>{i($),m(null),x(null)},children:"Reset"}),d?e.jsx("p",{className:"text-sm text-destructive",children:d}):null,!d&&p?e.jsx("p",{className:"text-sm text-muted-foreground",children:p}):null,!d&&!C?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No unsaved changes."}):null]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Linked objects"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Workspace context"})]}),e.jsx(yn,{className:"my-4"}),e.jsx(Rs,{label:"Project",children:b?e.jsx(Oe,{to:`/projects/${I}`,className:"hover:underline",children:b.name}):e.jsx(Ks,{value:h.projectId})}),e.jsx(Rs,{label:"Project workspace",children:b&&M?e.jsx(ZU,{project:b,workspace:M}):h.projectWorkspaceId?e.jsx(Ks,{value:h.projectWorkspaceId}):"None"}),e.jsx(Rs,{label:"Source issue",children:y?e.jsxs(Oe,{to:Bc(y),className:"hover:underline",children:[y.identifier??y.id," · ",y.title]}):h.sourceIssueId?e.jsx(Ks,{value:h.sourceIssueId}):"None"}),e.jsx(Rs,{label:"Derived from",children:_?e.jsx(Oe,{to:`/execution-workspaces/${_.id}`,className:"hover:underline",children:_.name}):h.derivedFromExecutionWorkspaceId?e.jsx(Ks,{value:h.derivedFromExecutionWorkspaceId}):"None"}),e.jsx(Rs,{label:"Workspace ID",children:e.jsx(Ks,{value:h.id})})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Paths and refs"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Concrete location"})]}),e.jsx(yn,{className:"my-4"}),e.jsx(Rs,{label:"Working dir",children:h.cwd?e.jsx(Ks,{value:h.cwd,copy:!0}):"None"}),e.jsx(Rs,{label:"Provider ref",children:h.providerRef?e.jsx(Ks,{value:h.providerRef,copy:!0}):"None"}),e.jsx(Rs,{label:"Repo URL",children:h.repoUrl&&VU(h.repoUrl)?e.jsxs("div",{className:"inline-flex max-w-full items-start gap-2",children:[e.jsxs("a",{href:h.repoUrl,target:"_blank",rel:"noreferrer",className:"inline-flex min-w-0 items-center gap-1 break-all hover:underline",children:[h.repoUrl,e.jsx(Is,{className:"h-3.5 w-3.5 shrink-0"})]}),e.jsx(uo,{text:h.repoUrl,className:"shrink-0 text-muted-foreground hover:text-foreground",copiedLabel:"Copied",children:e.jsx(_s,{className:"h-3.5 w-3.5"})})]}):h.repoUrl?e.jsx(Ks,{value:h.repoUrl,copy:!0}):"None"}),e.jsx(Rs,{label:"Base ref",children:h.baseRef?e.jsx(Ks,{value:h.baseRef,copy:!0}):"None"}),e.jsx(Rs,{label:"Branch",children:h.branchName?e.jsx(Ks,{value:h.branchName,copy:!0}):"None"}),e.jsx(Rs,{label:"Opened",children:js(h.openedAt)}),e.jsx(Rs,{label:"Last used",children:js(h.lastUsedAt)}),e.jsx(Rs,{label:"Cleanup",children:h.cleanupEligibleAt?`${js(h.cleanupEligibleAt)}${h.cleanupReason?` · ${h.cleanupReason}`:""}`:"Not scheduled"})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Runtime services"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Attached services"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Source: ",L==="execution_workspace"?"execution workspace override":L==="project_workspace"?"project workspace default":"none"]})]}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:flex-wrap",children:[e.jsxs(G,{variant:"outline",size:"sm",className:"w-full sm:w-auto",disabled:z.isPending||!k||!h.cwd,onClick:()=>z.mutate("start"),children:[z.isPending?e.jsx(kn,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):null,"Start"]}),e.jsx(G,{variant:"outline",size:"sm",className:"w-full sm:w-auto",disabled:z.isPending||!k||!h.cwd,onClick:()=>z.mutate("restart"),children:"Restart"}),e.jsx(G,{variant:"outline",size:"sm",className:"w-full sm:w-auto",disabled:z.isPending||(((H=h.runtimeServices)==null?void 0:H.length)??0)===0,onClick:()=>z.mutate("stop"),children:"Stop"})]})]}),e.jsx(yn,{className:"my-4"}),h.runtimeServices&&h.runtimeServices.length>0?e.jsx("div",{className:"space-y-3",children:h.runtimeServices.map(U=>e.jsx("div",{className:"rounded-xl border border-border/80 bg-background px-3 py-2",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm font-medium",children:U.serviceName}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[U.status," · ",U.lifecycle]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[U.url?e.jsxs("a",{href:U.url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 hover:underline",children:[U.url,e.jsx(Is,{className:"h-3.5 w-3.5"})]}):null,U.port?e.jsxs("div",{children:["Port ",U.port]}):null,U.command?e.jsx(Ks,{value:U.command,copy:!0}):null,U.cwd?e.jsx(Ks,{value:U.cwd,copy:!0}):null]})]}),e.jsx(Da,{className:"self-start",children:U.healthStatus})]})},U.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:k?"No runtime services are currently running for this execution workspace.":"No runtime config is defined for this execution workspace yet."})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Recent operations"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Runtime and cleanup logs"})]}),e.jsx(yn,{className:"my-4"}),T.isLoading?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading workspace operations…"}):T.error?e.jsx("p",{className:"text-sm text-destructive",children:T.error instanceof Error?T.error.message:"Failed to load workspace operations."}):T.data&&T.data.length>0?e.jsx("div",{className:"space-y-3",children:T.data.slice(0,6).map(U=>e.jsx("div",{className:"rounded-xl border border-border/80 bg-background px-3 py-2",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm font-medium",children:U.command??U.phase}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[js(U.startedAt),U.finishedAt?` → ${js(U.finishedAt)}`:""]}),U.stderrExcerpt?e.jsx("div",{className:"whitespace-pre-wrap break-words text-xs text-destructive",children:U.stderrExcerpt}):U.stdoutExcerpt?e.jsx("div",{className:"whitespace-pre-wrap break-words text-xs text-muted-foreground",children:U.stdoutExcerpt}):null]}),e.jsx(Da,{className:"self-start",children:U.status})]})},U.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No workspace operations have been recorded yet."})]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground",children:"Linked issues"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Issues using this workspace"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Any issue attached to this execution workspace appears here so you can review the full session context before reusing or closing it."})]}),e.jsxs(Da,{children:[S.length," linked"]})]}),e.jsx(yn,{className:"my-4"}),E.isLoading?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading linked issues…"}):E.error?e.jsx("p",{className:"text-sm text-destructive",children:E.error instanceof Error?E.error.message:"Failed to load linked issues."}):S.length>0?e.jsx("div",{className:"-mx-1 flex gap-3 overflow-x-auto px-1 pb-1",children:S.map(U=>e.jsxs(Oe,{to:Bc(U),className:"min-w-72 rounded-xl border border-border/80 bg-background px-4 py-3 transition-colors hover:bg-accent/20",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("div",{className:"font-mono text-xs text-muted-foreground",children:U.identifier??U.id.slice(0,8)}),e.jsx("div",{className:"line-clamp-2 text-sm font-medium",children:U.title})]}),e.jsx(Da,{className:"shrink-0",children:U.status})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[e.jsx("span",{className:"uppercase tracking-[0.16em]",children:U.priority}),e.jsx("span",{children:js(U.updatedAt)})]})]},U.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No issues are currently linked to this execution workspace."})]})]}),e.jsx(oN,{workspaceId:h.id,workspaceName:h.name,currentStatus:h.status,open:l,onOpenChange:u,onClosed:U=>{n.setQueryData(N.executionWorkspaces.detail(U.id),U),n.invalidateQueries({queryKey:N.executionWorkspaces.closeReadiness(U.id)}),n.invalidateQueries({queryKey:N.executionWorkspaces.workspaceOperations(U.id)}),b&&(n.invalidateQueries({queryKey:N.projects.detail(b.id)}),n.invalidateQueries({queryKey:N.executionWorkspaces.list(b.companyId,{projectId:b.id})})),y&&n.invalidateQueries({queryKey:N.issues.detail(y.id)})}})]})}function _N({goal:t,children:n,allGoals:s,depth:r,goalLink:a,onSelect:o}){const[i,l]=c.useState(!0),u=n.length>0,d=a==null?void 0:a(t),m=e.jsxs(e.Fragment,{children:[u?e.jsx("button",{className:"p-0.5",onClick:x=>{x.preventDefault(),x.stopPropagation(),l(!i)},children:e.jsx(sn,{className:O("h-3 w-3 transition-transform",i&&"rotate-90")})}):e.jsx("span",{className:"w-4"}),e.jsx("span",{className:"text-xs text-muted-foreground capitalize",children:t.level}),e.jsx("span",{className:"flex-1 truncate",children:t.title}),e.jsx(Dt,{status:t.status})]}),p=O("flex items-center gap-2 px-3 py-1.5 text-sm transition-colors cursor-pointer hover:bg-accent/50");return e.jsxs("div",{children:[d?e.jsx(Oe,{to:d,className:O(p,"no-underline text-inherit"),style:{paddingLeft:`${r*16+12}px`},children:m}):e.jsx("div",{className:p,style:{paddingLeft:`${r*16+12}px`},onClick:()=>o==null?void 0:o(t),children:m}),u&&i&&e.jsx("div",{children:n.map(x=>e.jsx(_N,{goal:x,children:s.filter(f=>f.parentId===x.id),allGoals:s,depth:r+1,goalLink:a,onSelect:o},x.id))})]})}function AN({goals:t,goalLink:n,onSelect:s}){const r=new Set(t.map(o=>o.id)),a=t.filter(o=>!o.parentId||!r.has(o.parentId));return t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No goals."}):e.jsx("div",{className:"border border-border py-1",children:a.map(o=>e.jsx(_N,{goal:o,children:t.filter(i=>i.parentId===o.id),allGoals:t,depth:0,goalLink:n,onSelect:s},o.id))})}function XU(){const{selectedCompanyId:t}=et(),{openNewGoal:n}=In(),{setBreadcrumbs:s}=Ft();c.useEffect(()=>{s([{label:"Goals"}])},[s]);const{data:r,isLoading:a,error:o}=oe({queryKey:N.goals.list(t),queryFn:()=>Zs.list(t),enabled:!!t});return t?a?e.jsx(mn,{variant:"list"}):e.jsxs("div",{className:"space-y-4",children:[o&&e.jsx("p",{className:"text-sm text-destructive",children:o.message}),r&&r.length===0&&e.jsx(tn,{icon:Ir,message:"No goals yet.",action:"Add Goal",onAction:()=>n()}),r&&r.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center justify-start",children:e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>n(),children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1.5"}),"New Goal"]})}),e.jsx(AN,{goals:r,goalLink:i=>`/goals/${i.id}`})]})]}):e.jsx(tn,{icon:Ir,message:"Select a company to view goals."})}function Eo({label:t,children:n}){return e.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-20",children:t}),e.jsx("div",{className:"flex items-center gap-1.5 min-w-0",children:n})]})}function eB(t){return t.replace(/_/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function Qg({current:t,options:n,onChange:s,children:r}){const[a,o]=c.useState(!1);return e.jsxs(Ht,{open:a,onOpenChange:o,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{className:"cursor-pointer hover:opacity-80 transition-opacity",children:r})}),e.jsx(Qt,{className:"w-40 p-1",align:"end",children:n.map(i=>e.jsx(G,{variant:"ghost",size:"sm",className:O("w-full justify-start text-xs",i===t&&"bg-accent"),onClick:()=>{s(i),o(!1)},children:eB(i)},i))})]})}function tB({goal:t,onUpdate:n}){const{selectedCompanyId:s}=et(),{data:r}=oe({queryKey:N.agents.list(s),queryFn:()=>We.list(s),enabled:!!s}),{data:a}=oe({queryKey:N.goals.list(s),queryFn:()=>Zs.list(s),enabled:!!s}),o=t.ownerAgentId?r==null?void 0:r.find(l=>l.id===t.ownerAgentId):null,i=t.parentId?a==null?void 0:a.find(l=>l.id===t.parentId):null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Eo,{label:"Status",children:n?e.jsx(Qg,{current:t.status,options:ix,onChange:l=>n({status:l}),children:e.jsx(Dt,{status:t.status})}):e.jsx(Dt,{status:t.status})}),e.jsx(Eo,{label:"Level",children:n?e.jsx(Qg,{current:t.level,options:ox,onChange:l=>n({level:l}),children:e.jsx("span",{className:"text-sm capitalize",children:t.level})}):e.jsx("span",{className:"text-sm capitalize",children:t.level})}),e.jsx(Eo,{label:"Owner",children:o?e.jsx(Oe,{to:Na(o),className:"text-sm hover:underline",children:o.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"None"})}),t.parentId&&e.jsx(Eo,{label:"Parent Goal",children:e.jsx(Oe,{to:`/goals/${t.parentId}`,className:"text-sm hover:underline",children:(i==null?void 0:i.title)??t.parentId.slice(0,8)})})]}),e.jsx(yn,{}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Eo,{label:"Created",children:e.jsx("span",{className:"text-sm",children:xs(t.createdAt)})}),e.jsx(Eo,{label:"Updated",children:e.jsx("span",{className:"text-sm",children:xs(t.updatedAt)})})]})]})}function nB(){const{goalId:t}=Xn(),{selectedCompanyId:n,setSelectedCompanyId:s}=et(),{openNewGoal:r}=In(),{openPanel:a,closePanel:o}=ji(),{setBreadcrumbs:i}=Ft(),l=at(),{data:u,isLoading:d,error:m}=oe({queryKey:N.goals.detail(t),queryFn:()=>Zs.get(t),enabled:!!t}),p=(u==null?void 0:u.companyId)??n,{data:x}=oe({queryKey:N.goals.list(p),queryFn:()=>Zs.list(p),enabled:!!p}),{data:f}=oe({queryKey:N.projects.list(p),queryFn:()=>en.list(p),enabled:!!p});c.useEffect(()=>{!(u!=null&&u.companyId)||u.companyId===n||s(u.companyId,{source:"route_sync"})},[u==null?void 0:u.companyId,n,s]);const h=ge({mutationFn:y=>Zs.update(t,y),onSuccess:()=>{l.invalidateQueries({queryKey:N.goals.detail(t)}),p&&l.invalidateQueries({queryKey:N.goals.list(p)})}}),j=ge({mutationFn:async y=>{if(!p)throw new Error("No company selected");return Aa.uploadImage(p,y,`goals/${t??"draft"}`)}}),b=(x??[]).filter(y=>y.parentId===t),g=(f??[]).filter(y=>t?y.goalIds.includes(t)||y.goals.some(v=>v.id===t)?!0:y.goalId===t:!1);return c.useEffect(()=>{i([{label:"Goals",href:"/goals"},{label:(u==null?void 0:u.title)??t??"Goal"}])},[i,u,t]),c.useEffect(()=>(u&&a(e.jsx(tB,{goal:u,onUpdate:y=>h.mutate(y)})),()=>o()),[u]),d?e.jsx(mn,{variant:"detail"}):m?e.jsx("p",{className:"text-sm text-destructive",children:m.message}):u?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs uppercase text-muted-foreground",children:u.level}),e.jsx(Dt,{status:u.status})]}),e.jsx(kr,{value:u.title,onSave:y=>h.mutate({title:y}),as:"h2",className:"text-xl font-bold"}),e.jsx(kr,{value:u.description??"",onSave:y=>h.mutate({description:y}),as:"p",className:"text-sm text-muted-foreground",placeholder:"Add a description...",multiline:!0,imageUploadHandler:async y=>(await j.mutateAsync(y)).contentPath})]}),e.jsxs(Ss,{defaultValue:"children",children:[e.jsxs(co,{children:[e.jsxs(An,{value:"children",children:["Sub-Goals (",b.length,")"]}),e.jsxs(An,{value:"projects",children:["Projects (",g.length,")"]})]}),e.jsxs(on,{value:"children",className:"mt-4 space-y-3",children:[e.jsx("div",{className:"flex items-center justify-start",children:e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>r({parentId:t}),children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1.5"}),"Sub Goal"]})}),b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sub-goals."}):e.jsx(AN,{goals:b,goalLink:y=>`/goals/${y.id}`})]}),e.jsx(on,{value:"projects",className:"mt-4",children:g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No linked projects."}):e.jsx("div",{className:"border border-border",children:g.map(y=>e.jsx(gr,{title:y.name,subtitle:y.description??void 0,to:El(y),trailing:e.jsx(Dt,{status:y.status})},y.id))})})]})]}):null}const sB={hire_agent:"Hire Agent",approve_ceo_strategy:"CEO Strategy",budget_override_required:"Budget Override"};function of(t,n){const s=sB[t]??t;return t==="hire_agent"&&(n!=null&&n.name)?`${s}: ${String(n.name)}`:s}const lf={hire_agent:ay,approve_ceo_strategy:Vb,budget_override_required:Ja},cf=kc;function Va({label:t,value:n}){return n?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:t}),e.jsx("span",{children:String(n)})]}):null}function rB({values:t}){if(!Array.isArray(t))return null;const n=t.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean);return n.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs pt-0.5",children:"Skills"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(s=>e.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground",children:s},s))})]})}function aB({payload:t}){return e.jsxs("div",{className:"mt-3 space-y-1.5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:"Name"}),e.jsx("span",{className:"font-medium",children:String(t.name??"—")})]}),e.jsx(Va,{label:"Role",value:t.role}),e.jsx(Va,{label:"Title",value:t.title}),e.jsx(Va,{label:"Icon",value:t.icon}),!!t.capabilities&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs pt-0.5",children:"Capabilities"}),e.jsx("span",{className:"text-muted-foreground",children:String(t.capabilities)})]}),!!t.adapterType&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:"Adapter"}),e.jsx("span",{className:"font-mono text-xs bg-muted px-1.5 py-0.5 rounded",children:String(t.adapterType)})]}),e.jsx(rB,{values:t.desiredSkills})]})}function oB({payload:t}){const n=t.plan??t.description??t.strategy??t.text;return e.jsxs("div",{className:"mt-3 space-y-1.5 text-sm",children:[e.jsx(Va,{label:"Title",value:t.title}),!!n&&e.jsx("div",{className:"mt-2 rounded-md bg-muted/40 px-3 py-2 text-sm text-muted-foreground whitespace-pre-wrap font-mono text-xs max-h-48 overflow-y-auto",children:String(n)}),!n&&e.jsx("pre",{className:"mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground overflow-x-auto max-h-48",children:JSON.stringify(t,null,2)})]})}function iB({payload:t}){const n=typeof t.budgetAmount=="number"?t.budgetAmount:null,s=typeof t.observedAmount=="number"?t.observedAmount:null;return e.jsxs("div",{className:"mt-3 space-y-1.5 text-sm",children:[e.jsx(Va,{label:"Scope",value:t.scopeName??t.scopeType}),e.jsx(Va,{label:"Window",value:t.windowKind}),e.jsx(Va,{label:"Metric",value:t.metric}),n!==null||s!==null?e.jsxs("div",{className:"rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:["Limit ",n!==null?ot(n):"—"," · Observed ",s!==null?ot(s):"—"]}):null,!!t.guidance&&e.jsx("p",{className:"text-muted-foreground",children:String(t.guidance)})]})}function EN({type:t,payload:n}){return t==="hire_agent"?e.jsx(aB,{payload:n}):t==="budget_override_required"?e.jsx(iB,{payload:n}):e.jsx(oB,{payload:n})}function lB(t){return t==="approved"?e.jsx(ho,{className:"h-3.5 w-3.5 text-green-600 dark:text-green-400"}):t==="rejected"?e.jsx(fi,{className:"h-3.5 w-3.5 text-red-600 dark:text-red-400"}):t==="revision_requested"?e.jsx(_r,{className:"h-3.5 w-3.5 text-amber-600 dark:text-amber-400"}):t==="pending"?e.jsx(_r,{className:"h-3.5 w-3.5 text-yellow-600 dark:text-yellow-400"}):null}function cB({approval:t,requesterAgent:n,onApprove:s,onReject:r,onOpen:a,detailLink:o,isPending:i}){const l=lf[t.type]??cf,u=of(t.type,t.payload),d=t.type!=="budget_override_required"&&(t.status==="pending"||t.status==="revision_requested");return e.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:u}),n&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["requested by ",e.jsx(Ut,{name:n.name,size:"sm",className:"inline-flex"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[lB(t.status),e.jsx("span",{className:"text-xs text-muted-foreground capitalize",children:t.status}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["· ",as(t.createdAt)]})]})]}),e.jsx(EN,{type:t.type,payload:t.payload}),t.decisionNote&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground italic border-t border-border pt-2",children:["Note: ",t.decisionNote]}),d&&e.jsxs("div",{className:"flex gap-2 mt-4 pt-3 border-t border-border",children:[e.jsx(G,{size:"sm",className:"bg-green-700 hover:bg-green-600 text-white",onClick:s,disabled:i,children:"Approve"}),e.jsx(G,{variant:"destructive",size:"sm",onClick:r,disabled:i,children:"Reject"})]}),e.jsx("div",{className:"mt-3",children:o?e.jsx(G,{variant:"ghost",size:"sm",className:"text-xs px-0",asChild:!0,children:e.jsx(Oe,{to:o,children:"View details"})}):e.jsx(G,{variant:"ghost",size:"sm",className:"text-xs px-0",onClick:a,children:"View details"})})]})}function Gg(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),s=at(),r=Sn(),i=(fn().pathname.split("/").pop()??"pending")==="all"?"all":"pending",[l,u]=c.useState(null);c.useEffect(()=>{n([{label:"Approvals"}])},[n]);const{data:d,isLoading:m,error:p}=oe({queryKey:N.approvals.list(t),queryFn:()=>Wn.list(t),enabled:!!t}),{data:x}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),f=ge({mutationFn:g=>Wn.approve(g),onSuccess:(g,y)=>{u(null),s.invalidateQueries({queryKey:N.approvals.list(t)}),r(`/approvals/${y}?resolved=approved`)},onError:g=>{u(g instanceof Error?g.message:"Failed to approve")}}),h=ge({mutationFn:g=>Wn.reject(g),onSuccess:()=>{u(null),s.invalidateQueries({queryKey:N.approvals.list(t)})},onError:g=>{u(g instanceof Error?g.message:"Failed to reject")}}),j=(d??[]).filter(g=>i==="all"||g.status==="pending"||g.status==="revision_requested").sort((g,y)=>new Date(y.createdAt).getTime()-new Date(g.createdAt).getTime()),b=(d??[]).filter(g=>g.status==="pending"||g.status==="revision_requested").length;return t?m?e.jsx(mn,{variant:"approvals"}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Ss,{value:i,onValueChange:g=>r(`/approvals/${g}`),children:e.jsx(Ca,{items:[{value:"pending",label:e.jsxs(e.Fragment,{children:["Pending",b>0&&e.jsx("span",{className:O("ml-1.5 rounded-full px-1.5 py-0.5 text-[10px] font-medium","bg-yellow-500/20 text-yellow-500"),children:b})]})},{value:"all",label:"All"}]})})}),p&&e.jsx("p",{className:"text-sm text-destructive",children:p.message}),l&&e.jsx("p",{className:"text-sm text-destructive",children:l}),j.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(kc,{className:"h-8 w-8 text-muted-foreground/30 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i==="pending"?"No pending approvals.":"No approvals yet."})]}),j.length>0&&e.jsx("div",{className:"grid gap-3",children:j.map(g=>e.jsx(cB,{approval:g,requesterAgent:g.requestedByAgentId?(x??[]).find(y=>y.id===g.requestedByAgentId)??null:null,onApprove:()=>f.mutate(g.id),onReject:()=>h.mutate(g.id),detailLink:`/approvals/${g.id}`,isPending:f.isPending||h.isPending},g.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a company first."})}function Ur({className:t,...n}){return e.jsx("textarea",{"data-slot":"textarea",className:O("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),...n})}function dB(){const{approvalId:t}=Xn(),{selectedCompanyId:n,setSelectedCompanyId:s}=et(),{setBreadcrumbs:r}=Ft(),a=Sn(),[o]=ui(),i=at(),[l,u]=c.useState(""),[d,m]=c.useState(null),[p,x]=c.useState(!1),{data:f,isLoading:h}=oe({queryKey:N.approvals.detail(t),queryFn:()=>Wn.get(t),enabled:!!t}),j=(f==null?void 0:f.companyId)??n,{data:b}=oe({queryKey:N.approvals.comments(t),queryFn:()=>Wn.listComments(t),enabled:!!t}),{data:g}=oe({queryKey:N.approvals.issues(t),queryFn:()=>Wn.listIssues(t),enabled:!!t}),{data:y}=oe({queryKey:N.agents.list(j??""),queryFn:()=>We.list(j??""),enabled:!!j});c.useEffect(()=>{!(f!=null&&f.companyId)||f.companyId===n||s(f.companyId,{source:"route_sync"})},[f==null?void 0:f.companyId,n,s]);const v=c.useMemo(()=>{const A=new Map;for(const R of y??[])A.set(R.id,R.name);return A},[y]);c.useEffect(()=>{var A;r([{label:"Approvals",href:"/approvals"},{label:((A=f==null?void 0:f.id)==null?void 0:A.slice(0,8))??t??"Approval"}])},[r,f,t]);const _=()=>{t&&(i.invalidateQueries({queryKey:N.approvals.detail(t)}),i.invalidateQueries({queryKey:N.approvals.comments(t)}),i.invalidateQueries({queryKey:N.approvals.issues(t)}),f!=null&&f.companyId&&(i.invalidateQueries({queryKey:N.approvals.list(f.companyId)}),i.invalidateQueries({queryKey:N.approvals.list(f.companyId,"pending")}),i.invalidateQueries({queryKey:N.agents.list(f.companyId)})))},E=ge({mutationFn:()=>Wn.approve(t),onSuccess:()=>{m(null),_(),a(`/approvals/${t}?resolved=approved`,{replace:!0})},onError:A=>m(A instanceof Error?A.message:"Approve failed")}),S=ge({mutationFn:()=>Wn.reject(t),onSuccess:()=>{m(null),_()},onError:A=>m(A instanceof Error?A.message:"Reject failed")}),M=ge({mutationFn:()=>Wn.requestRevision(t),onSuccess:()=>{m(null),_()},onError:A=>m(A instanceof Error?A.message:"Revision request failed")}),B=ge({mutationFn:()=>Wn.resubmit(t),onSuccess:()=>{m(null),_()},onError:A=>m(A instanceof Error?A.message:"Resubmit failed")}),k=ge({mutationFn:()=>Wn.addComment(t,l.trim()),onSuccess:()=>{u(""),m(null),_()},onError:A=>m(A instanceof Error?A.message:"Comment failed")}),L=ge({mutationFn:A=>We.remove(A),onSuccess:()=>{m(null),_(),a("/approvals")},onError:A=>m(A instanceof Error?A.message:"Delete failed")});if(h)return e.jsx(mn,{variant:"detail"});if(!f)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Approval not found."});const $=f.payload,C=typeof $.agentId=="string"?$.agentId:null,I=f.status==="pending"||f.status==="revision_requested",K=f.type==="budget_override_required",T=lf[f.type]??cf,z=o.get("resolved")==="approved"&&f.status==="approved",w=(g==null?void 0:g[0])??null,F=w?{label:((g==null?void 0:g.length)??0)>1?"Review linked issues":"Review linked issue",to:`/issues/${w.identifier??w.id}`}:C?{label:"Open hired agent",to:`/agents/${C}`}:{label:"Back to approvals",to:"/approvals"};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[z&&e.jsx("div",{className:"border border-green-300 dark:border-green-700/40 bg-green-50 dark:bg-green-900/20 rounded-lg px-4 py-3 animate-in fade-in zoom-in-95 duration-300",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"relative mt-0.5",children:[e.jsx(ho,{className:"h-4 w-4 text-green-600 dark:text-green-300"}),e.jsx(xo,{className:"h-3 w-3 text-green-500 dark:text-green-200 absolute -right-2 -top-1 animate-pulse"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-green-800 dark:text-green-100 font-medium",children:"Approval confirmed"}),e.jsx("p",{className:"text-xs text-green-700 dark:text-green-200/90",children:"Requesting agent was notified to review this approval and linked issues."})]})]}),e.jsx(G,{size:"sm",variant:"outline",className:"border-green-400 dark:border-green-600/50 text-green-800 dark:text-green-100 hover:bg-green-100 dark:hover:bg-green-900/30",onClick:()=>a(F.to),children:F.label})]})}),e.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:of(f.type,f.payload)}),e.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:f.id})]})]}),e.jsx(Dt,{status:f.status})]}),e.jsxs("div",{className:"text-sm space-y-1",children:[f.requestedByAgentId&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Requested by"}),e.jsx(Ut,{name:v.get(f.requestedByAgentId)??f.requestedByAgentId.slice(0,8),size:"sm"})]}),e.jsx(EN,{type:f.type,payload:$}),e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors mt-2",onClick:()=>x(A=>!A),children:[e.jsx(sn,{className:`h-3 w-3 transition-transform ${p?"rotate-90":""}`}),"See full request"]}),p&&e.jsx("pre",{className:"text-xs bg-muted/40 rounded-md p-3 overflow-x-auto",children:JSON.stringify($,null,2)}),f.decisionNote&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Decision note: ",f.decisionNote]})]}),d&&e.jsx("p",{className:"text-sm text-destructive",children:d}),g&&g.length>0&&e.jsxs("div",{className:"pt-2 border-t border-border/60",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1.5",children:"Linked Issues"}),e.jsx("div",{className:"space-y-1.5",children:g.map(A=>e.jsxs(Oe,{to:`/issues/${A.identifier??A.id}`,className:"block text-xs rounded border border-border/70 px-2 py-1.5 hover:bg-accent/20",children:[e.jsx("span",{className:"font-mono text-muted-foreground mr-2",children:A.identifier??A.id.slice(0,8)}),e.jsx("span",{children:A.title})]},A.id))}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2",children:"Linked issues remain open until the requesting agent follows up and closes them."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[I&&!K&&e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",className:"bg-green-700 hover:bg-green-600 text-white",onClick:()=>E.mutate(),disabled:E.isPending,children:"Approve"}),e.jsx(G,{variant:"destructive",size:"sm",onClick:()=>S.mutate(),disabled:S.isPending,children:"Reject"})]}),K&&f.status==="pending"&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Resolve this budget stop from the budget controls on ",e.jsx(Oe,{to:"/costs",className:"underline underline-offset-2",children:"/costs"}),"."]}),f.status==="pending"&&e.jsx(G,{size:"sm",variant:"outline",onClick:()=>M.mutate(),disabled:M.isPending,children:"Request revision"}),f.status==="revision_requested"&&e.jsx(G,{size:"sm",variant:"outline",onClick:()=>B.mutate(),disabled:B.isPending,children:"Mark resubmitted"}),f.status==="rejected"&&f.type==="hire_agent"&&C&&e.jsx(G,{size:"sm",variant:"outline",className:"text-destructive border-destructive/40",onClick:()=>{window.confirm("Delete this disapproved agent? This cannot be undone.")&&L.mutate(C)},disabled:L.isPending,children:"Delete disapproved agent"})]})]}),e.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium",children:["Comments (",(b==null?void 0:b.length)??0,")"]}),e.jsx("div",{className:"space-y-2",children:(b??[]).map(A=>e.jsxs("div",{className:"border border-border/60 rounded-md p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[A.authorAgentId?e.jsx(Oe,{to:`/agents/${A.authorAgentId}`,className:"hover:underline",children:e.jsx(Ut,{name:v.get(A.authorAgentId)??A.authorAgentId.slice(0,8),size:"sm"})}):e.jsx(Ut,{name:"Board",size:"sm"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(A.createdAt).toLocaleString()})]}),e.jsx(Xs,{className:"text-sm",children:A.body})]},A.id))}),e.jsx(Ur,{value:l,onChange:A=>u(A.target.value),placeholder:"Add a comment...",rows:3}),e.jsx("div",{className:"flex justify-end",children:e.jsx(G,{size:"sm",onClick:()=>k.mutate(),disabled:!l.trim()||k.isPending,children:k.isPending?"Posting…":"Post comment"})})]})]})}function Fr(t,n){const s=new URLSearchParams;t&&s.set("from",t),n&&s.set("to",n);const r=s.toString();return r?`?${r}`:""}const bs={summary:(t,n,s)=>ne.get(`/companies/${t}/costs/summary${Fr(n,s)}`),byAgent:(t,n,s)=>ne.get(`/companies/${t}/costs/by-agent${Fr(n,s)}`),byAgentModel:(t,n,s)=>ne.get(`/companies/${t}/costs/by-agent-model${Fr(n,s)}`),byProject:(t,n,s)=>ne.get(`/companies/${t}/costs/by-project${Fr(n,s)}`),byProvider:(t,n,s)=>ne.get(`/companies/${t}/costs/by-provider${Fr(n,s)}`),byBiller:(t,n,s)=>ne.get(`/companies/${t}/costs/by-biller${Fr(n,s)}`),financeSummary:(t,n,s)=>ne.get(`/companies/${t}/costs/finance-summary${Fr(n,s)}`),financeByBiller:(t,n,s)=>ne.get(`/companies/${t}/costs/finance-by-biller${Fr(n,s)}`),financeByKind:(t,n,s)=>ne.get(`/companies/${t}/costs/finance-by-kind${Fr(n,s)}`),financeEvents:(t,n,s,r=100)=>ne.get(`/companies/${t}/costs/finance-events${uB(n,s,r)}`),windowSpend:t=>ne.get(`/companies/${t}/costs/window-spend`),quotaWindows:t=>ne.get(`/companies/${t}/costs/quota-windows`)};function uB(t,n,s){const r=new URLSearchParams;t&&r.set("from",t),n&&r.set("to",n),s&&r.set("limit",String(s));const a=r.toString();return a?`?${a}`:""}function mB(t){return t>90?"bg-red-400":t>70?"bg-yellow-400":"bg-green-400"}function dp({label:t,percentUsed:n,leftLabel:s,rightLabel:r,showDeficitNotch:a=!1,className:o}){const i=Math.min(100,Math.max(0,n)),l=Math.min(i,97);return e.jsxs("div",{className:O("space-y-1.5",o),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:"text-xs font-medium tabular-nums",children:s}),r&&e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:r})]})]}),e.jsxs("div",{className:"relative h-2 w-full border border-border overflow-hidden",children:[e.jsx("div",{className:O("absolute inset-y-0 left-0 transition-[width,background-color] duration-150",mB(i)),style:{width:`${i}%`}}),a&&i>0&&e.jsx("div",{className:"absolute inset-y-0 w-[2px] bg-destructive z-10",style:{left:`${l}%`}})]})]})}function Jg({row:t,weekSpendCents:n,budgetMonthlyCents:s,totalCompanySpendCents:r,providerRows:a}){const o=c.useMemo(()=>{const d=new Map;for(const m of a){const p=d.get(m.provider)??{provider:m.provider,costCents:0,inputTokens:0,outputTokens:0};p.costCents+=m.costCents,p.inputTokens+=m.inputTokens+m.cachedInputTokens,p.outputTokens+=m.outputTokens,d.set(m.provider,p)}return Array.from(d.values()).sort((m,p)=>p.costCents-m.costCents)},[a]),i=c.useMemo(()=>{const d=new Map;for(const m of a)d.set(m.billingType,(d.get(m.billingType)??0)+m.costCents);return Array.from(d.entries()).sort((m,p)=>p[1]-m[1])},[a]),l=s>0&&r>0?t.costCents/r*s:s,u=l>0?Math.min(100,t.costCents/l*100):0;return e.jsxs(jn,{children:[e.jsx(qn,{className:"px-4 pt-4 pb-0 gap-1",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Un,{className:"text-sm font-semibold",children:lr(t.biller)}),e.jsxs(cs,{className:"text-xs mt-0.5",children:[e.jsx("span",{className:"font-mono",children:Et(t.inputTokens+t.cachedInputTokens)})," in"," · ",e.jsx("span",{className:"font-mono",children:Et(t.outputTokens)})," out"," · ",t.providerCount," provider",t.providerCount===1?"":"s"," · ",t.modelCount," model",t.modelCount===1?"":"s"]})]}),e.jsx("span",{className:"text-xl font-bold tabular-nums shrink-0",children:ot(t.costCents)})]})}),e.jsxs(wn,{className:"px-4 pb-4 pt-3 space-y-4",children:[s>0&&e.jsx(dp,{label:"Period spend",percentUsed:u,leftLabel:ot(t.costCents),rightLabel:`${Math.round(u)}% of allocation`}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.apiRunCount>0?`${t.apiRunCount} metered run${t.apiRunCount===1?"":"s"}`:"0 metered runs"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription run${t.subscriptionRunCount===1?"":"s"}`:"0 subscription runs"," · ",ot(n)," this week"]}),i.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Billing types"}),e.jsx("div",{className:"space-y-1.5",children:i.map(([d,m])=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:px(d)}),e.jsx("span",{className:"font-medium tabular-nums",children:ot(m)})]},d))})]})]}),o.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Upstream providers"}),e.jsx("div",{className:"space-y-1.5",children:o.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:lr(d.provider)}),e.jsxs("div",{className:"text-right tabular-nums",children:[e.jsx("div",{className:"font-medium",children:ot(d.costCents)}),e.jsxs("div",{className:"text-muted-foreground",children:[Et(d.inputTokens+d.outputTokens)," tok"]})]})]},d.provider))})]})]})]})]})}function pB(t){return(t/100).toFixed(2)}function xB(t){const n=Number(t);return!Number.isFinite(n)||n<0?null:Math.round(n*100)}function Zg({incident:t,onRaiseAndResume:n,onKeepPaused:s,isMutating:r}){const[a,o]=c.useState(pB(Math.max(t.amountObserved+1e3,t.amountLimit))),i=xB(a);return e.jsxs(jn,{className:"overflow-hidden border-red-500/20 bg-[linear-gradient(180deg,rgba(255,70,70,0.10),rgba(255,255,255,0.02))]",children:[e.jsx(qn,{className:"px-5 pt-5 pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.22em] text-red-200/80",children:[t.scopeType," hard stop"]}),e.jsx(Un,{className:"mt-1 text-base text-red-50",children:t.scopeName}),e.jsxs(cs,{className:"mt-1 text-red-100/70",children:["Spending reached ",ot(t.amountObserved)," against a limit of ",ot(t.amountLimit),"."]})]}),e.jsx("div",{className:"rounded-full border border-red-400/30 bg-red-500/10 p-2 text-red-200",children:e.jsx(T1,{className:"h-4 w-4"})})]})}),e.jsxs(wn,{className:"space-y-4 px-5 pb-5 pt-0",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2 text-sm text-red-50/90",children:[e.jsx($p,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("div",{children:t.scopeType==="project"?"Project execution is paused. New work in this project will not start until you resolve the budget incident.":"This scope is paused. New heartbeats will not start until you resolve the budget incident."})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-background/60 p-3",children:[e.jsx("label",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"New budget (USD)"}),e.jsxs("div",{className:"mt-2 flex flex-col gap-3 sm:flex-row",children:[e.jsx(Xt,{value:a,onChange:l=>o(l.target.value),inputMode:"decimal",placeholder:"0.00"}),e.jsxs(G,{className:"gap-2",disabled:r||i===null||i<=t.amountObserved,onClick:()=>{typeof i=="number"&&n(i)},children:[e.jsx(ti,{className:"h-4 w-4"}),r?"Applying...":"Raise budget & resume"]})]}),i!==null&&i<=t.amountObserved?e.jsx("p",{className:"mt-2 text-xs text-red-200/80",children:"The new budget must exceed current observed spend."}):null]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(G,{variant:"ghost",className:"text-muted-foreground",disabled:r,onClick:s,children:"Keep paused"})})]})]})}function fB({row:t}){return e.jsxs(jn,{children:[e.jsx(qn,{className:"px-4 pt-4 pb-1",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Un,{className:"text-base",children:lr(t.biller)}),e.jsxs(cs,{className:"mt-1 text-xs",children:[t.eventCount," event",t.eventCount===1?"":"s"," across ",t.kindCount," kind",t.kindCount===1?"":"s"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-lg font-semibold tabular-nums",children:ot(t.netCents)}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"net"})]})]})}),e.jsx(wn,{className:"space-y-3 px-4 pb-4 pt-3",children:e.jsxs("div",{className:"grid gap-2 text-sm sm:grid-cols-3",children:[e.jsxs("div",{className:"border border-border p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"debits"}),e.jsx("div",{className:"mt-1 font-medium tabular-nums",children:ot(t.debitCents)})]}),e.jsxs("div",{className:"border border-border p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"credits"}),e.jsx("div",{className:"mt-1 font-medium tabular-nums",children:ot(t.creditCents)})]}),e.jsxs("div",{className:"border border-border p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"estimated"}),e.jsx("div",{className:"mt-1 font-medium tabular-nums",children:ot(t.estimatedDebitCents)})]})]})})]})}function hB({rows:t}){return e.jsxs(jn,{children:[e.jsxs(qn,{className:"px-4 pt-4 pb-1",children:[e.jsx(Un,{className:"text-base",children:"Financial event mix"}),e.jsx(cs,{children:"Account-level charges grouped by event kind."})]}),e.jsx(wn,{className:"space-y-2 px-4 pb-4 pt-3",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No finance events in this period."}):t.map(n=>e.jsxs("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:dj(n.eventKind)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[n.eventCount," event",n.eventCount===1?"":"s"," · ",n.billerCount," biller",n.billerCount===1?"":"s"]})]}),e.jsxs("div",{className:"text-right tabular-nums",children:[e.jsx("div",{className:"text-sm font-medium",children:ot(n.netCents)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[ot(n.debitCents)," debits"]})]})]},n.eventKind))})]})}function Yg({rows:t,emptyMessage:n="No financial events in this period."}){return e.jsxs(jn,{children:[e.jsxs(qn,{className:"px-4 pt-4 pb-1",children:[e.jsx(Un,{className:"text-base",children:"Recent financial events"}),e.jsx(cs,{children:"Top-ups, fees, credits, commitments, and other non-request charges."})]}),e.jsx(wn,{className:"space-y-3 px-4 pb-4 pt-3",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:n}):t.map(s=>e.jsx("div",{className:"border border-border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Wt,{variant:"secondary",children:dj(s.eventKind)}),e.jsx(Wt,{variant:s.direction==="credit"?"outline":"secondary",children:V_(s.direction)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:js(s.occurredAt)})]}),e.jsxs("div",{className:"text-sm font-medium",children:[lr(s.biller),s.provider?` -> ${lr(s.provider)}`:"",s.model?e.jsx("span",{className:"ml-1 font-mono text-xs text-muted-foreground",children:s.model}):null]}),(s.description||s.externalInvoiceId||s.region||s.pricingTier)&&e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[s.description?e.jsx("div",{children:s.description}):null,s.externalInvoiceId?e.jsxs("div",{children:["invoice ",s.externalInvoiceId]}):null,s.region?e.jsxs("div",{children:["region ",s.region]}):null,s.pricingTier?e.jsxs("div",{children:["tier ",s.pricingTier]}):null]})]}),e.jsxs("div",{className:"text-right tabular-nums",children:[e.jsx("div",{className:"text-sm font-semibold",children:ot(s.amountCents)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s.currency}),s.estimated?e.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-amber-600",children:"estimated"}):null]})]})},s.id))})]})}const ic=["currentsession","currentweekallmodels","currentweeksonnetonly","currentweeksonnet","currentweekopusonly","currentweekopus","extrausage"];function up(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function gB(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}function bB(t){return[...t].sort((n,s)=>{const r=ic.indexOf(up(n.label)),a=ic.indexOf(up(s.label));return(r===-1?ic.length:r)-(a===-1?ic.length:a)})}function yB(t){return t==null?"bg-zinc-700":t>=90?"bg-red-400":t>=70?"bg-amber-400":"bg-primary/70"}function vB({windows:t,source:n=null,error:s=null}){const r=bB(t);return e.jsxs("div",{className:"border border-border px-4 py-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-muted-foreground",children:"Anthropic subscription"}),e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:"Live Claude quota windows."})]}),n?e.jsx("span",{className:"shrink-0 border border-border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:xx(n)}):null]}),s?e.jsx("div",{className:"mt-4 border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:s}):null,e.jsx("div",{className:"mt-4 space-y-4",children:r.map(a=>{const o=up(a.label),i=gB(a);if(o==="extrausage")return e.jsxs("div",{className:"border border-border px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:a.label}),a.valueLabel?e.jsx("div",{className:"text-sm font-medium text-foreground",children:a.valueLabel}):null]}),i?e.jsx("div",{className:"mt-2 text-sm text-muted-foreground",children:i}):null]},a.label);const l=Math.min(100,Math.max(0,a.usedPercent??0));return e.jsxs("div",{className:"border border-border px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:a.label}),i?e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:i}):null]}),a.usedPercent!=null?e.jsxs("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-foreground",children:[a.usedPercent,"% used"]}):null]}),e.jsx("div",{className:"mt-3 h-2 overflow-hidden bg-muted",children:e.jsx("div",{className:O("h-full transition-[width] duration-200",yB(a.usedPercent)),style:{width:`${l}%`}})})]},a.label)})})]})}const lc=["5hlimit","weeklylimit","credits"];function mp(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function jB(t){return[...t].sort((n,s)=>{const r=mp(n.label).replace(/^gpt53codexspark/,""),a=mp(s.label).replace(/^gpt53codexspark/,""),o=lc.indexOf(r),i=lc.indexOf(a);return(o===-1?lc.length:o)-(i===-1?lc.length:i)})}function wB(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}function NB(t){return t==null?"bg-zinc-700":t>=90?"bg-red-400":t>=70?"bg-amber-400":"bg-primary/70"}function Xg(t){const n=mp(t);return n.includes("gpt53codexspark")||n.includes("gpt5")}function kB({windows:t,source:n=null,error:s=null}){const r=jB(t),a=r.filter(i=>!Xg(i.label)),o=r.filter(i=>Xg(i.label));return e.jsxs("div",{className:"border border-border px-4 py-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-muted-foreground",children:"Codex subscription"}),e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:"Live Codex quota windows."})]}),n?e.jsx("span",{className:"shrink-0 border border-border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:xx(n)}):null]}),s?e.jsx("div",{className:"mt-4 border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:s}):null,e.jsxs("div",{className:"mt-4 space-y-5",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Account windows"}),e.jsx("div",{className:"space-y-3",children:a.map(i=>e.jsx(eb,{window:i},i.label))})]}),o.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Model windows"}),e.jsx("div",{className:"space-y-3",children:o.map(i=>e.jsx(eb,{window:i},i.label))})]}):null]})]})}function eb({window:t}){const n=wB(t);return t.usedPercent==null?e.jsxs("div",{className:"border border-border px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:t.label}),t.valueLabel?e.jsx("div",{className:"text-sm font-semibold tabular-nums text-foreground",children:t.valueLabel}):null]}),n?e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:n}):null]}):e.jsxs("div",{className:"border border-border px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:t.label}),n?e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:n}):null]}),e.jsxs("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-foreground",children:[t.usedPercent,"% used"]})]}),e.jsx("div",{className:"mt-3 h-2 overflow-hidden bg-muted",children:e.jsx("div",{className:O("h-full transition-[width] duration-200",NB(t.usedPercent)),style:{width:`${Math.max(0,Math.min(100,t.usedPercent))}%`}})})]})}const CB=["5h","24h","7d"];function tb({provider:t,rows:n,budgetMonthlyCents:s,totalCompanySpendCents:r,weekSpendCents:a,windowRows:o,showDeficitNotch:i,quotaWindows:l=[],quotaError:u=null,quotaSource:d=null,quotaLoading:m=!1}){const p=c.useMemo(()=>{let w=0,F=0,A=0,R=0,Q=0,H=0,U=0;for(const J of n)w+=J.inputTokens,F+=J.outputTokens,A+=J.costCents,R+=J.apiRunCount,Q+=J.subscriptionRunCount,H+=J.subscriptionInputTokens,U+=J.subscriptionOutputTokens;const Z=w+F,V=H+U,W=Z+V;return{totalInputTokens:w,totalOutputTokens:F,totalTokens:Z,totalCostCents:A,totalApiRuns:R,totalSubRuns:Q,totalSubInputTokens:H,totalSubOutputTokens:U,totalSubTokens:V,subSharePct:W>0?V/W*100:0}},[n]),{totalInputTokens:x,totalOutputTokens:f,totalTokens:h,totalCostCents:j,totalApiRuns:b,totalSubRuns:g,totalSubInputTokens:y,totalSubOutputTokens:v,totalSubTokens:_,subSharePct:E}=p,S=s>0&&r>0?j/r*s:s,M=S>0?Math.min(100,j/S*100):0,B=S>0?S/4.33:0,k=B>0?Math.min(100,a/B*100):0,L=s>0,$=c.useMemo(()=>new Map(o.map(w=>[w.window,w])),[o]),C=c.useMemo(()=>Math.max(...o.map(w=>w.costCents),0),[o]),I=t==="anthropic",K=t==="openai"&&(d==null?void 0:d.startsWith("codex-")),z=(t==="anthropic"||t==="openai")&&(m||l.length>0||u!=null);return e.jsxs(jn,{children:[e.jsx(qn,{className:"px-4 pt-4 pb-0 gap-1",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Un,{className:"text-sm font-semibold",children:lr(t)}),e.jsxs(cs,{className:"text-xs mt-0.5",children:[e.jsx("span",{className:"font-mono",children:Et(x)})," in"," · ",e.jsx("span",{className:"font-mono",children:Et(f)})," out",(b>0||g>0)&&e.jsxs("span",{className:"ml-1.5",children:["·"," ",b>0&&`~${b} api`,b>0&&g>0&&" / ",g>0&&`~${g} sub`," runs"]})]})]}),e.jsx("span",{className:"text-xl font-bold tabular-nums shrink-0",children:ot(j)})]})}),e.jsxs(wn,{className:"px-4 pb-4 pt-3 space-y-4",children:[L&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(dp,{label:"Period spend",percentUsed:M,leftLabel:ot(j),rightLabel:`${Math.round(M)}% of allocation`,showDeficitNotch:i}),e.jsx(dp,{label:"This week",percentUsed:k,leftLabel:ot(a),rightLabel:`~${ot(Math.round(B))} / wk`,showDeficitNotch:k>=100})]}),o.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Rolling windows"}),e.jsx("div",{className:"space-y-2.5",children:CB.map(w=>{const F=$.get(w);if(!F)return null;const A=F.costCents,R=F.inputTokens+F.outputTokens,Q=C>0?A/C*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("span",{className:"font-mono text-muted-foreground w-6 shrink-0",children:w}),e.jsxs("span",{className:"text-muted-foreground font-mono flex-1",children:[Et(R)," tok"]}),e.jsx("span",{className:"font-medium tabular-nums",children:ot(A)})]}),e.jsx("div",{className:"h-2 w-full border border-border overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary/60 transition-[width] duration-150",style:{width:`${Q}%`}})})]},w)})})]})]}),g>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Subscription"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono text-foreground",children:g})," runs"," · ",_>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono text-foreground",children:Et(_)})," total"," · "]}),e.jsx("span",{className:"font-mono text-foreground",children:Et(y)})," in"," · ",e.jsx("span",{className:"font-mono text-foreground",children:Et(v)})," out"]}),E>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-1.5 w-full border border-border overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary/60 transition-[width] duration-150",style:{width:`${E}%`}})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(E),"% of token usage via subscription"]})]})]})]}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border"}),e.jsx("div",{className:"space-y-3",children:n.map(w=>{const F=w.inputTokens+w.outputTokens,A=h>0?F/h*100:0,R=j>0?w.costCents/j*100:0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs text-muted-foreground truncate font-mono block",children:w.model}),e.jsxs("span",{className:"text-[11px] text-muted-foreground truncate block",children:[lr(w.biller)," · ",px(w.billingType)]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 tabular-nums text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[Et(F)," tok"]}),e.jsx("span",{className:"font-medium",children:ot(w.costCents)})]})]}),e.jsxs("div",{className:"relative h-2 w-full border border-border overflow-hidden",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/60 transition-[width] duration-150",style:{width:`${A}%`},title:`${Math.round(A)}% of provider tokens`}),e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/85 transition-[width] duration-150",style:{width:`${R}%`},title:`${Math.round(R)}% of provider cost`})]})]},`${w.provider}:${w.model}`)})})]}),z&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Subscription quota"}),d&&!I&&!K?e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:xx(d)}):null]}),m?e.jsx(SB,{}):I?e.jsx(vB,{windows:l,source:d,error:u}):K?e.jsx(kB,{windows:l,source:d,error:u}):e.jsxs(e.Fragment,{children:[u?e.jsx("p",{className:"text-xs text-destructive",children:u}):null,e.jsx("div",{className:"space-y-2.5",children:l.map(w=>{const F=w.usedPercent==null?null:w.usedPercent>=90?"bg-red-400":w.usedPercent>=70?"bg-yellow-400":"bg-green-400";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:w.label}),e.jsx("span",{className:"flex-1"}),w.valueLabel!=null?e.jsx("span",{className:"font-medium tabular-nums",children:w.valueLabel}):w.usedPercent!=null?e.jsxs("span",{className:"font-medium tabular-nums",children:[w.usedPercent,"% used"]}):null]}),w.usedPercent!=null&&F!=null&&e.jsx("div",{className:"h-2 w-full border border-border overflow-hidden",children:e.jsx("div",{className:`h-full transition-[width] duration-150 ${F}`,style:{width:`${w.usedPercent}%`}})}),w.detail?e.jsx("p",{className:"text-xs text-muted-foreground",children:w.detail}):w.resetsAt?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["resets ",new Date(w.resetsAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})]}):null]},w.label)})})]})]})]})]})]})}function SB(){return e.jsxs("div",{className:"border border-border px-4 py-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border pb-3",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx(Ze,{className:"h-3 w-36"}),e.jsx(Ze,{className:"h-4 w-64 max-w-full"})]}),e.jsx(Ze,{className:"h-7 w-28"})]}),e.jsx("div",{className:"mt-4 space-y-3",children:Array.from({length:3}).map((t,n)=>e.jsxs("div",{className:"border border-border px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx(Ze,{className:"h-4 w-32"}),e.jsx(Ze,{className:"h-3 w-44 max-w-full"})]}),e.jsx(Ze,{className:"h-4 w-20"})]}),e.jsx(Ze,{className:"mt-3 h-2 w-full"})]},n))})]})}const IB={mtd:"Month to Date","7d":"Last 7 Days","30d":"Last 30 Days",ytd:"Year to Date",all:"All Time",custom:"Custom"},_B=["mtd","7d","30d","ytd","all","custom"];function AB(t){const n=new Date,s=n.toISOString();switch(t){case"mtd":return{from:new Date(n.getFullYear(),n.getMonth(),1).toISOString(),to:s};case"7d":return{from:new Date(n.getFullYear(),n.getMonth(),n.getDate()-7,0,0,0,0).toISOString(),to:s};case"30d":return{from:new Date(n.getFullYear(),n.getMonth(),n.getDate()-30,0,0,0,0).toISOString(),to:s};case"ytd":return{from:new Date(n.getFullYear(),0,1).toISOString(),to:s};case"all":case"custom":return{from:"",to:""}}}function mm(t){const n=new Date(t);return n.setSeconds(0,0),n.toISOString()}function EB(){const[t,n]=c.useState("mtd"),[s,r]=c.useState(""),[a,o]=c.useState(""),i=c.useRef(null),[l,u]=c.useState(()=>mm(new Date));c.useEffect(()=>{const x=new Date,f=(60-x.getSeconds())*1e3-x.getMilliseconds(),h=setTimeout(()=>{u(mm(new Date)),i.current=setInterval(()=>u(mm(new Date)),6e4)},f);return()=>{clearTimeout(h),i.current!=null&&clearInterval(i.current)}},[]);const{from:d,to:m}=c.useMemo(()=>{if(t!=="custom")return AB(t);const x=s?new Date(s+"T00:00:00"):null,f=a?new Date(a+"T23:59:59.999"):null;return{from:x?x.toISOString():"",to:f?f.toISOString():""}},[t,s,a,l]);return{preset:t,setPreset:n,customFrom:s,setCustomFrom:r,customTo:a,setCustomTo:o,from:d,to:m,customReady:t!=="custom"||!!s&&!!a}}const TB="__none__";function RB(){const t=new Date,n=t.getDay(),s=n===0?-6:1-n,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()+s,0,0,0,0),a=new Date(r.getFullYear(),r.getMonth(),r.getDate()+6,23,59,59,999);return{from:r.toISOString(),to:a.toISOString()}}function PB({provider:t,rows:n}){const s=n.reduce((a,o)=>a+o.inputTokens+o.cachedInputTokens+o.outputTokens,0),r=n.reduce((a,o)=>a+o.costCents,0);return e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{children:lr(t)}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Et(s)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ot(r)})]})}function MB({biller:t,rows:n}){const s=n.reduce((a,o)=>a+o.inputTokens+o.cachedInputTokens+o.outputTokens,0),r=n.reduce((a,o)=>a+o.costCents,0);return e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{children:lr(t)}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Et(s)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ot(r)})]})}function Vs({label:t,value:n,subtitle:s,icon:r}){return e.jsx("div",{className:"border border-border p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:t}),e.jsx("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:n}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:s})]}),e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center border border-border",children:e.jsx(r,{className:"h-4 w-4 text-muted-foreground"})})]})})}function nb({debitCents:t,creditCents:n,netCents:s,estimatedDebitCents:r,eventCount:a}){return e.jsxs(jn,{children:[e.jsxs(qn,{className:"px-5 pt-5 pb-2",children:[e.jsx(Un,{className:"text-base",children:"Finance ledger"}),e.jsx(cs,{children:"Account-level charges that do not map to a single inference request."})]}),e.jsxs(wn,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Vs,{label:"Debits",value:ot(t),subtitle:`${a} total event${a===1?"":"s"} in range`,icon:ti}),e.jsx(Vs,{label:"Credits",value:ot(n),subtitle:"Refunds, offsets, and credit returns",icon:R1}),e.jsx(Vs,{label:"Net",value:ot(s),subtitle:"Debit minus credit for the selected period",icon:wm}),e.jsx(Vs,{label:"Estimated",value:ot(r),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:jm})]})]})}function $B(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),s=at(),[r,a]=c.useState("overview"),[o,i]=c.useState("all"),[l,u]=c.useState("all"),{preset:d,setPreset:m,customFrom:p,setCustomFrom:x,customTo:f,setCustomTo:h,from:j,to:b,customReady:g}=EB();c.useEffect(()=>{n([{label:"Costs"}])},[n]);const[y,v]=c.useState(()=>new Date().toDateString()),_=c.useRef(null);c.useEffect(()=>{const se=()=>{const ce=new Date,Te=new Date(ce.getFullYear(),ce.getMonth(),ce.getDate()+1).getTime()-ce.getTime();_.current=setTimeout(()=>{v(new Date().toDateString()),se()},Te)};return se(),()=>{_.current!=null&&clearTimeout(_.current)}},[]);const E=c.useMemo(()=>RB(),[y]),S=t??TB,{data:M,isLoading:B,error:k}=oe({queryKey:N.budgets.overview(S),queryFn:()=>Wa.overview(S),enabled:!!t&&g,refetchInterval:3e4,staleTime:5e3}),L=()=>{t&&(s.invalidateQueries({queryKey:N.budgets.overview(t)}),s.invalidateQueries({queryKey:N.dashboard(t)}),s.invalidateQueries({queryKey:N.agents.list(t)}),s.invalidateQueries({queryKey:N.projects.list(t)}))},$=ge({mutationFn:se=>Wa.upsertPolicy(S,{scopeType:se.scopeType,scopeId:se.scopeId,amount:se.amount,windowKind:se.windowKind}),onSuccess:L}),C=ge({mutationFn:se=>Wa.resolveIncident(S,se.incidentId,se),onSuccess:L}),{data:I,isLoading:K,error:T}=oe({queryKey:N.costs(S,j||void 0,b||void 0),queryFn:async()=>{const[se,ce,Te,ae]=await Promise.all([bs.summary(S,j||void 0,b||void 0),bs.byAgent(S,j||void 0,b||void 0),bs.byProject(S,j||void 0,b||void 0),bs.byAgentModel(S,j||void 0,b||void 0)]);return{summary:se,byAgent:ce,byProject:Te,byAgentModel:ae}},enabled:!!t&&g}),{data:z,isLoading:w,error:F}=oe({queryKey:[N.financeSummary(S,j||void 0,b||void 0),N.financeByBiller(S,j||void 0,b||void 0),N.financeByKind(S,j||void 0,b||void 0),N.financeEvents(S,j||void 0,b||void 0,18)],queryFn:async()=>{const[se,ce,Te,ae]=await Promise.all([bs.financeSummary(S,j||void 0,b||void 0),bs.financeByBiller(S,j||void 0,b||void 0),bs.financeByKind(S,j||void 0,b||void 0),bs.financeEvents(S,j||void 0,b||void 0,18)]);return{summary:se,byBiller:ce,byKind:Te,events:ae}},enabled:!!t&&g}),[A,R]=c.useState(new Set);c.useEffect(()=>{R(new Set)},[S,j,b]);function Q(se){R(ce=>{const Te=new Set(ce);return Te.has(se)?Te.delete(se):Te.add(se),Te})}const H=c.useMemo(()=>{const se=new Map;for(const ce of(I==null?void 0:I.byAgentModel)??[]){const Te=se.get(ce.agentId)??[];Te.push(ce),se.set(ce.agentId,Te)}for(const[ce,Te]of se)se.set(ce,Te.slice().sort((ae,je)=>je.costCents-ae.costCents));return se},[I==null?void 0:I.byAgentModel]),{data:U}=oe({queryKey:N.usageByProvider(S,j||void 0,b||void 0),queryFn:()=>bs.byProvider(S,j||void 0,b||void 0),enabled:!!t&&g&&(r==="providers"||r==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:Z}=oe({queryKey:N.usageByBiller(S,j||void 0,b||void 0),queryFn:()=>bs.byBiller(S,j||void 0,b||void 0),enabled:!!t&&g&&r==="billers",refetchInterval:3e4,staleTime:1e4}),{data:V}=oe({queryKey:N.usageByProvider(S,E.from,E.to),queryFn:()=>bs.byProvider(S,E.from,E.to),enabled:!!t&&(r==="providers"||r==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:W}=oe({queryKey:N.usageByBiller(S,E.from,E.to),queryFn:()=>bs.byBiller(S,E.from,E.to),enabled:!!t&&r==="billers",refetchInterval:3e4,staleTime:1e4}),{data:J}=oe({queryKey:N.usageWindowSpend(S),queryFn:()=>bs.windowSpend(S),enabled:!!t&&r==="providers",refetchInterval:3e4,staleTime:1e4}),{data:Y,isLoading:de}=oe({queryKey:N.usageQuotaWindows(S),queryFn:()=>bs.quotaWindows(S),enabled:!!t&&r==="providers",refetchInterval:3e5,staleTime:6e4}),fe=c.useMemo(()=>{const se=new Map;for(const ce of U??[]){const Te=se.get(ce.provider)??[];Te.push(ce),se.set(ce.provider,Te)}return se},[U]),Ce=c.useMemo(()=>{const se=new Map;for(const ce of Z??[]){const Te=se.get(ce.biller)??[];Te.push(ce),se.set(ce.biller,Te)}return se},[Z]),le=c.useMemo(()=>{const se=new Map;for(const ce of V??[])se.set(ce.provider,(se.get(ce.provider)??0)+ce.costCents);return se},[V]),Re=c.useMemo(()=>{const se=new Map;for(const ce of W??[])se.set(ce.biller,(se.get(ce.biller)??0)+ce.costCents);return se},[W]),Pe=c.useMemo(()=>{const se=new Map;for(const ce of J??[]){const Te=se.get(ce.provider)??[];Te.push(ce),se.set(ce.provider,Te)}return se},[J]),Fe=c.useMemo(()=>{const se=new Map;for(const ce of Y??[])ce.ok&&ce.windows.length>0&&se.set(ce.provider,ce.windows);return se},[Y]),pe=c.useMemo(()=>{const se=new Map;for(const ce of Y??[])!ce.ok&&ce.error&&se.set(ce.provider,ce.error);return se},[Y]),Le=c.useMemo(()=>{const se=new Map;for(const ce of Y??[])typeof ce.source=="string"&&ce.source.length>0&&se.set(ce.provider,ce.source);return se},[Y]),q=c.useMemo(()=>{const se=new Map;if(d!=="mtd")return se;const ce=(I==null?void 0:I.summary.budgetCents)??0;if(ce<=0)return se;const Te=(I==null?void 0:I.summary.spendCents)??0,ae=new Date,je=ae.getDate(),ke=new Date(ae.getFullYear(),ae.getMonth()+1,0).getDate();for(const[Xe,lt]of fe){const It=lt.reduce((ln,yt)=>ln+yt.costCents,0),Ue=Te>0?It/Te:0,pt=ce*Ue;if(pt<=0){se.set(Xe,!1);continue}const ht=It/Math.max(je,1);se.set(Xe,It+ht*(ke-je)>pt)}return se},[d,I,fe]),D=c.useMemo(()=>Array.from(fe.keys()),[fe]),ie=c.useMemo(()=>Array.from(Ce.keys()),[Ce]),Ie=o==="all"||D.includes(o)?o:"all";c.useEffect(()=>{Ie!==o&&i("all")},[Ie,o]);const ue=l==="all"||ie.includes(l)?l:"all";c.useEffect(()=>{ue!==l&&u("all")},[ue,l]);const Be=c.useMemo(()=>{const se=Array.from(fe.keys()),ce=se.reduce((ae,je)=>{var ke;return ae+(((ke=fe.get(je))==null?void 0:ke.reduce((Xe,lt)=>Xe+lt.inputTokens+lt.cachedInputTokens+lt.outputTokens,0))??0)},0),Te=se.reduce((ae,je)=>{var ke;return ae+(((ke=fe.get(je))==null?void 0:ke.reduce((Xe,lt)=>Xe+lt.costCents,0))??0)},0);return[{value:"all",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{children:"All providers"}),se.length>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Et(ce)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ot(Te)})]}):null]})},...se.map(ae=>({value:ae,label:e.jsx(PB,{provider:ae,rows:fe.get(ae)??[]})}))]},[fe]),be=c.useMemo(()=>{const se=Array.from(Ce.keys()),ce=se.reduce((ae,je)=>{var ke;return ae+(((ke=Ce.get(je))==null?void 0:ke.reduce((Xe,lt)=>Xe+lt.inputTokens+lt.cachedInputTokens+lt.outputTokens,0))??0)},0),Te=se.reduce((ae,je)=>{var ke;return ae+(((ke=Ce.get(je))==null?void 0:ke.reduce((Xe,lt)=>Xe+lt.costCents,0))??0)},0);return[{value:"all",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{children:"All billers"}),se.length>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Et(ce)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ot(Te)})]}):null]})},...se.map(ae=>({value:ae,label:e.jsx(MB,{biller:ae,rows:Ce.get(ae)??[]})}))]},[Ce]),he=((I==null?void 0:I.byAgent)??[]).reduce((se,ce)=>se+ce.inputTokens+ce.cachedInputTokens+ce.outputTokens,0),Se=(z==null?void 0:z.events)??[],we=(M==null?void 0:M.policies)??[],ee=(M==null?void 0:M.activeIncidents)??[],me=c.useMemo(()=>({company:we.filter(se=>se.scopeType==="company"),agent:we.filter(se=>se.scopeType==="agent"),project:we.filter(se=>se.scopeType==="project")}),[we]);if(!t)return e.jsx(tn,{icon:wr,message:"Select a company to view costs."});const ye=d==="custom"&&!g,Ke=(K||w)&&g,qe=T??F;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted-foreground",children:"Inference spend, platform fees, credits, and live quota windows."})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:_B.map(se=>e.jsx(G,{variant:d===se?"secondary":"ghost",size:"sm",onClick:()=>m(se),children:IB[se]},se))})]}),d==="custom"?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border border-border p-3",children:[e.jsx("input",{type:"date",value:p,onChange:se=>x(se.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx("input",{type:"date",value:f,onChange:se=>h(se.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"})]}):null,e.jsxs("div",{className:"grid gap-3 lg:grid-cols-4",children:[e.jsx(Vs,{label:"Inference spend",value:ot((I==null?void 0:I.summary.spendCents)??0),subtitle:`${Et(he)} tokens across request-scoped events`,icon:wr}),e.jsx(Vs,{label:"Budget",value:ee.length>0?String(ee.length):I!=null&&I.summary.budgetCents&&I.summary.budgetCents>0?`${I.summary.utilizationPercent}%`:"Open",subtitle:ee.length>0?`${(M==null?void 0:M.pausedAgentCount)??0} agents paused · ${(M==null?void 0:M.pausedProjectCount)??0} projects paused`:I!=null&&I.summary.budgetCents&&I.summary.budgetCents>0?`${ot(I.summary.spendCents)} of ${ot(I.summary.budgetCents)}`:"No monthly cap configured",icon:jm}),e.jsx(Vs,{label:"Finance net",value:ot((z==null?void 0:z.summary.netCents)??0),subtitle:`${ot((z==null?void 0:z.summary.debitCents)??0)} debits · ${ot((z==null?void 0:z.summary.creditCents)??0)} credits`,icon:wm}),e.jsx(Vs,{label:"Finance events",value:String((z==null?void 0:z.summary.eventCount)??0),subtitle:`${ot((z==null?void 0:z.summary.estimatedDebitCents)??0)} estimated in range`,icon:ti})]})]}),e.jsxs(Ss,{value:r,onValueChange:se=>a(se),children:[e.jsxs(co,{variant:"line",className:"justify-start",children:[e.jsx(An,{value:"overview",children:"Overview"}),e.jsx(An,{value:"budgets",children:"Budgets"}),e.jsx(An,{value:"providers",children:"Providers"}),e.jsx(An,{value:"billers",children:"Billers"}),e.jsx(An,{value:"finance",children:"Finance"})]}),e.jsx(on,{value:"overview",className:"mt-4 space-y-4",children:ye?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):Ke?e.jsx(mn,{variant:"costs"}):qe?e.jsx("p",{className:"text-sm text-destructive",children:qe.message}):e.jsxs(e.Fragment,{children:[ee.length>0?e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:ee.slice(0,2).map(se=>e.jsx(Zg,{incident:se,isMutating:C.isPending,onKeepPaused:()=>C.mutate({incidentId:se.id,action:"keep_paused"}),onRaiseAndResume:ce=>C.mutate({incidentId:se.id,action:"raise_budget_and_resume",amount:ce})},se.id))}):null,e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1.3fr,1fr]",children:[e.jsxs(jn,{children:[e.jsxs(qn,{className:"px-5 pt-5 pb-2",children:[e.jsx(Un,{className:"text-base",children:"Inference ledger"}),e.jsx(cs,{children:"Request-scoped inference spend for the selected period."})]}),e.jsxs(wn,{className:"space-y-4 px-5 pb-5 pt-2",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-3xl font-semibold tabular-nums",children:ot((I==null?void 0:I.summary.spendCents)??0)}),e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:I!=null&&I.summary.budgetCents&&I.summary.budgetCents>0?`Budget ${ot(I.summary.budgetCents)}`:"Unlimited budget"})]}),e.jsxs("div",{className:"border border-border px-4 py-3 text-right",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"usage"}),e.jsx("div",{className:"mt-1 text-lg font-medium tabular-nums",children:Et(he)})]})]}),I!=null&&I.summary.budgetCents&&I.summary.budgetCents>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"h-2 overflow-hidden bg-muted",children:e.jsx("div",{className:O("h-full transition-[width,background-color] duration-150",I.summary.utilizationPercent>90?"bg-red-400":I.summary.utilizationPercent>70?"bg-yellow-400":"bg-emerald-400"),style:{width:`${Math.min(100,I.summary.utilizationPercent)}%`}})}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[I.summary.utilizationPercent,"% of monthly budget consumed in this range."]})]}):null]})]}),e.jsx(nb,{debitCents:(z==null?void 0:z.summary.debitCents)??0,creditCents:(z==null?void 0:z.summary.creditCents)??0,netCents:(z==null?void 0:z.summary.netCents)??0,estimatedDebitCents:(z==null?void 0:z.summary.estimatedDebitCents)??0,eventCount:(z==null?void 0:z.summary.eventCount)??0})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1.25fr,0.95fr]",children:[e.jsxs(jn,{children:[e.jsxs(qn,{className:"px-5 pt-5 pb-2",children:[e.jsx(Un,{className:"text-base",children:"By agent"}),e.jsx(cs,{children:"What each agent consumed in the selected period."})]}),e.jsx(wn,{className:"space-y-2 px-5 pb-5 pt-2",children:((I==null?void 0:I.byAgent.length)??0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No cost events yet."}):I==null?void 0:I.byAgent.map(se=>{const ce=H.get(se.agentId)??[],Te=A.has(se.agentId),ae=ce.length>0;return e.jsxs("div",{className:"border border-border px-4 py-3",children:[e.jsxs("div",{className:O("flex items-start justify-between gap-3",ae?"cursor-pointer select-none":""),onClick:()=>ae&&Q(se.agentId),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[ae?Te?e.jsx(rn,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(sn,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx("span",{className:"h-3 w-3 shrink-0"}),e.jsx(Ut,{name:se.agentName??se.agentId,size:"sm"}),se.agentStatus==="terminated"?e.jsx(Dt,{status:"terminated"}):null]}),e.jsxs("div",{className:"text-right text-sm tabular-nums",children:[e.jsx("div",{className:"font-medium",children:ot(se.costCents)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["in ",Et(se.inputTokens+se.cachedInputTokens)," · out ",Et(se.outputTokens)]}),se.apiRunCount>0||se.subscriptionRunCount>0?e.jsxs("div",{className:"text-xs text-muted-foreground",children:[se.apiRunCount>0?`${se.apiRunCount} api`:"0 api"," · ",se.subscriptionRunCount>0?`${se.subscriptionRunCount} subscription`:"0 subscription"]}):null]})]}),Te&&ce.length>0?e.jsx("div",{className:"mt-3 space-y-2 border-l border-border pl-4",children:ce.map(je=>{const ke=se.costCents>0?Math.round(je.costCents/se.costCents*100):0;return e.jsxs("div",{className:"flex items-start justify-between gap-3 text-xs",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"truncate font-medium text-foreground",children:[lr(je.provider),e.jsx("span",{className:"mx-1 text-border",children:"/"}),e.jsx("span",{className:"font-mono",children:je.model})]}),e.jsxs("div",{className:"truncate text-muted-foreground",children:[lr(je.biller)," · ",px(je.billingType)]})]}),e.jsxs("div",{className:"text-right tabular-nums",children:[e.jsxs("div",{className:"font-medium",children:[ot(je.costCents),e.jsxs("span",{className:"ml-1 font-normal text-muted-foreground",children:["(",ke,"%)"]})]}),e.jsxs("div",{className:"text-muted-foreground",children:[Et(je.inputTokens+je.cachedInputTokens+je.outputTokens)," tok"]})]})]},`${je.provider}:${je.model}:${je.billingType}`)})}):null]},se.agentId)})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(jn,{children:[e.jsxs(qn,{className:"px-5 pt-5 pb-2",children:[e.jsx(Un,{className:"text-base",children:"By project"}),e.jsx(cs,{children:"Run costs attributed through project-linked issues."})]}),e.jsx(wn,{className:"space-y-2 px-5 pb-5 pt-2",children:((I==null?void 0:I.byProject.length)??0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No project-attributed run costs yet."}):I==null?void 0:I.byProject.map((se,ce)=>e.jsxs("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm",children:[e.jsx("span",{className:"truncate",children:se.projectName??se.projectId??"Unattributed"}),e.jsx("span",{className:"font-medium tabular-nums",children:ot(se.costCents)})]},se.projectId??`unattributed-${ce}`))})]}),e.jsx(Yg,{rows:Se.slice(0,6),emptyMessage:"No finance events yet. Add account-level charges once biller invoices or credits land."})]})]})]})}),e.jsx(on,{value:"budgets",className:"mt-4 space-y-4",children:B?e.jsx(mn,{variant:"costs"}):k?e.jsx("p",{className:"text-sm text-destructive",children:k.message}):e.jsxs(e.Fragment,{children:[e.jsxs(jn,{className:"border-border/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))]",children:[e.jsxs(qn,{className:"px-5 pt-5 pb-3",children:[e.jsx(Un,{className:"text-base",children:"Budget control plane"}),e.jsx(cs,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),e.jsxs(wn,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[e.jsx(Vs,{label:"Active incidents",value:String(ee.length),subtitle:"Open soft or hard threshold crossings",icon:wm}),e.jsx(Vs,{label:"Pending approvals",value:String((M==null?void 0:M.pendingApprovalCount)??0),subtitle:"Budget override approvals awaiting board action",icon:ti}),e.jsx(Vs,{label:"Paused agents",value:String((M==null?void 0:M.pausedAgentCount)??0),subtitle:"Agent heartbeats blocked by budget",icon:jm}),e.jsx(Vs,{label:"Paused projects",value:String((M==null?void 0:M.pausedProjectCount)??0),subtitle:"Project execution blocked by budget",icon:wr})]})]}),ee.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Active incidents"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Resolve hard stops here by raising the budget or explicitly keeping the scope paused."})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:ee.map(se=>e.jsx(Zg,{incident:se,isMutating:C.isPending,onKeepPaused:()=>C.mutate({incidentId:se.id,action:"keep_paused"}),onRaiseAndResume:ce=>C.mutate({incidentId:se.id,action:"raise_budget_and_resume",amount:ce})},se.id))})]}):null,e.jsxs("div",{className:"space-y-5",children:[["company","agent","project"].map(se=>{const ce=me[se];return ce.length===0?null:e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold capitalize",children:[se," budgets"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:se==="company"?"Company-wide monthly policy.":se==="agent"?"Recurring monthly spend policies for individual agents.":"Lifetime spend policies for execution-bound projects."})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:ce.map(Te=>e.jsx(rf,{summary:Te,isSaving:$.isPending,onSave:ae=>$.mutate({scopeType:Te.scopeType,scopeId:Te.scopeId,amount:ae,windowKind:Te.windowKind})},Te.policyId))})]},se)}),we.length===0?e.jsx(jn,{children:e.jsx(wn,{className:"px-5 py-8 text-sm text-muted-foreground",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control."})}):null]})]})}),e.jsx(on,{value:"providers",className:"mt-4 space-y-4",children:ye?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):e.jsx(e.Fragment,{children:e.jsxs(Ss,{value:Ie,onValueChange:i,children:[e.jsx(Ca,{items:Be,value:Ie}),e.jsx(on,{value:"all",className:"mt-4",children:D.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No cost events in this period."}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:D.map(se=>e.jsx(tb,{provider:se,rows:fe.get(se)??[],budgetMonthlyCents:(I==null?void 0:I.summary.budgetCents)??0,totalCompanySpendCents:(I==null?void 0:I.summary.spendCents)??0,weekSpendCents:le.get(se)??0,windowRows:Pe.get(se)??[],showDeficitNotch:q.get(se)??!1,quotaWindows:Fe.get(se)??[],quotaError:pe.get(se)??null,quotaSource:Le.get(se)??null,quotaLoading:de},se))})}),D.map(se=>e.jsx(on,{value:se,className:"mt-4",children:e.jsx(tb,{provider:se,rows:fe.get(se)??[],budgetMonthlyCents:(I==null?void 0:I.summary.budgetCents)??0,totalCompanySpendCents:(I==null?void 0:I.summary.spendCents)??0,weekSpendCents:le.get(se)??0,windowRows:Pe.get(se)??[],showDeficitNotch:q.get(se)??!1,quotaWindows:Fe.get(se)??[],quotaError:pe.get(se)??null,quotaSource:Le.get(se)??null,quotaLoading:de})},se))]})})}),e.jsx(on,{value:"billers",className:"mt-4 space-y-4",children:ye?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):e.jsx(e.Fragment,{children:e.jsxs(Ss,{value:ue,onValueChange:u,children:[e.jsx(Ca,{items:be,value:ue}),e.jsx(on,{value:"all",className:"mt-4",children:ie.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No billable events in this period."}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:ie.map(se=>{const ce=(Ce.get(se)??[])[0];if(!ce)return null;const Te=(U??[]).filter(ae=>ae.biller===se);return e.jsx(Jg,{row:ce,weekSpendCents:Re.get(se)??0,budgetMonthlyCents:(I==null?void 0:I.summary.budgetCents)??0,totalCompanySpendCents:(I==null?void 0:I.summary.spendCents)??0,providerRows:Te},se)})})}),ie.map(se=>{const ce=(Ce.get(se)??[])[0];if(!ce)return null;const Te=(U??[]).filter(ae=>ae.biller===se);return e.jsx(on,{value:se,className:"mt-4",children:e.jsx(Jg,{row:ce,weekSpendCents:Re.get(se)??0,budgetMonthlyCents:(I==null?void 0:I.summary.budgetCents)??0,totalCompanySpendCents:(I==null?void 0:I.summary.spendCents)??0,providerRows:Te})},se)})]})})}),e.jsx(on,{value:"finance",className:"mt-4 space-y-4",children:ye?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):w?e.jsx(mn,{variant:"costs"}):F?e.jsx("p",{className:"text-sm text-destructive",children:F.message}):e.jsxs(e.Fragment,{children:[e.jsx(nb,{debitCents:(z==null?void 0:z.summary.debitCents)??0,creditCents:(z==null?void 0:z.summary.creditCents)??0,netCents:(z==null?void 0:z.summary.netCents)??0,estimatedDebitCents:(z==null?void 0:z.summary.estimatedDebitCents)??0,eventCount:(z==null?void 0:z.summary.eventCount)??0}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1.2fr,0.95fr]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(jn,{children:[e.jsxs(qn,{className:"px-5 pt-5 pb-2",children:[e.jsx(Un,{className:"text-base",children:"By biller"}),e.jsx(cs,{children:"Account-level financial events grouped by who charged or credited them."})]}),e.jsx(wn,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:((z==null?void 0:z.byBiller.length)??0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No finance events yet."}):z==null?void 0:z.byBiller.map(se=>e.jsx(fB,{row:se},se.biller))})]}),e.jsx(Yg,{rows:Se})]}),e.jsx(hB,{rows:(z==null?void 0:z.byKind)??[]})]})]})})]})]})}function DB(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),[s,r]=c.useState("all");c.useEffect(()=>{n([{label:"Activity"}])},[n]);const{data:a,isLoading:o,error:i}=oe({queryKey:N.activity(t),queryFn:()=>ya.list(t),enabled:!!t}),{data:l}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),{data:u}=oe({queryKey:N.issues.list(t),queryFn:()=>nt.list(t),enabled:!!t}),{data:d}=oe({queryKey:N.projects.list(t),queryFn:()=>en.list(t),enabled:!!t}),{data:m}=oe({queryKey:N.goals.list(t),queryFn:()=>Zs.list(t),enabled:!!t}),p=c.useMemo(()=>{const b=new Map;for(const g of l??[])b.set(g.id,g);return b},[l]),x=c.useMemo(()=>{const b=new Map;for(const g of u??[])b.set(`issue:${g.id}`,g.identifier??g.id.slice(0,8));for(const g of l??[])b.set(`agent:${g.id}`,g.name);for(const g of d??[])b.set(`project:${g.id}`,g.name);for(const g of m??[])b.set(`goal:${g.id}`,g.title);return b},[u,l,d,m]),f=c.useMemo(()=>{const b=new Map;for(const g of u??[])b.set(`issue:${g.id}`,g.title);return b},[u]);if(!t)return e.jsx(tn,{icon:sl,message:"Select a company to view activity."});if(o)return e.jsx(mn,{variant:"list"});const h=a&&s!=="all"?a.filter(b=>b.entityType===s):a,j=a?[...new Set(a.map(b=>b.entityType))].sort():[];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(Hn,{value:s,onValueChange:r,children:[e.jsx(Qn,{className:"w-[140px] h-8 text-xs",children:e.jsx(Vn,{placeholder:"Filter by type"})}),e.jsxs(Gn,{children:[e.jsx(Mt,{value:"all",children:"All types"}),j.map(b=>e.jsx(Mt,{value:b,children:b.charAt(0).toUpperCase()+b.slice(1)},b))]})]})}),i&&e.jsx("p",{className:"text-sm text-destructive",children:i.message}),h&&h.length===0&&e.jsx(tn,{icon:sl,message:"No activity yet."}),h&&h.length>0&&e.jsx("div",{className:"border border-border divide-y divide-border",children:h.map(b=>e.jsx(rw,{event:b,agentMap:p,entityNameMap:x,entityTitleMap:f},b.id))})]})}const OB=.32,LB=.88,FB=140;function cc({children:t,onArchive:n,disabled:s=!1,selected:r=!1,className:a}){const o=c.useRef(null),i=c.useRef(null),l=c.useRef(0),u=c.useRef(null),d=c.useRef(!1),[m,p]=c.useState(0),[x,f]=c.useState(!1),[h,j]=c.useState(!1),[b,g]=c.useState(null);c.useEffect(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]);const y=()=>{i.current=null,f(!1),p(0)},v=()=>{const B=o.current;if(!B){n();return}f(!1),g(B.offsetHeight),p(-Math.max(l.current,B.offsetWidth)),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{j(!0)})}),u.current=window.setTimeout(()=>{n()},FB)},_=B=>{if(s||B.touches.length!==1)return;const k=B.touches[0],L=o.current;l.current=(L==null?void 0:L.offsetWidth)??0,g((L==null?void 0:L.offsetHeight)??null),j(!1),d.current=!1,i.current={x:k.clientX,y:k.clientY}},E=B=>{if(s||h)return;const k=i.current;if(!k||B.touches.length!==1)return;const L=B.touches[0],$=L.clientX-k.x,C=L.clientY-k.y;if(!x){if(Math.abs($)<6)return;if(Math.abs(C)>Math.abs($)){i.current=null;return}d.current=!0}if($>=0){B.preventDefault(),f(!0),p(0);return}const I=l.current>0?l.current*LB:Number.POSITIVE_INFINITY;B.preventDefault(),f(!0),p(Math.max($,-I))},S=()=>{if(s||h)return;if(l.current>0&&Math.abs(m)>=l.current*OB){v();return}y()},M=l.current>0?Math.min(Math.abs(m)/l.current,1):0;return e.jsxs("div",{ref:o,className:O("relative overflow-hidden touch-pan-y",a),style:{height:b===null?void 0:h?0:b,opacity:h?0:1,transition:h?"height 200ms ease, opacity 200ms ease":void 0},onTouchStart:_,onTouchMove:E,onTouchEnd:S,onTouchCancel:S,onClickCapture:B=>{d.current&&(B.preventDefault(),B.stopPropagation(),d.current=!1)},children:[e.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 flex items-center justify-end bg-emerald-600 px-4 text-white",style:{opacity:Math.max(M,.2)},children:e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm font-medium",children:[e.jsx(ty,{className:"h-4 w-4"}),"Archive"]})}),e.jsx("div",{"data-inbox-row-surface":!0,className:O("relative will-change-transform",r?"bg-zinc-100 dark:bg-zinc-800":"bg-card"),style:{transform:`translate3d(${m}px, 0, 0)`,transition:x?"none":"transform 180ms ease-out"},children:t})]})}function sb(t){return t?t.split(`
|
|
124
|
+
`).map(s=>s.trim()).find(Boolean)??null:null}function qB(t){return sb(t.error)??sb(t.stderrExcerpt)??"Run exited with an error."}function UB(t){return t.replaceAll("_"," ")}function TN(t){const n=t.contextSnapshot;if(!n)return null;const s=n.issueId;if(typeof s=="string"&&s.length>0)return s;const r=n.taskId;return typeof r=="string"&&r.length>0?r:null}const BB="!text-muted-foreground !border-muted-foreground";function df(t){return t?"hover:bg-muted/80":"hover:bg-blue-500/20"}function uf(t){return t?"bg-muted-foreground/70":"bg-blue-600 dark:bg-blue-400"}function KB({issue:t,selected:n,isLive:s}){return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden shrink-0 sm:inline-flex",children:e.jsx(Pn,{status:t.status,className:n?BB:void 0})}),e.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:t.identifier??t.id.slice(0,8)}),s&&e.jsxs("span",{className:O("inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 sm:gap-1.5 sm:px-2",n?"bg-muted":"bg-blue-500/10"),children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[n?null:e.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:O("relative inline-flex h-2 w-2 rounded-full",n?"bg-muted-foreground/70":"bg-blue-500")})]}),e.jsx("span",{className:O("hidden text-[11px] font-medium sm:inline",n?"text-muted-foreground":"text-blue-600 dark:text-blue-400"),children:"Live"})]})]})}function zB({run:t,issueById:n,agentName:s,issueLinkState:r,onDismiss:a,onRetry:o,isRetrying:i,unreadState:l=null,onMarkRead:u,onArchive:d,archiveDisabled:m,selected:p=!1,className:x}){const f=TN(t),h=f?n.get(f)??null:null,j=qB(t),b=l!==null,g=l==="visible"||l==="fading";return e.jsxs("div",{className:O("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",x),children:[e.jsxs("div",{className:"flex items-start gap-2 sm:items-center",children:[b?e.jsx("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:g?e.jsx("button",{type:"button",onClick:u,className:O("inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors",df(p)),"aria-label":"Mark as read",children:e.jsx("span",{className:O("block h-2 w-2 rounded-full transition-opacity duration-300",uf(p),l==="fading"?"opacity-0":"opacity-100")})}):d?e.jsx("button",{type:"button",onClick:d,disabled:m,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:e.jsx(zt,{className:"h-3.5 w-3.5"})}):e.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,e.jsxs(Oe,{to:`/agents/${t.agentId}/runs/${t.id}`,className:O("flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors",p?"hover:bg-transparent":"hover:bg-accent/50"),children:[!b&&e.jsx("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),e.jsx("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),e.jsx("span",{className:"mt-0.5 shrink-0 rounded-md bg-red-500/20 p-1.5 sm:mt-0",children:e.jsx(fi,{className:"h-4 w-4 text-red-600 dark:text-red-400"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:h?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono text-muted-foreground mr-1.5",children:h.identifier??h.id.slice(0,8)}),h.title]}):e.jsxs(e.Fragment,{children:["Failed run",s?` — ${s}`:""]})}),e.jsxs("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[e.jsx(Dt,{status:t.status}),s&&h?e.jsx("span",{children:s}):null,e.jsx("span",{className:"truncate max-w-[300px]",children:j}),e.jsx("span",{children:as(t.createdAt)})]})]})]}),e.jsxs("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 px-2.5",onClick:o,disabled:i,children:[e.jsx(Wr,{className:"mr-1.5 h-3.5 w-3.5"}),i?"Retrying…":"Retry"]}),!b&&e.jsx("button",{type:"button",onClick:a,className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover:opacity-100","aria-label":"Dismiss",children:e.jsx(zt,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2 sm:hidden",children:[e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 px-2.5",onClick:o,disabled:i,children:[e.jsx(Wr,{className:"mr-1.5 h-3.5 w-3.5"}),i?"Retrying…":"Retry"]}),!b&&e.jsx("button",{type:"button",onClick:a,className:"rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground","aria-label":"Dismiss",children:e.jsx(zt,{className:"h-4 w-4"})})]})]})}function WB({approval:t,requesterName:n,onApprove:s,onReject:r,isPending:a,unreadState:o=null,onMarkRead:i,onArchive:l,archiveDisabled:u,selected:d=!1,className:m}){const p=lf[t.type]??cf,x=of(t.type,t.payload),f=t.type!=="budget_override_required"&&Gc.has(t.status),h=o!==null,j=o==="visible"||o==="fading";return e.jsxs("div",{className:O("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",m),children:[e.jsxs("div",{className:"flex items-start gap-2 sm:items-center",children:[h?e.jsx("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:j?e.jsx("button",{type:"button",onClick:i,className:O("inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors",df(d)),"aria-label":"Mark as read",children:e.jsx("span",{className:O("block h-2 w-2 rounded-full transition-opacity duration-300",uf(d),o==="fading"?"opacity-0":"opacity-100")})}):l?e.jsx("button",{type:"button",onClick:l,disabled:u,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:e.jsx(zt,{className:"h-3.5 w-3.5"})}):e.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,e.jsxs(Oe,{to:`/approvals/${t.id}`,className:O("flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors",d?"hover:bg-transparent":"hover:bg-accent/50"),children:[!h&&e.jsx("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),e.jsx("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),e.jsx("span",{className:"mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0",children:e.jsx(p,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:x}),e.jsxs("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"capitalize",children:UB(t.status)}),n?e.jsxs("span",{children:["requested by ",n]}):null,e.jsxs("span",{children:["updated ",as(t.updatedAt)]})]})]})]}),f?e.jsxs("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[e.jsx(G,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:s,disabled:a,children:"Approve"}),e.jsx(G,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:r,disabled:a,children:"Reject"})]}):null]}),f?e.jsxs("div",{className:"mt-3 flex gap-2 sm:hidden",children:[e.jsx(G,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:s,disabled:a,children:"Approve"}),e.jsx(G,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:r,disabled:a,children:"Reject"})]}):null]})}function HB({joinRequest:t,onApprove:n,onReject:s,isPending:r,unreadState:a=null,onMarkRead:o,onArchive:i,archiveDisabled:l,selected:u=!1,className:d}){const m=t.requestType==="human"?"Human join request":`Agent join request${t.agentName?`: ${t.agentName}`:""}`,p=a!==null,x=a==="visible"||a==="fading";return e.jsxs("div",{className:O("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",d),children:[e.jsxs("div",{className:"flex items-start gap-2 sm:items-center",children:[p?e.jsx("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:x?e.jsx("button",{type:"button",onClick:o,className:O("inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors",df(u)),"aria-label":"Mark as read",children:e.jsx("span",{className:O("block h-2 w-2 rounded-full transition-opacity duration-300",uf(u),a==="fading"?"opacity-0":"opacity-100")})}):i?e.jsx("button",{type:"button",onClick:i,disabled:l,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:e.jsx(zt,{className:"h-3.5 w-3.5"})}):e.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-2",children:[!p&&e.jsx("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),e.jsx("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),e.jsx("span",{className:"mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0",children:e.jsx(ay,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:m}),e.jsxs("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["requested ",as(t.createdAt)," from IP ",t.requestIp]}),t.adapterType&&e.jsxs("span",{children:["adapter: ",t.adapterType]})]})]})]}),e.jsxs("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[e.jsx(G,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:n,disabled:r,children:"Approve"}),e.jsx(G,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:s,disabled:r,children:"Reject"})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2 sm:hidden",children:[e.jsx(G,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:n,disabled:r,children:"Approve"}),e.jsx(G,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:s,disabled:r,children:"Reject"})]})]})}function dc(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),s=Sn(),r=fn(),a=at(),[o,i]=c.useState(null),[l,u]=c.useState("everything"),[d,m]=c.useState("all"),{dismissed:p,dismiss:x}=o0(),{readItems:f,markRead:h,markUnread:j}=ZT(),b=r.pathname.split("/").pop()??"mine",g=b==="mine"||b==="recent"||b==="all"||b==="unread"?b:"mine",y=zT(g),v=c.useMemo(()=>dN("Inbox",`${r.pathname}${r.search}${r.hash}`,"inbox"),[r.pathname,r.search,r.hash]),{data:_}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t});c.useEffect(()=>{n([{label:"Inbox"}])},[n]),c.useEffect(()=>{KT(g),ce(-1)},[g]);const{data:E,isLoading:S,error:M}=oe({queryKey:N.approvals.list(t),queryFn:()=>Wn.list(t),enabled:!!t}),{data:B=[],isLoading:k}=oe({queryKey:N.access.joinRequests(t),queryFn:async()=>{try{return await ms.listJoinRequests(t,"pending_approval")}catch(te){if(te instanceof Qr&&(te.status===403||te.status===401))return[];throw te}},enabled:!!t,retry:!1}),{data:L,isLoading:$}=oe({queryKey:N.dashboard(t),queryFn:()=>Px.summary(t),enabled:!!t}),{data:C,isLoading:I}=oe({queryKey:N.issues.list(t),queryFn:()=>nt.list(t),enabled:!!t}),{data:K=[],isLoading:T}=oe({queryKey:N.issues.listMineByMe(t),queryFn:()=>nt.list(t,{touchedByUserId:"me",inboxArchivedByUserId:"me",status:km}),enabled:!!t}),{data:z=[],isLoading:w}=oe({queryKey:N.issues.listTouchedByMe(t),queryFn:()=>nt.list(t,{touchedByUserId:"me",status:km}),enabled:!!t}),{data:F,isLoading:A}=oe({queryKey:N.heartbeats(t),queryFn:()=>Yt.list(t),enabled:!!t}),R=c.useMemo(()=>zm(K),[K]),Q=c.useMemo(()=>zm(z),[z]),H=c.useMemo(()=>Q.filter(te=>te.isUnreadForMe),[Q]),U=c.useMemo(()=>g==="mine"?R:g==="unread"?H:Q,[g,R,Q,H]),Z=c.useMemo(()=>{const te=new Map;for(const Ae of _??[])te.set(Ae.id,Ae.name);return te},[_]),V=c.useMemo(()=>{const te=new Map;for(const Ae of C??[])te.set(Ae.id,Ae);return te},[C]),W=c.useMemo(()=>r0(F??[]).filter(te=>!p.has(`run:${te.id}`)),[F,p]),J=c.useMemo(()=>{const te=new Set;for(const Ae of F??[]){if(Ae.status!=="running"&&Ae.status!=="queued")continue;const Je=TN(Ae);Je&&te.add(Je)}return te},[F]),Y=c.useMemo(()=>{let te=HT(E??[],g,d);return g==="mine"&&(te=te.filter(Ae=>!p.has(`approval:${Ae.id}`))),te},[E,g,d,p]),de=l==="everything"||l==="join_requests",fe=l==="everything"||l==="issues_i_touched",Ce=l==="everything"||l==="approvals",le=l==="everything"||l==="failed_runs",Re=l==="everything"||l==="alerts",Pe=c.useMemo(()=>g==="all"&&!le?[]:W,[W,g,le]),Fe=c.useMemo(()=>g==="all"&&!de?[]:g==="mine"?B.filter(te=>!p.has(`join:${te.id}`)):B,[B,g,de,p]),pe=c.useMemo(()=>VT({issues:g==="all"&&!fe?[]:U,approvals:g==="all"&&!Ce?[]:Y,failedRuns:Pe,joinRequests:Fe}),[Y,U,Ce,fe,g,Pe,Fe]),Le=te=>te?Z.get(te)??null:null,q=ge({mutationFn:te=>Wn.approve(te),onSuccess:(te,Ae)=>{i(null),a.invalidateQueries({queryKey:N.approvals.list(t)}),s(`/approvals/${Ae}?resolved=approved`)},onError:te=>{i(te instanceof Error?te.message:"Failed to approve")}}),D=ge({mutationFn:te=>Wn.reject(te),onSuccess:()=>{i(null),a.invalidateQueries({queryKey:N.approvals.list(t)})},onError:te=>{i(te instanceof Error?te.message:"Failed to reject")}}),ie=ge({mutationFn:te=>ms.approveJoinRequest(t,te.id),onSuccess:()=>{i(null),a.invalidateQueries({queryKey:N.access.joinRequests(t)}),a.invalidateQueries({queryKey:N.sidebarBadges(t)}),a.invalidateQueries({queryKey:N.agents.list(t)}),a.invalidateQueries({queryKey:N.companies.all})},onError:te=>{i(te instanceof Error?te.message:"Failed to approve join request")}}),Ie=ge({mutationFn:te=>ms.rejectJoinRequest(t,te.id),onSuccess:()=>{i(null),a.invalidateQueries({queryKey:N.access.joinRequests(t)}),a.invalidateQueries({queryKey:N.sidebarBadges(t)})},onError:te=>{i(te instanceof Error?te.message:"Failed to reject join request")}}),[ue,Be]=c.useState(new Set),be=ge({mutationFn:async te=>{const Ae={},Je=te.contextSnapshot;Je&&(typeof Je.issueId=="string"&&Je.issueId&&(Ae.issueId=Je.issueId),typeof Je.taskId=="string"&&Je.taskId&&(Ae.taskId=Je.taskId),typeof Je.taskKey=="string"&&Je.taskKey&&(Ae.taskKey=Je.taskKey));const ft=await We.wakeup(te.agentId,{source:"on_demand",triggerDetail:"manual",reason:"retry_failed_run",payload:Ae});if(!("id"in ft))throw new Error("Retry was skipped because the agent is not currently invokable.");return{newRun:ft,originalRun:te}},onMutate:te=>{Be(Ae=>new Set(Ae).add(te.id))},onSuccess:({newRun:te,originalRun:Ae})=>{a.invalidateQueries({queryKey:N.heartbeats(Ae.companyId)}),a.invalidateQueries({queryKey:N.heartbeats(Ae.companyId,Ae.agentId)}),s(`/agents/${Ae.agentId}/runs/${te.id}`)},onSettled:(te,Ae,Je)=>{Je&&Be(ft=>{const xn=new Set(ft);return xn.delete(Je.id),xn})}}),[he,Se]=c.useState(new Set),[we,ee]=c.useState(new Set),[me,ye]=c.useState(new Set),[Ke,qe]=c.useState(new Set),[se,ce]=c.useState(-1),Te=c.useRef(null),ae=()=>{t&&(a.invalidateQueries({queryKey:N.issues.listMineByMe(t)}),a.invalidateQueries({queryKey:N.issues.listTouchedByMe(t)}),a.invalidateQueries({queryKey:N.issues.listUnreadTouchedByMe(t)}),a.invalidateQueries({queryKey:N.sidebarBadges(t)}))},je=ge({mutationFn:te=>nt.archiveFromInbox(te),onMutate:te=>{i(null),ee(Ae=>new Set(Ae).add(te))},onSuccess:()=>{ae()},onError:(te,Ae)=>{i(te instanceof Error?te.message:"Failed to archive issue"),ee(Je=>{const ft=new Set(Je);return ft.delete(Ae),ft})},onSettled:(te,Ae,Je)=>{Ae||window.setTimeout(()=>{ee(ft=>{const xn=new Set(ft);return xn.delete(Je),xn})},500)}}),ke=ge({mutationFn:te=>nt.markRead(te),onMutate:te=>{Se(Ae=>new Set(Ae).add(te))},onSuccess:()=>{ae()},onSettled:(te,Ae,Je)=>{setTimeout(()=>{Se(ft=>{const xn=new Set(ft);return xn.delete(Je),xn})},300)}}),Xe=ge({mutationFn:async te=>{await Promise.all(te.map(Ae=>nt.markRead(Ae)))},onMutate:te=>{Se(Ae=>{const Je=new Set(Ae);for(const ft of te)Je.add(ft);return Je})},onSuccess:()=>{ae()},onSettled:(te,Ae,Je)=>{setTimeout(()=>{Se(ft=>{const xn=new Set(ft);for(const _n of Je)xn.delete(_n);return xn})},300)}}),lt=ge({mutationFn:te=>nt.markUnread(te),onSuccess:()=>{ae()}}),It=c.useCallback(te=>{ye(Ae=>new Set(Ae).add(te)),h(te),setTimeout(()=>{ye(Ae=>{const Je=new Set(Ae);return Je.delete(te),Je})},300)},[h]),Ue=c.useCallback(te=>{qe(Ae=>new Set(Ae).add(te)),setTimeout(()=>{x(te),qe(Ae=>{const Je=new Set(Ae);return Je.delete(te),Je})},200)},[x]),pt=te=>{if(!y)return null;const Ae=f.has(te);return me.has(te)?"fading":Ae?"hidden":"visible"},ht=c.useCallback(te=>te.kind==="issue"?`issue:${te.issue.id}`:te.kind==="approval"?`approval:${te.approval.id}`:te.kind==="failed_run"?`run:${te.run.id}`:`join:${te.joinRequest.id}`,[]);c.useEffect(()=>{ce(te=>WT(te,pe.length))},[pe.length]);const ln=c.useRef({workItems:pe,selectedIndex:se,canArchive:y,archivingIssueIds:we,archivingNonIssueIds:Ke,fadingOutIssues:he,readItems:f});ln.current={workItems:pe,selectedIndex:se,canArchive:y,archivingIssueIds:we,archivingNonIssueIds:Ke,fadingOutIssues:he,readItems:f};const yt=c.useRef({archiveIssue:te=>je.mutate(te),archiveNonIssue:Ue,markRead:te=>ke.mutate(te),markUnreadIssue:te=>lt.mutate(te),markNonIssueRead:It,markNonIssueUnread:j,navigate:s});if(yt.current={archiveIssue:te=>je.mutate(te),archiveNonIssue:Ue,markRead:te=>ke.mutate(te),markUnreadIssue:te=>lt.mutate(te),markNonIssueRead:It,markNonIssueUnread:j,navigate:s},c.useEffect(()=>{const te=Ae=>{if(Ae.defaultPrevented)return;const Je=Ae.target;if(!(Je instanceof HTMLElement)||Je.closest("input, textarea, select, [contenteditable='true'], [role='textbox'], [role='combobox']")||Je.isContentEditable||document.querySelector("[role='dialog'], [aria-modal='true']")||Ae.metaKey||Ae.ctrlKey||Ae.altKey)return;const ft=ln.current,xn=yt.current;if(!ft.canArchive)return;const _n=ft.workItems.length;if(_n!==0)switch(Ae.key){case"j":{Ae.preventDefault(),ce(bt=>dh(bt,_n,"next"));break}case"k":{Ae.preventDefault(),ce(bt=>dh(bt,_n,"previous"));break}case"a":case"y":{if(ft.selectedIndex<0||ft.selectedIndex>=_n)return;Ae.preventDefault();const bt=ft.workItems[ft.selectedIndex];if(bt.kind==="issue")ft.archivingIssueIds.has(bt.issue.id)||xn.archiveIssue(bt.issue.id);else{const Gt=ht(bt);ft.archivingNonIssueIds.has(Gt)||xn.archiveNonIssue(Gt)}break}case"U":{if(ft.selectedIndex<0||ft.selectedIndex>=_n)return;Ae.preventDefault();const bt=ft.workItems[ft.selectedIndex];bt.kind==="issue"?xn.markUnreadIssue(bt.issue.id):xn.markNonIssueUnread(ht(bt));break}case"r":{if(ft.selectedIndex<0||ft.selectedIndex>=_n)return;Ae.preventDefault();const bt=ft.workItems[ft.selectedIndex];if(bt.kind==="issue")bt.issue.isUnreadForMe&&!ft.fadingOutIssues.has(bt.issue.id)&&xn.markRead(bt.issue.id);else{const Gt=ht(bt);ft.readItems.has(Gt)||xn.markNonIssueRead(Gt)}break}case"Enter":{if(ft.selectedIndex<0||ft.selectedIndex>=_n)return;Ae.preventDefault();const bt=ft.workItems[ft.selectedIndex];if(bt.kind==="issue"){const Gt=bt.issue.identifier??bt.issue.id;xn.navigate(Gi(Gt,v),{state:v})}else bt.kind==="approval"?xn.navigate(`/approvals/${bt.approval.id}`):bt.kind==="failed_run"&&xn.navigate(`/agents/${bt.run.agentId}/runs/${bt.run.id}`);break}default:return}};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[ht,v]),c.useEffect(()=>{if(se<0||!Te.current)return;const Ae=Te.current.querySelectorAll("[data-inbox-item]")[se];Ae&&Ae.scrollIntoView({block:"nearest"})},[se]),!t)return e.jsx(tn,{icon:Ga,message:"Select a company to view inbox."});const hn=W.length>0,pn=!!L&&L.agents.error>0&&!hn&&!p.has("alert:agent-errors"),re=!!L&&L.costs.monthBudgetCents>0&&L.costs.monthUtilizationPercent>=80&&!p.has("alert:budget"),$e=pn||re,Ee=pe.length>0,He=QT({tab:g,hasItems:$e,showOnMine:$e,showOnRecent:$e,showOnUnread:$e,showOnAll:Re&&$e}),rt=[He?"alerts":null,Ee?"work_items":null].filter(te=>te!==null),xt=!k&&!S&&!$&&!I&&!T&&!w&&!A,Pt=te=>rt.indexOf(te)>0,$n=(g==="mine"?R:H).filter(te=>te.isUnreadForMe&&!he.has(te.id)&&!we.has(te.id)).map(te=>te.id),Ne=$n.length>0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ss,{value:g,onValueChange:te=>s(`/inbox/${te}`),children:e.jsx(Ca,{items:[{value:"mine",label:"Mine"},{value:"recent",label:"Recent"},{value:"unread",label:"Unread"},{value:"all",label:"All"}]})}),e.jsx("div",{className:"flex items-center gap-2",children:Ne&&e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0",onClick:()=>Xe.mutate($n),disabled:Xe.isPending,children:Xe.isPending?"Marking…":"Mark all as read"})})]}),g==="all"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Hn,{value:l,onValueChange:te=>u(te),children:[e.jsx(Qn,{className:"h-8 w-[170px] text-xs",children:e.jsx(Vn,{placeholder:"Category"})}),e.jsxs(Gn,{children:[e.jsx(Mt,{value:"everything",children:"All categories"}),e.jsx(Mt,{value:"issues_i_touched",children:"My recent issues"}),e.jsx(Mt,{value:"join_requests",children:"Join requests"}),e.jsx(Mt,{value:"approvals",children:"Approvals"}),e.jsx(Mt,{value:"failed_runs",children:"Failed runs"}),e.jsx(Mt,{value:"alerts",children:"Alerts"})]})]}),Ce&&e.jsxs(Hn,{value:d,onValueChange:te=>m(te),children:[e.jsx(Qn,{className:"h-8 w-[170px] text-xs",children:e.jsx(Vn,{placeholder:"Approval status"})}),e.jsxs(Gn,{children:[e.jsx(Mt,{value:"all",children:"All approval statuses"}),e.jsx(Mt,{value:"actionable",children:"Needs action"}),e.jsx(Mt,{value:"resolved",children:"Resolved"})]})]})]}),M&&e.jsx("p",{className:"text-sm text-destructive",children:M.message}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),!xt&&rt.length===0&&e.jsx(mn,{variant:"inbox"}),xt&&rt.length===0&&e.jsx(tn,{icon:Ga,message:g==="mine"?"Inbox zero.":g==="unread"?"No new inbox items.":g==="recent"?"No recent inbox items.":"No inbox items match these filters."}),Ee&&e.jsxs(e.Fragment,{children:[Pt("work_items")&&e.jsx(yn,{}),e.jsx("div",{children:e.jsx("div",{ref:Te,className:"overflow-hidden rounded-xl border border-border bg-card",children:pe.flatMap((te,Ae)=>{const Je=(qt,us,qs)=>e.jsx("div",{"data-inbox-item":!0,className:"relative",onClick:()=>ce(Ae),children:qs},`sel-${qt}`),ft=Date.now()-864e5,xn=Ae>0&&te.timestamp>0&&te.timestamp<ft&&pe[Ae-1].timestamp>=ft,_n=[];xn&&_n.push(e.jsxs("div",{className:"flex items-center gap-3 px-4 my-2",children:[e.jsx("div",{className:"flex-1 border-t border-border"}),e.jsx("span",{className:"shrink-0 text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Earlier"})]},"today-divider"));const bt=se===Ae;if(te.kind==="approval"){const qt=`approval:${te.approval.id}`,us=Ke.has(qt),qs=e.jsx(WB,{approval:te.approval,selected:bt,requesterName:Le(te.approval.requestedByAgentId),onApprove:()=>q.mutate(te.approval.id),onReject:()=>D.mutate(te.approval.id),isPending:q.isPending||D.isPending,unreadState:pt(qt),onMarkRead:()=>It(qt),onArchive:y?()=>Ue(qt):void 0,archiveDisabled:us,className:us?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},qt);return _n.push(Je(qt,bt,y?e.jsx(cc,{selected:bt,disabled:us,onArchive:()=>Ue(qt),children:qs},qt):qs)),_n}if(te.kind==="failed_run"){const qt=`run:${te.run.id}`,us=Ke.has(qt),qs=e.jsx(zB,{run:te.run,selected:bt,issueById:V,agentName:Le(te.run.agentId),issueLinkState:v,onDismiss:()=>x(qt),onRetry:()=>be.mutate(te.run),isRetrying:ue.has(te.run.id),unreadState:pt(qt),onMarkRead:()=>It(qt),onArchive:y?()=>Ue(qt):void 0,archiveDisabled:us,className:us?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},qt);return _n.push(Je(qt,bt,y?e.jsx(cc,{selected:bt,disabled:us,onArchive:()=>Ue(qt),children:qs},qt):qs)),_n}if(te.kind==="join_request"){const qt=`join:${te.joinRequest.id}`,us=Ke.has(qt),qs=e.jsx(HB,{joinRequest:te.joinRequest,selected:bt,onApprove:()=>ie.mutate(te.joinRequest),onReject:()=>Ie.mutate(te.joinRequest),isPending:ie.isPending||Ie.isPending,unreadState:pt(qt),onMarkRead:()=>It(qt),onArchive:y?()=>Ue(qt):void 0,archiveDisabled:us,className:us?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},qt);return _n.push(Je(qt,bt,y?e.jsx(cc,{selected:bt,disabled:us,onArchive:()=>Ue(qt),children:qs},qt):qs)),_n}const Gt=te.issue,Jr=Gt.isUnreadForMe&&!he.has(Gt.id),cu=he.has(Gt.id),ki=we.has(Gt.id),Bl=e.jsx(uN,{issue:Gt,issueLinkState:v,selected:bt,className:ki?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out",desktopMetaLeading:e.jsx(KB,{issue:Gt,selected:bt,isLive:J.has(Gt.id)}),mobileMeta:Gt.lastExternalCommentAt?`commented ${as(Gt.lastExternalCommentAt)}`:`updated ${as(Gt.updatedAt)}`,unreadState:Jr?"visible":cu?"fading":"hidden",onMarkRead:()=>ke.mutate(Gt.id),onArchive:y?()=>je.mutate(Gt.id):void 0,archiveDisabled:ki||je.isPending,trailingMeta:Gt.lastExternalCommentAt?`commented ${as(Gt.lastExternalCommentAt)}`:`updated ${as(Gt.updatedAt)}`},`issue:${Gt.id}`);return _n.push(Je(`issue:${Gt.id}`,bt,y?e.jsx(cc,{selected:bt,disabled:ki||je.isPending,onArchive:()=>je.mutate(Gt.id),children:Bl},`issue:${Gt.id}`):Bl)),_n})})})]}),He&&e.jsxs(e.Fragment,{children:[Pt("alerts")&&e.jsx(yn,{}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Alerts"}),e.jsxs("div",{className:"divide-y divide-border border border-border",children:[pn&&e.jsxs("div",{className:"group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50",children:[e.jsxs(Oe,{to:"/agents",className:"flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit",children:[e.jsx(ir,{className:"h-4 w-4 shrink-0 text-red-600 dark:text-red-400"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:L.agents.error})," ",L.agents.error===1?"agent has":"agents have"," errors"]})]}),e.jsx("button",{type:"button",onClick:()=>x("alert:agent-errors"),className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100","aria-label":"Dismiss",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]}),re&&e.jsxs("div",{className:"group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50",children:[e.jsxs(Oe,{to:"/costs",className:"flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit",children:[e.jsx(ir,{className:"h-4 w-4 shrink-0 text-yellow-400"}),e.jsxs("span",{className:"text-sm",children:["Budget at"," ",e.jsxs("span",{className:"font-medium",children:[L.costs.monthUtilizationPercent,"%"]})," ","utilization this month"]})]}),e.jsx("button",{type:"button",onClick:()=>x("alert:budget"),className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100","aria-label":"Dismiss",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]})]})]})]})]})}function VB(){const{companies:t,selectedCompany:n,selectedCompanyId:s,setSelectedCompanyId:r}=et(),{setBreadcrumbs:a}=Ft(),{pushToast:o}=ds(),i=at(),[l,u]=c.useState(""),[d,m]=c.useState(""),[p,x]=c.useState(""),[f,h]=c.useState(""),[j,b]=c.useState(null);c.useEffect(()=>{n&&(u(n.name),m(n.description??""),x(n.brandColor??""),h(n.logoUrl??""))},[n]);const[g,y]=c.useState(null),[v,_]=c.useState(null),[E,S]=c.useState(!1),[M,B]=c.useState(0),k=!!n&&(l!==n.name||d!==(n.description??"")||p!==(n.brandColor??"")),L=ge({mutationFn:R=>ls.update(s,R),onSuccess:()=>{i.invalidateQueries({queryKey:N.companies.all})}}),$=ge({mutationFn:R=>ls.update(s,{requireBoardApprovalForNewAgents:R}),onSuccess:()=>{i.invalidateQueries({queryKey:N.companies.all})}}),C=ge({mutationFn:()=>ms.createOpenClawInvitePrompt(s),onSuccess:async R=>{var V,W,J;y(null);const Q=window.location.origin.replace(/\/+$/,""),H=R.onboardingTextUrl??R.onboardingTextPath??`/api/invites/${R.token}/onboarding.txt`,U=H.startsWith("http")?H:`${Q}${H}`;S(!1),B(0);let Z;try{const Y=await ms.getInviteOnboarding(R.token);Z=rb({onboardingTextUrl:U,connectionCandidates:((V=Y.onboarding.connectivity)==null?void 0:V.connectionCandidates)??null,testResolutionUrl:((J=(W=Y.onboarding.connectivity)==null?void 0:W.testResolutionEndpoint)==null?void 0:J.url)??null})}catch{Z=rb({onboardingTextUrl:U,connectionCandidates:null,testResolutionUrl:null})}_(Z);try{await navigator.clipboard.writeText(Z),S(!0),B(Y=>Y+1),setTimeout(()=>S(!1),2e3)}catch{}i.invalidateQueries({queryKey:N.sidebarBadges(s)})},onError:R=>{y(R instanceof Error?R.message:"Failed to create invite")}}),I=R=>{h(R??""),i.invalidateQueries({queryKey:N.companies.all})},K=ge({mutationFn:R=>Aa.uploadCompanyLogo(s,R).then(Q=>ls.update(s,{logoAssetId:Q.assetId})),onSuccess:R=>{I(R.logoUrl),b(null)}}),T=ge({mutationFn:()=>ls.update(s,{logoAssetId:null}),onSuccess:R=>{b(null),I(R.logoUrl)}});function z(R){var H;const Q=((H=R.target.files)==null?void 0:H[0])??null;R.currentTarget.value="",Q&&(b(null),K.mutate(Q))}function w(){T.mutate()}c.useEffect(()=>{y(null),_(null),S(!1),B(0)},[s]);const F=ge({mutationFn:({companyId:R,nextCompanyId:Q})=>ls.archive(R).then(()=>({nextCompanyId:Q})),onSuccess:async({nextCompanyId:R})=>{R&&r(R),await i.invalidateQueries({queryKey:N.companies.all}),await i.invalidateQueries({queryKey:N.companies.stats})}});if(c.useEffect(()=>{a([{label:(n==null?void 0:n.name)??"Company",href:"/dashboard"},{label:"Settings"}])},[a,n==null?void 0:n.name]),!n)return e.jsx("div",{className:"text-sm text-muted-foreground",children:"No company selected. Select a company from the switcher above."});function A(){L.mutate({name:l.trim(),description:d.trim()||null,brandColor:p||null})}return e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h1",{className:"text-lg font-semibold",children:"Company Settings"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"General"}),e.jsxs("div",{className:"space-y-3 rounded-md border border-border px-4 py-4",children:[e.jsx(ct,{label:"Company name",hint:"The display name for your company.",children:e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",type:"text",value:l,onChange:R=>u(R.target.value)})}),e.jsx(ct,{label:"Description",hint:"Optional description shown in the company profile.",children:e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",type:"text",value:d,placeholder:"Optional company description",onChange:R=>m(R.target.value)})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Appearance"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border px-4 py-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0",children:e.jsx(Fj,{companyName:l||n.name,logoUrl:f||null,brandColor:p||null,className:"rounded-[14px]"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(ct,{label:"Logo",hint:"Upload a PNG, JPEG, WEBP, GIF, or SVG logo image.",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp,image/gif,image/svg+xml",onChange:z,className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none file:mr-4 file:rounded-md file:border-0 file:bg-muted file:px-2.5 file:py-1 file:text-xs"}),f&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(G,{size:"sm",variant:"outline",onClick:w,disabled:T.isPending,children:T.isPending?"Removing...":"Remove logo"})}),(K.isError||j)&&e.jsx("span",{className:"text-xs text-destructive",children:j??(K.error instanceof Error?K.error.message:"Logo upload failed")}),T.isError&&e.jsx("span",{className:"text-xs text-destructive",children:T.error.message}),K.isPending&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploading logo..."})]})}),e.jsx(ct,{label:"Brand color",hint:"Sets the hue for the company icon. Leave empty for auto-generated color.",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:p||"#6366f1",onChange:R=>x(R.target.value),className:"h-8 w-8 cursor-pointer rounded border border-border bg-transparent p-0"}),e.jsx("input",{type:"text",value:p,onChange:R=>{const Q=R.target.value;(Q===""||/^#[0-9a-fA-F]{0,6}$/.test(Q))&&x(Q)},placeholder:"Auto",className:"w-28 rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm font-mono outline-none"}),p&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>x(""),className:"text-xs text-muted-foreground",children:"Clear"})]})})]})]})})]}),k&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{size:"sm",onClick:A,disabled:L.isPending||!l.trim(),children:L.isPending?"Saving...":"Save changes"}),L.isSuccess&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Saved"}),L.isError&&e.jsx("span",{className:"text-xs text-destructive",children:L.error instanceof Error?L.error.message:"Failed to save"})]}),e.jsxs("div",{className:"space-y-4","data-testid":"company-settings-team-section",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Hiring"}),e.jsx("div",{className:"rounded-md border border-border px-4 py-3",children:e.jsx(ao,{label:"Require board approval for new hires",hint:"New agent hires stay pending until approved by board.",checked:!!n.requireBoardApprovalForNewAgents,onChange:R=>$.mutate(R),toggleTestId:"company-settings-team-approval-toggle"})})]}),e.jsxs("div",{className:"space-y-4","data-testid":"company-settings-invites-section",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Invites"}),e.jsxs("div",{className:"space-y-3 rounded-md border border-border px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Generate an OpenClaw agent invite snippet."}),e.jsx(xl,{text:"Creates a short-lived OpenClaw agent invite and renders a copy-ready prompt."})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(G,{"data-testid":"company-settings-invites-generate-button",size:"sm",onClick:()=>C.mutate(),disabled:C.isPending,children:C.isPending?"Generating...":"Generate OpenClaw Invite Prompt"})}),g&&e.jsx("p",{className:"text-sm text-destructive",children:g}),v&&e.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-2","data-testid":"company-settings-invites-snippet",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"OpenClaw Invite Prompt"}),E&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-600 animate-pulse",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Copied"]},M)]}),e.jsxs("div",{className:"mt-1 space-y-1.5",children:[e.jsx("textarea",{"data-testid":"company-settings-invites-snippet-textarea",className:"h-[28rem] w-full rounded-md border border-border bg-background px-2 py-1.5 font-mono text-xs outline-none",value:v,readOnly:!0}),e.jsx("div",{className:"flex justify-end",children:e.jsx(G,{"data-testid":"company-settings-invites-copy-button",size:"sm",variant:"ghost",onClick:async()=>{try{await navigator.clipboard.writeText(v),S(!0),B(R=>R+1),setTimeout(()=>S(!1),2e3)}catch{}},children:E?"Copied snippet":"Copy snippet"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Company Packages"}),e.jsxs("div",{className:"rounded-md border border-border px-4 py-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Import and export have moved to dedicated pages accessible from the"," ",e.jsx("a",{href:"/org",className:"underline hover:text-foreground",children:"Org Chart"})," header."]}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:"/company/export",children:[e.jsx(ei,{className:"mr-1.5 h-3.5 w-3.5"}),"Export"]})}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:"/company/import",children:[e.jsx(ol,{className:"mr-1.5 h-3.5 w-3.5"}),"Import"]})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs font-medium text-destructive uppercase tracking-wide",children:"Danger Zone"}),e.jsxs("div",{className:"space-y-3 rounded-md border border-destructive/40 bg-destructive/5 px-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Archive this company to hide it from the sidebar. This persists in the database."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{size:"sm",variant:"destructive",disabled:F.isPending||n.status==="archived",onClick:()=>{var H;if(!s||!window.confirm(`Archive company "${n.name}"? It will be hidden from the sidebar.`))return;const Q=((H=t.find(U=>U.id!==s&&U.status!=="archived"))==null?void 0:H.id)??null;F.mutate({companyId:s,nextCompanyId:Q})},children:F.isPending?"Archiving...":n.status==="archived"?"Already archived":"Archive company"}),F.isError&&e.jsx("span",{className:"text-xs text-destructive",children:F.error instanceof Error?F.error.message:"Failed to archive company"})]})]})]})]})}function rb(t){const n=QB(t),s=GB(t),r=n.length>0?n.map(i=>`- ${i}`).join(`
|
|
125
|
+
`):"- (No candidate URLs available yet.)",a=n.length===0?`No candidate URLs are available. Ask your user to configure a reachable hostname in CrewSpace, then retry.
|
|
126
|
+
Suggested steps:
|
|
127
|
+
- choose a hostname that resolves to the CrewSpace host from your runtime
|
|
128
|
+
- run: pnpm crewspaceai allowed-hostname <host>
|
|
129
|
+
- restart CrewSpace
|
|
130
|
+
- verify with: curl -fsS http://<host>:3100/api/health
|
|
131
|
+
- regenerate this invite snippet`:`If none are reachable, ask your user to add a reachable hostname in CrewSpace, restart, and retry.
|
|
132
|
+
Suggested command:
|
|
133
|
+
- pnpm crewspaceai allowed-hostname <host>
|
|
134
|
+
Then verify with: curl -fsS <base-url>/api/health`,o=s?`
|
|
135
|
+
You MUST test CrewSpace-to-gateway reachability, call: ${s}?url=<urlencoded-gateway-url> (using the hostname that worked above). Do not assume your 172.x is necessarily reachable from CrewSpace. Test it. `:"";return`You're invited to join a CrewSpace organization.
|
|
136
|
+
|
|
137
|
+
The URLs you should try are:
|
|
138
|
+
${r}
|
|
139
|
+
|
|
140
|
+
Connectivity guidance:
|
|
141
|
+
If you are running on a different machine than CrewSpace, CrewSpace must be reachable at one of the hostnames used above.
|
|
142
|
+
Verify the hostname works from your runtime with: GET <base-url>/api/health
|
|
143
|
+
|
|
144
|
+
${a}
|
|
145
|
+
|
|
146
|
+
For your "agentName", just use your own agent name (OpenClaw or whatever your name is) and send it directly.
|
|
147
|
+
You also need to send a gateway URL that CrewSpace can access. Check your config and include that URL.${o}
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
This onboarding flow is for OpenClaw Gateway.
|
|
152
|
+
When you submit the join request, use:
|
|
153
|
+
- \`adapterType: "openclaw_gateway"\`
|
|
154
|
+
- \`agentDefaultsPayload.url\` as your \`ws://\` or \`wss://\` gateway URL
|
|
155
|
+
- \`agentDefaultsPayload.headers["x-openclaw-token"]\` with your gateway token
|
|
156
|
+
- (legacy accepted) \`agentDefaultsPayload.headers["x-openclaw-auth"]\`
|
|
157
|
+
- Keep device auth enabled (recommended). If \`devicePrivateKeyPem\` is omitted, CrewSpace will generate and persist one during join so pairing approvals remain stable.
|
|
158
|
+
- Only use \`disableDeviceAuth=true\` for special environments where pairing cannot be completed.
|
|
159
|
+
|
|
160
|
+
Do NOT use \`/v1/responses\` or \`/hooks/*\` in this join flow.
|
|
161
|
+
|
|
162
|
+
Before you do anything, please respond to your user that you understand the instructions and you're going to work on them. Then do the step above in another session called "crewspace-onboarding" and then tell your user when you're done. Update your user in intermediate steps along the way so they know what's going on.
|
|
163
|
+
|
|
164
|
+
Then after you've connected to CrewSpace (exchanged keys etc.) you MUST review and follow the onboarding instructions in onboarding.txt they give you.
|
|
165
|
+
|
|
166
|
+
`}function QB(t){const n=(t.connectionCandidates??[]).map(o=>o.trim()).filter(Boolean),s=new Set;let r=null;try{r=new URL(t.onboardingTextUrl),s.add(r.toString())}catch{const o=t.onboardingTextUrl.trim();o&&s.add(o)}if(!r){for(const o of n)s.add(o);return Array.from(s)}const a=`${r.pathname}${r.search}`;for(const o of n)try{const i=new URL(o);s.add(`${i.origin}${a}`)}catch{s.add(o)}return Array.from(s)}function GB(t){var s;const n=(s=t.testResolutionUrl)==null?void 0:s.trim();if(n)return n;try{const r=new URL(t.onboardingTextUrl),a=r.pathname.replace(/\/onboarding\.txt$/,"/test-resolution");return`${r.origin}${a}`}catch{return null}}const ab=16,ob=24,ib="min-h-9";function lb(t){return e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...t,children:e.jsx("path",{d:"M12 4 21 19H3z"})})}function JB(t){const n=t.replace(/\r\n/g,`
|
|
167
|
+
`);if(!n.startsWith(`---
|
|
168
|
+
`))return n.trim();const s=n.indexOf(`
|
|
169
|
+
---
|
|
170
|
+
`,4);return s<0?n.trim():n.slice(s+5).trim()}function pp(t){const n=t.replace(/\r\n/g,`
|
|
171
|
+
`);if(!n.startsWith(`---
|
|
172
|
+
`))return{frontmatter:null,body:n};const s=n.indexOf(`
|
|
173
|
+
---
|
|
174
|
+
`,4);return s<0?{frontmatter:null,body:n}:{frontmatter:n.slice(4,s).trim(),body:n.slice(s+5).trimStart()}}function ZB(t,n){const s=pp(t);return s.frontmatter?["---",s.frontmatter,"---","",n].join(`
|
|
175
|
+
`):n}function YB(t){const n={children:[]};for(const r of t){const a=r.path.split("/").filter(Boolean);let o=n,i="";for(const[l,u]of a.entries()){i=i?`${i}/${u}`:u;const d=l===a.length-1;let m=o.children.find(p=>p.name===u);m||(m={name:u,path:d?r.path:i,kind:d?"file":"dir",fileKind:d?r.kind:void 0,children:[]},o.children.push(m)),o=m}}function s(r){r.children.sort((a,o)=>a.kind!==o.kind?a.kind==="dir"?-1:1:a.name==="SKILL.md"?-1:o.name==="SKILL.md"?1:a.name.localeCompare(o.name)),r.children.forEach(s)}return s(n),n.children}function RN(t,n){const s=(n==null?void 0:n.toLowerCase())??"",r=s.includes("skills.sh")||s.includes("vercel-labs/skills");switch(t){case"skills_sh":return{icon:lb,label:n??"skills.sh",managedLabel:"skills.sh managed"};case"github":return r?{icon:lb,label:n??"skills.sh",managedLabel:"skills.sh managed"}:{icon:Sc,label:n??"GitHub",managedLabel:"GitHub managed"};case"url":return{icon:oy,label:n??"URL",managedLabel:"URL managed"};case"local":return{icon:Op,label:n??"Folder",managedLabel:"Folder managed"};case"crewspace":return{icon:ai,label:n??"CrewSpace",managedLabel:"CrewSpace managed"};default:return{icon:Cd,label:n??"Catalog",managedLabel:"Catalog managed"}}}function xp(t){return t?t.slice(0,7):null}function XB(t){const n=[`${t.discovered} found`,`${t.imported.length} imported`,`${t.updated.length} updated`];return t.conflicts.length>0&&n.push(`${t.conflicts.length} conflicts`),t.skipped.length>0&&n.push(`${t.skipped.length} skipped`),`${n.join(", ")} across ${t.scannedWorkspaces} workspace${t.scannedWorkspaces===1?"":"s"}.`}function eK(t){return t==="script"||t==="reference"?ey:Id}function tK(t){return t.split("/").map(n=>encodeURIComponent(n)).join("/")}function nK(t){return t?t.split("/").filter(Boolean).map(n=>{try{return decodeURIComponent(n)}catch{return n}}).join("/"):"SKILL.md"}function sK(t){const n=(t??"").split("/").filter(Boolean);if(n.length===0)return{skillId:null,filePath:"SKILL.md"};const[s,r,...a]=n,o=s?decodeURIComponent(s):null;return o?r==="files"?{skillId:o,filePath:nK(a.join("/"))}:{skillId:o,filePath:"SKILL.md"}:{skillId:null,filePath:"SKILL.md"}}function Uo(t,n){return n?`/skills/${t}/files/${tK(n)}`:`/skills/${t}`}function rK(t){const n=t.split("/").filter(Boolean),s=[];for(let r=0;r<n.length-1;r+=1)s.push(n.slice(0,r+1).join("/"));return s}function aK({onCreate:t,isPending:n,onCancel:s}){const[r,a]=c.useState(""),[o,i]=c.useState(""),[l,u]=c.useState("");return e.jsx("div",{className:"border-b border-border px-4 py-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(Xt,{value:r,onChange:d=>a(d.target.value),placeholder:"Skill name",className:"h-9 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"}),e.jsx(Xt,{value:o,onChange:d=>i(d.target.value),placeholder:"optional-shortname",className:"h-9 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"}),e.jsx(Ur,{value:l,onChange:d=>u(d.target.value),placeholder:"Short description",className:"min-h-20 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:s,disabled:n,children:"Cancel"}),e.jsx(G,{size:"sm",onClick:()=>t({name:r,slug:o||null,description:l||null}),disabled:n||r.trim().length===0,children:n?"Creating...":"Create skill"})]})]})})}function PN({nodes:t,skillId:n,selectedPath:s,expandedDirs:r,onToggleDir:a,onSelectPath:o,depth:i=0}){return e.jsx("div",{children:t.map(l=>{const u=l.kind==="dir"&&l.path?r.has(l.path):!1;if(l.kind==="dir")return e.jsxs("div",{children:[e.jsxs("div",{className:O("group grid w-full grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",ib),children:[e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-2 py-1 text-left",style:{paddingLeft:`${ab+i*ob}px`},onClick:()=>l.path&&a(l.path),children:[e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center",children:u?e.jsx(kl,{className:"h-3.5 w-3.5"}):e.jsx(Op,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"truncate",children:l.name})]}),e.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center self-center rounded-sm text-muted-foreground opacity-70 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100",onClick:()=>l.path&&a(l.path),children:u?e.jsx(rn,{className:"h-3.5 w-3.5"}):e.jsx(sn,{className:"h-3.5 w-3.5"})})]}),u&&e.jsx(PN,{nodes:l.children,skillId:n,selectedPath:s,expandedDirs:r,onToggleDir:a,onSelectPath:o,depth:i+1})]},l.path??l.name);const d=eK(l.fileKind??"other");return e.jsxs(Oe,{className:O("flex w-full items-center gap-2 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",ib,l.path===s&&"text-foreground"),style:{paddingInlineStart:`${ab+i*ob}px`},to:Uo(n,l.path),onClick:()=>l.path&&o(l.path),children:[e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center",children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"truncate",children:l.name})]},l.path??l.name)})})}function oK({skills:t,selectedSkillId:n,skillFilter:s,expandedSkillId:r,expandedDirs:a,selectedPaths:o,onToggleSkill:i,onToggleDir:l,onSelectSkill:u,onSelectPath:d}){const m=t.filter(p=>`${p.name} ${p.key} ${p.slug} ${p.sourceLabel??""}`.toLowerCase().includes(s.toLowerCase()));return m.length===0?e.jsx("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"No skills match this filter."}):e.jsx("div",{children:m.map(p=>{const x=r===p.id,f=YB(p.fileInventory),h=RN(p.sourceBadge,p.sourceLabel),j=h.icon;return e.jsxs("div",{className:"border-b border-border",children:[e.jsxs("div",{className:O("group grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",p.id===n&&"text-foreground"),children:[e.jsx(Oe,{to:Uo(p.id),className:"flex min-w-0 items-center self-stretch pr-2 text-left no-underline",onClick:()=>u(p.id),children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2 self-center",children:[e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsxs("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100",children:[e.jsx(j,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:h.managedLabel})]})}),e.jsx(Yn,{side:"top",children:h.managedLabel})]}),e.jsx("span",{className:"min-w-0 overflow-hidden text-[13px] font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]",children:p.name})]})}),e.jsx("button",{type:"button",className:"flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100",onClick:()=>i(p.id),"aria-label":x?`Collapse ${p.name}`:`Expand ${p.name}`,children:x?e.jsx(rn,{className:"h-3.5 w-3.5"}):e.jsx(sn,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{"aria-hidden":!x,className:O("grid overflow-hidden transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)]",x?"grid-rows-[1fr] opacity-100":"grid-rows-[0fr] opacity-0"),children:e.jsx("div",{className:"min-h-0 overflow-hidden",children:e.jsx(PN,{nodes:f,skillId:p.id,selectedPath:o[p.id]??"SKILL.md",expandedDirs:a[p.id]??new Set,onToggleDir:b=>l(p.id,b),onSelectPath:b=>d(p.id,b),depth:1})})})]},p.id)})})}function iK({loading:t,detail:n,file:s,fileLoading:r,updateStatus:a,updateStatusLoading:o,viewMode:i,editMode:l,draft:u,setViewMode:d,setEditMode:m,setDraft:p,onCheckUpdates:x,checkUpdatesPending:f,onInstallUpdate:h,installUpdatePending:j,onSave:b,savePending:g}){const{pushToast:y}=ds();if(!n)return t?e.jsx(mn,{variant:"detail"}):e.jsx(tn,{icon:Cd,message:"Select a skill to inspect its files."});const v=RN(n.sourceBadge,n.sourceLabel),_=v.icon,E=n.usedByAgents,S=s!=null&&s.markdown?JB(s.content):(s==null?void 0:s.content)??"",M=xp(n.sourceRef),B=xp(a==null?void 0:a.latestRef);return e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"border-b border-border px-5 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"flex items-center gap-2 truncate text-2xl font-semibold",children:[e.jsx(_,{className:"h-5 w-5 shrink-0 text-muted-foreground"}),n.name]}),n.description&&e.jsx("p",{className:"mt-2 max-w-3xl text-sm text-muted-foreground",children:n.description})]}),n.editable?e.jsxs("button",{className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground",onClick:()=>m(!l),children:[e.jsx(Cc,{className:"h-3.5 w-3.5"}),l?"Stop editing":"Edit"]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:n.editableReason})]}),e.jsxs("div",{className:"mt-4 space-y-3 border-t border-border pt-4 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Source"}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(_,{className:"h-3.5 w-3.5 text-muted-foreground"}),n.sourcePath?e.jsx("button",{className:"truncate hover:text-foreground text-muted-foreground transition-colors cursor-pointer",onClick:()=>{navigator.clipboard.writeText(n.sourcePath),y({title:"Copied path to workspace"})},children:v.label}):e.jsx("span",{className:"truncate",children:v.label})]})]}),n.sourceType==="github"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Pin"}),e.jsx("span",{className:"font-mono text-xs",children:M??"untracked"}),(a==null?void 0:a.trackingRef)&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["tracking ",a.trackingRef]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:x,disabled:f||o,children:[e.jsx(Za,{className:O("mr-1.5 h-3.5 w-3.5",(f||o)&&"animate-spin")}),"Check for updates"]}),(a==null?void 0:a.supported)&&a.hasUpdate&&e.jsxs(G,{size:"sm",onClick:h,disabled:j,children:[e.jsx(Za,{className:O("mr-1.5 h-3.5 w-3.5",j&&"animate-spin")}),"Install update",B?` ${B}`:""]}),(a==null?void 0:a.supported)&&!a.hasUpdate&&!o&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Up to date"}),!(a!=null&&a.supported)&&(a==null?void 0:a.reason)&&e.jsx("span",{className:"text-xs text-muted-foreground",children:a.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Key"}),e.jsx("span",{className:"font-mono text-xs",children:n.key})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Mode"}),e.jsx("span",{children:n.editable?"Editable":"Read only"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-start gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"Used by"}),E.length===0?e.jsx("span",{className:"text-muted-foreground",children:"No agents attached"}):e.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1",children:E.map(k=>e.jsx(Oe,{to:`/agents/${k.urlKey}/skills`,className:"text-foreground no-underline hover:underline",children:k.name},k.id))})]})]})]}),e.jsx("div",{className:"border-b border-border px-5 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:e.jsx("div",{className:"truncate font-mono text-sm",children:(s==null?void 0:s.path)??"SKILL.md"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[(s==null?void 0:s.markdown)&&!l&&e.jsxs("div",{className:"flex items-center border border-border",children:[e.jsx("button",{className:O("px-3 py-1.5 text-sm",i==="preview"&&"text-foreground",i!=="preview"&&"text-muted-foreground"),onClick:()=>d("preview"),children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(pi,{className:"h-3.5 w-3.5"}),"View"]})}),e.jsx("button",{className:O("border-l border-border px-3 py-1.5 text-sm",i==="code"&&"text-foreground",i!=="code"&&"text-muted-foreground"),onClick:()=>d("code"),children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(P1,{className:"h-3.5 w-3.5"}),"Code"]})})]}),l&&(s==null?void 0:s.editable)&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>m(!1),disabled:g,children:"Cancel"}),e.jsxs(G,{size:"sm",onClick:b,disabled:g,children:[e.jsx(Lp,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Saving...":"Save"]})]})]})]})}),e.jsx("div",{className:"min-h-[560px] px-5 py-5",children:r?e.jsx(mn,{variant:"detail"}):s?l&&s.editable?s.markdown?e.jsx(ps,{value:u,onChange:p,bordered:!1,className:"min-h-[520px]"}):e.jsx(Ur,{value:u,onChange:k=>p(k.target.value),className:"min-h-[520px] rounded-none border-0 bg-transparent px-0 py-0 font-mono text-sm shadow-none focus-visible:ring-0"}):s.markdown&&i==="preview"?e.jsx(Xs,{children:S}):e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground",children:e.jsx("code",{children:s.content})}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Select a file to inspect."})})]})}function lK(){var fe,Ce;const{"*":t}=Xn(),n=Sn(),s=at(),{selectedCompanyId:r}=et(),{setBreadcrumbs:a}=Ft(),{pushToast:o}=ds(),[i,l]=c.useState(""),[u,d]=c.useState(""),[m,p]=c.useState(!1),[x,f]=c.useState(!1),[h,j]=c.useState(null),[b,g]=c.useState({}),[y,v]=c.useState("preview"),[_,E]=c.useState(!1),[S,M]=c.useState(""),[B,k]=c.useState(null),[L,$]=c.useState(null),[C,I]=c.useState(null),K=c.useMemo(()=>sK(t),[t]),T=K.skillId,z=K.filePath;c.useEffect(()=>{a([{label:"Skills",href:"/skills"},...T?[{label:"Detail"}]:[]])},[T,a]);const w=oe({queryKey:N.companySkills.list(r??""),queryFn:()=>nr.list(r),enabled:!!r}),F=c.useMemo(()=>{var le,Re;return T||(((Re=(le=w.data)==null?void 0:le[0])==null?void 0:Re.id)??null)},[T,w.data]);c.useEffect(()=>{T||!F||n(Uo(F),{replace:!0})},[n,T,F]);const A=oe({queryKey:N.companySkills.detail(r??"",F??""),queryFn:()=>nr.detail(r,F),enabled:!!(r&&F)}),R=oe({queryKey:N.companySkills.file(r??"",F??"",z),queryFn:()=>nr.file(r,F,z),enabled:!!(r&&F&&z)}),Q=oe({queryKey:N.companySkills.updateStatus(r??"",F??""),queryFn:()=>nr.updateStatus(r,F),enabled:!!(r&&F&&(((fe=A.data)==null?void 0:fe.sourceType)==="github"||(B==null?void 0:B.sourceType)==="github")),staleTime:6e4});c.useEffect(()=>{j(F)},[F]),c.useEffect(()=>{if(!F||z==="SKILL.md")return;const le=rK(z);le.length!==0&&g(Re=>{const Pe=new Set(Re[F]??[]);let Fe=!1;for(const pe of le)Pe.has(pe)||(Pe.add(pe),Fe=!0);return Fe?{...Re,[F]:Pe}:Re})},[z,F]),c.useEffect(()=>{E(!1)},[F,z]),c.useEffect(()=>{A.data&&k(A.data)},[A.data]),c.useEffect(()=>{R.data&&($(R.data),M(R.data.markdown?pp(R.data.content).body:R.data.content))},[R.data]),c.useEffect(()=>{F||(k(null),$(null))},[F]);const H=A.data??B,U=R.data??L,Z=ge({mutationFn:le=>nr.importFromSource(r,le),onSuccess:async le=>{await s.invalidateQueries({queryKey:N.companySkills.list(r)}),le.imported[0]&&n(Uo(le.imported[0].id)),o({tone:"success",title:"Skills imported",body:`${le.imported.length} skill${le.imported.length===1?"":"s"} added.`}),le.warnings[0]&&o({tone:"warn",title:"Import warnings",body:le.warnings[0]}),d("")},onError:le=>{o({tone:"error",title:"Skill import failed",body:le instanceof Error?le.message:"Failed to import skill source."})}}),V=ge({mutationFn:le=>nr.create(r,le),onSuccess:async le=>{await s.invalidateQueries({queryKey:N.companySkills.list(r)}),n(Uo(le.id)),p(!1),o({tone:"success",title:"Skill created",body:`${le.name} is now editable in the CrewSpace workspace.`})},onError:le=>{o({tone:"error",title:"Skill creation failed",body:le instanceof Error?le.message:"Failed to create skill."})}}),W=ge({mutationFn:()=>nr.scanProjects(r),onMutate:()=>{I("Scanning project workspaces for skills...")},onSuccess:async le=>{I("Refreshing skills list..."),await s.invalidateQueries({queryKey:N.companySkills.list(r)});const Re=XB(le);I(Re),o({tone:"success",title:"Project skill scan complete",body:Re}),le.conflicts[0]?o({tone:"warn",title:"Skill conflicts found",body:le.conflicts[0].reason}):le.warnings[0]&&o({tone:"warn",title:"Scan warnings",body:le.warnings[0]})},onError:le=>{I(null),o({tone:"error",title:"Project skill scan failed",body:le instanceof Error?le.message:"Failed to scan project workspaces."})}}),J=ge({mutationFn:()=>nr.updateFile(r,F,z,U!=null&&U.markdown?ZB(U.content,S):S),onSuccess:async le=>{await Promise.all([s.invalidateQueries({queryKey:N.companySkills.list(r)}),s.invalidateQueries({queryKey:N.companySkills.detail(r,F)}),s.invalidateQueries({queryKey:N.companySkills.file(r,F,z)})]),M(le.markdown?pp(le.content).body:le.content),E(!1),o({tone:"success",title:"Skill saved",body:le.path})},onError:le=>{o({tone:"error",title:"Save failed",body:le instanceof Error?le.message:"Failed to save skill file."})}}),Y=ge({mutationFn:()=>nr.installUpdate(r,F),onSuccess:async le=>{await Promise.all([s.invalidateQueries({queryKey:N.companySkills.list(r)}),s.invalidateQueries({queryKey:N.companySkills.detail(r,F)}),s.invalidateQueries({queryKey:N.companySkills.updateStatus(r,F)}),s.invalidateQueries({queryKey:N.companySkills.file(r,F,z)})]),n(Uo(le.id,z)),o({tone:"success",title:"Skill updated",body:le.sourceRef?`Pinned to ${xp(le.sourceRef)}`:le.name})},onError:le=>{o({tone:"error",title:"Update failed",body:le instanceof Error?le.message:"Failed to install skill update."})}});if(!r)return e.jsx(tn,{icon:Cd,message:"Select a company to manage skills."});function de(){const le=u.trim();if(le.length===0){f(!0);return}Z.mutate(le)}return e.jsxs(e.Fragment,{children:[e.jsx(Cs,{open:x,onOpenChange:f,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(fa,{children:[e.jsx(ha,{children:"Add a skill source"}),e.jsx(ga,{children:"Paste a local path, GitHub URL, or `skills.sh` command into the field first."})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",className:"flex items-start justify-between rounded-md border border-border px-3 py-3 text-foreground no-underline transition-colors hover:bg-accent/40",children:[e.jsxs("span",{children:[e.jsx("span",{className:"block font-medium",children:"Browse skills.sh"}),e.jsx("span",{className:"mt-1 block text-muted-foreground",children:"Find install commands and paste one here."})]}),e.jsx(Is,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"})]}),e.jsxs("a",{href:"https://github.com/search?q=SKILL.md&type=code",target:"_blank",rel:"noreferrer",className:"flex items-start justify-between rounded-md border border-border px-3 py-3 text-foreground no-underline transition-colors hover:bg-accent/40",children:[e.jsxs("span",{children:[e.jsx("span",{className:"block font-medium",children:"Search GitHub"}),e.jsx("span",{className:"mt-1 block text-muted-foreground",children:"Look for repositories with `SKILL.md`, then paste the repo URL here."})]}),e.jsx(Is,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"})]})]}),e.jsx(Ho,{showCloseButton:!0})]})}),e.jsxs("div",{className:"grid min-h-[calc(100vh-12rem)] gap-0 xl:grid-cols-[19rem_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"border-r border-border",children:[e.jsxs("div",{className:"border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-base font-semibold",children:"Skills"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[((Ce=w.data)==null?void 0:Ce.length)??0," available"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon-sm",onClick:()=>W.mutate(),disabled:W.isPending,title:"Scan project workspaces for skills",children:e.jsx(Za,{className:O("h-4 w-4",W.isPending&&"animate-spin")})}),e.jsx(G,{variant:"ghost",size:"icon-sm",onClick:()=>p(le=>!le),children:e.jsx(Ot,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-b border-border pb-2",children:[e.jsx(ws,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{value:i,onChange:le=>l(le.target.value),placeholder:"Filter skills",className:"w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-b border-border pb-2",children:[e.jsx("input",{value:u,onChange:le=>d(le.target.value),placeholder:"Paste path, GitHub URL, or skills.sh command",className:"w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:de,disabled:Z.isPending,children:Z.isPending?e.jsx(Za,{className:"h-4 w-4 animate-spin"}):"Add"})]}),C&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:C})]}),m&&e.jsx(aK,{onCreate:le=>V.mutate(le),isPending:V.isPending,onCancel:()=>p(!1)}),w.isLoading?e.jsx(mn,{variant:"list"}):w.error?e.jsx("div",{className:"px-4 py-6 text-sm text-destructive",children:w.error.message}):e.jsx(oK,{skills:w.data??[],selectedSkillId:F,skillFilter:i,expandedSkillId:h,expandedDirs:b,selectedPaths:F?{[F]:z}:{},onToggleSkill:le=>j(Re=>Re===le?null:le),onToggleDir:(le,Re)=>{g(Pe=>{const Fe=new Set(Pe[le]??[]);return Fe.has(Re)?Fe.delete(Re):Fe.add(Re),{...Pe,[le]:Fe}})},onSelectSkill:le=>j(le),onSelectPath:()=>{}})]}),e.jsx("div",{className:"min-w-0 pl-6",children:e.jsx(iK,{loading:w.isLoading||A.isLoading,detail:H,file:U,fileLoading:R.isLoading&&!U,updateStatus:Q.data,updateStatusLoading:Q.isLoading,viewMode:y,editMode:_,draft:S,setViewMode:v,setEditMode:E,setDraft:M,onCheckUpdates:()=>{Q.refetch()},checkUpdatesPending:Q.isFetching,onInstallUpdate:()=>Y.mutate(),installUpdatePending:Y.isPending,onSave:()=>J.mutate(),savePending:J.isPending})})]})]})}const MN=new TextEncoder,$N=new TextDecoder,DN=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let s=0;s<8;s++)n=(n&1)===1?n>>>1^3988292384:n>>>1;DN[t]=n>>>0}function vl(t){return t.replace(/\\/g,"/").split("/").filter(Boolean).join("/")}function cK(t){let n=4294967295;for(const s of t)n=n>>>8^DN[(n^s)&255];return(n^4294967295)>>>0}function vn(t,n,s){t[n]=s&255,t[n+1]=s>>>8&255}function Ps(t,n,s){t[n]=s&255,t[n+1]=s>>>8&255,t[n+2]=s>>>16&255,t[n+3]=s>>>24&255}function uc(t,n){return t[n]|t[n+1]<<8}function cb(t,n){return(t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24)>>>0}function dK(t){const n=Math.min(Math.max(t.getFullYear(),1980),2107),s=t.getMonth()+1,r=t.getDate(),a=t.getHours(),o=t.getMinutes(),i=Math.floor(t.getSeconds()/2);return{time:a<<11|o<<5|i,date:n-1980<<9|s<<5|r}}function db(t){const n=t.reduce((a,o)=>a+o.length,0),s=new Uint8Array(n);let r=0;for(const a of t)s.set(a,r),r+=a.length;return s}function uK(t){if(t.length===0)return null;const n=t.map(r=>vl(r).split("/").filter(Boolean)).filter(r=>r.length>0);if(n.length===0)return null;const s=n[0][0];return n.every(r=>r.length>1&&r[0]===s)?s:null}const mK={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp"};function pK(t){const n=vl(t),s=n.lastIndexOf(".");return s===-1?null:mK[n.slice(s).toLowerCase()]??null}function xK(t){let n="";for(const s of t)n+=String.fromCharCode(s);return btoa(n)}function fK(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r<n.length;r+=1)s[r]=n.charCodeAt(r);return s}function hK(t,n){const s=pK(t);return s?{encoding:"base64",data:xK(n),contentType:s}:$N.decode(n)}function gK(t){return typeof t=="string"?MN.encode(t):fK(t.data)}async function bK(t,n){if(t===0)return n;if(t!==8)throw new Error("Unsupported zip archive: only STORE and DEFLATE entries are supported.");if(typeof DecompressionStream!="function")throw new Error("Unsupported zip archive: this browser cannot read compressed zip entries.");const s=new Uint8Array(n.byteLength);s.set(n);const r=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(r).arrayBuffer())}async function yK(t){const n=t instanceof Uint8Array?t:new Uint8Array(t),s=[];let r=0;for(;r+4<=n.length;){const i=cb(n,r);if(i===33639248||i===101010256)break;if(i!==67324752)throw new Error("Invalid zip archive: unsupported local file header.");if(r+30>n.length)throw new Error("Invalid zip archive: truncated local file header.");const l=uc(n,r+6),u=uc(n,r+8),d=cb(n,r+18),m=uc(n,r+26),p=uc(n,r+28);if((l&8)!==0)throw new Error("Unsupported zip archive: data descriptors are not supported.");const x=r+30,f=x+m+p,h=f+d;if(h>n.length)throw new Error("Invalid zip archive: truncated file contents.");const j=$N.decode(n.slice(x,x+m)),b=vl(j),g=/\/$/.test(j.replace(/\\/g,"/"));if(b&&!g){const y=await bK(u,n.slice(f,h));s.push({path:b,body:hK(b,y)})}r=h}const a=uK(s.map(i=>i.path)),o={};for(const i of s){const l=a&&i.path.startsWith(`${a}/`)?i.path.slice(a.length+1):i.path;l&&(o[l]=i.body)}return{rootPath:a,files:o}}function vK(t,n){const s=vl(n),r=[],a=[],o=dK(new Date);let i=0,l=0;for(const[m,p]of Object.entries(t).sort(([x],[f])=>x.localeCompare(f))){const x=vl(`${s}/${m}`),f=MN.encode(x),h=gK(p),j=cK(h),b=new Uint8Array(30+f.length);Ps(b,0,67324752),vn(b,4,20),vn(b,6,2048),vn(b,8,0),vn(b,10,o.time),vn(b,12,o.date),Ps(b,14,j),Ps(b,18,h.length),Ps(b,22,h.length),vn(b,26,f.length),vn(b,28,0),b.set(f,30);const g=new Uint8Array(46+f.length);Ps(g,0,33639248),vn(g,4,20),vn(g,6,20),vn(g,8,2048),vn(g,10,0),vn(g,12,o.time),vn(g,14,o.date),Ps(g,16,j),Ps(g,20,h.length),Ps(g,24,h.length),vn(g,28,f.length),vn(g,30,0),vn(g,32,0),vn(g,34,0),vn(g,36,0),Ps(g,38,0),Ps(g,42,i),g.set(f,46),r.push(b,h),a.push(g),i+=b.length+h.length,l+=1}const u=db(a),d=new Uint8Array(22);return Ps(d,0,101010256),vn(d,4,0),vn(d,6,0),vn(d,8,l),vn(d,10,l),Ps(d,12,u.length),Ps(d,16,i),vn(d,20,0),db([...r,u,d])}function jK(t){return/(?:^|\/)tasks\//.test(t)}function wK(t){const n=new Set;for(const s of t){if(!s.recurring)continue;const r=s.path.trim();if(!r)continue;n.add(r);const a=r.lastIndexOf("/");a>=0&&n.add(`${r.slice(0,a+1)}`)}return n}function NK(t,n){for(const s of n)if(t===s||t.startsWith(s))return!0;return!1}function kK(t,n,s){const r=new Set,a=wK(n);for(const o of t){if(s.has(o)){r.add(o);continue}(!jK(o)||NK(o,a))&&r.add(o)}return r}function ON(t,n){if(!n.has(t))return n.add(t),t;let s=2;for(;;){const r=`${t}-${s}`;if(!n.has(r))return n.add(r),r;s+=1}}function CK(t){const n=new Set,s=new Map,r=[...t].sort((a,o)=>a.name.localeCompare(o.name));for(const a of r){const o=dl(a.name)??"agent";s.set(a.id,ON(o,n))}return s}function SK(t){const n=new Set,s=new Map,r=[...t].sort((a,o)=>a.name.localeCompare(o.name));for(const a of r){const o=mx(a.name,a.name);s.set(a.id,ON(o,n))}return s}function IK(t){const n=CK(t.agents),s=SK(t.projects),r={agents:t.orderedAgents.map(a=>n.get(a.id)).filter(a=>!!a),projects:t.orderedProjects.map(a=>s.get(a.id)).filter(a=>!!a)};return r.agents.length>0||r.projects.length>0?r:void 0}const _K={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp"};function LN(t){return typeof t=="string"?t:null}function FN(t,n){if(n&&typeof n=="object"&&n.contentType)return n.contentType;const s=t.toLowerCase().lastIndexOf(".");return s===-1?null:_K[t.toLowerCase().slice(s)]??null}function xd(t,n){return!n||typeof n=="string"?null:`data:${FN(t,n)??"application/octet-stream"};base64,${n.data}`}function qN(t,n){const s=FN(t,n);return typeof s=="string"&&s.startsWith("image/")}function UN(t){const n=new Set,s=new Set,r=new Set;for(const a of t){const o=a.match(/^agents\/([^/]+)\//);o&&n.add(o[1]);const i=a.match(/^projects\/([^/]+)\//);i&&s.add(i[1]);const l=a.match(/^tasks\/([^/]+)\//);l&&r.add(l[1])}return{agents:n,projects:s,tasks:r,routines:new Set(r)}}function AK(t,n){const s=UN(n),r=t.split(`
|
|
176
|
+
`),a=[],o=new Set(["agents","projects","tasks","routines"]),i=new Set(["agents","projects"]);let l=null,u=null,d=!0,m=null,p=null,x=[],f=null,h=[];function j(){p!==null&&x.length>0&&(h.push(p),h.push(...x)),p=null,x=[]}function b(){j(),f!==null&&h.length>0&&(a.push(f),a.push(...h)),f=null,h=[]}for(const v of r){const _=v.match(/^([a-zA-Z_][\w-]*):\s*(.*)$/);if(_&&!v.startsWith(" ")){b(),u=null,d=!0;const E=_[0].split(":")[0];if(o.has(E)){l=E,f=v;continue}else if(E==="sidebar"){l=E,m=null,f=v;continue}else{l=null,a.push(v);continue}}if(l==="sidebar"){const E=v.match(/^ ([\w-]+):\s*$/);if(E&&!v.startsWith(" ")){j();const M=E[1];m=M&&i.has(M)?M:null,p=m?v:null;continue}const S=v.match(/^ - ["']?([^"'\n]+)["']?\s*$/);if(S&&m){const M=S[1],B=s[m];M&&B.has(M)&&x.push(v);continue}if(m){x.push(v);continue}}if(l&&o.has(l)){const E=v.match(/^ ([\w][\w-]*):\s*(.*)$/);if(E&&!v.startsWith(" ")){const S=E[1];u=S,d=s[l].has(S),d&&h.push(v);continue}if(u!==null){d&&h.push(v);continue}h.push(v);continue}a.push(v)}b();let g=a.join(`
|
|
177
|
+
`);const y=g.match(/^\s{2}logoPath:\s*["']?([^"'\n]+)["']?\s*$/m);return y&&!n.has(y[1])&&(g=g.replace(/^\s{2}logoPath:\s*["']?([^"'\n]+)["']?\s*\n?/m,"")),g}function BN(t,n){if(!n)return t;const s=n.toLowerCase();return t.map(r=>{if(r.kind==="file")return r.name.toLowerCase().includes(s)||r.path.toLowerCase().includes(s)?r:null;const a=BN(r.children,n);return a.length>0?{...r,children:a}:null}).filter(r=>r!==null)}function EK(t,n){const s=new Set,r=n.toLowerCase();function a(o,i){if(o.kind==="file"){if(o.name.toLowerCase().includes(r)||o.path.toLowerCase().includes(r))for(const l of i)s.add(l)}else for(const l of o.children)a(l,[...i,o.path])}for(const o of t)a(o,[]);return s}function KN(t,n){return t.map(s=>s.kind==="dir"?{...s,children:KN(s.children,n)}:s).sort((s,r)=>{if(s.kind!==r.kind)return s.kind==="file"?-1:1;if(s.kind==="file"&&r.kind==="file"){const a=n.has(s.path),o=n.has(r.path);if(a!==o)return a?-1:1}return s.name.localeCompare(r.name)})}const ub=10;function TK(t,n,s,r){let a=0,o=0;return{nodes:t.map(l=>{if(l.kind==="dir"&&l.name==="tasks"){a=l.children.length;const u=[],d=[],m=r.toLowerCase();for(const f of l.children){const h=ql([f],"file"),j=[...h].some(g=>s.has(g)),b=r&&(f.name.toLowerCase().includes(m)||f.path.toLowerCase().includes(m)||[...h].some(g=>g.toLowerCase().includes(m)));j||b?u.push(f):d.push(f)}const p=Math.max(0,n-u.length),x=[...u,...d.slice(0,p)];return o=x.length,{...l,children:x}}return l}),totalTaskChildren:a,visibleTaskChildren:o}}function RK(t,n,s){const r={};for(const[d]of Object.entries(t.files))n.has(d)&&(r[d]=s[d]??t.files[d]);const a=vK(r,t.rootPath),o=new ArrayBuffer(a.byteLength);new Uint8Array(o).set(a);const i=new Blob([o],{type:"application/zip"}),l=URL.createObjectURL(i),u=document.createElement("a");u.href=l,u.download=`${t.rootPath}.zip`,document.body.appendChild(u),u.click(),u.remove(),window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}function PK({data:t,onSkillClick:n}){return e.jsx("div",{className:"rounded-md border border-border bg-accent/20 px-4 py-3 mb-4",children:e.jsx("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-sm",children:Object.entries(t).map(([s,r])=>e.jsxs("div",{className:"contents",children:[e.jsx("dt",{className:"text-muted-foreground whitespace-nowrap py-0.5",children:Xw[s]??s}),e.jsx("dd",{className:"py-0.5",children:Array.isArray(r)?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(a=>e.jsx("button",{type:"button",className:O("inline-flex items-center rounded-md border border-border bg-background px-2 py-0.5 text-xs",s==="skills"&&n&&"cursor-pointer hover:bg-accent/50 hover:border-foreground/30 transition-colors"),onClick:()=>s==="skills"&&(n==null?void 0:n(a)),children:a},a))}):e.jsx("span",{children:r})})]},s))})})}const MK={ceo:"CEO",cto:"CTO",cmo:"CMO",cfo:"CFO",coo:"COO",vp:"VP",manager:"Manager",engineer:"Engineer",agent:"Agent"};function $K(t,n,s,r){const a=UN(n),o=t.agents.filter(p=>a.agents.has(p.slug)),i=t.projects.filter(p=>a.projects.has(p.slug)),l=t.issues.filter(p=>a.tasks.has(p.slug)),u=t.skills.filter(p=>[...n].some(x=>x.startsWith(`skills/${p.key}/`)||x.startsWith("skills/")&&x.includes(`/${p.slug}/`))),d=[];d.push(`# ${s}`),d.push(""),r&&(d.push(`> ${r}`),d.push("")),o.length>0&&(d.push(""),d.push("")),d.push("## What's Inside"),d.push(""),d.push("This is an [Agent Company](https://crewspace.ing) package."),d.push("");const m=[];if(o.length>0&&m.push(["Agents",o.length]),i.length>0&&m.push(["Projects",i.length]),u.length>0&&m.push(["Skills",u.length]),l.length>0&&m.push(["Tasks",l.length]),m.length>0){d.push("| Content | Count |"),d.push("|---------|-------|");for(const[p,x]of m)d.push(`| ${p} | ${x} |`);d.push("")}if(o.length>0){d.push("### Agents"),d.push(""),d.push("| Agent | Role | Reports To |"),d.push("|-------|------|------------|");for(const p of o){const x=MK[p.role]??p.role,f=p.reportsToSlug??"—";d.push(`| ${p.name} | ${x} | ${f} |`)}d.push("")}if(i.length>0){d.push("### Projects"),d.push("");for(const p of i){const x=p.description?` — ${p.description}`:"";d.push(`- **${p.name}**${x}`)}d.push("")}return d.push("## Getting Started"),d.push(""),d.push("```bash"),d.push("pnpm crewspaceai company import this-github-url-or-folder"),d.push("```"),d.push(""),d.push("See [CrewSpace](https://crewspace.ing) for more information."),d.push(""),d.push("---"),d.push(`Exported from [CrewSpace](https://crewspace.ing) on ${new Date().toISOString().split("T")[0]}`),d.push(""),d.join(`
|
|
178
|
+
`)}function DK({selectedFile:t,content:n,allFiles:s,onSkillClick:r}){if(!t||n===null)return e.jsx(tn,{icon:el,message:"Select a file to preview its contents."});const a=LN(n),o=t.endsWith(".md")&&a!==null,i=o&&a?Yw(a):null,l=qN(t,n)?xd(t,n):null,u=o?d=>{if(/^(?:https?:|data:)/i.test(d))return null;const p=(t.includes("/")?t.slice(0,t.lastIndexOf("/")+1):"")+d,x=s[p]??s[d];return x?xd(p in s?p:d,x):null}:void 0;return e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"border-b border-border px-5 py-3",children:e.jsx("div",{className:"truncate font-mono text-sm",children:t})}),e.jsx("div",{className:"min-h-[560px] px-5 py-5",children:i?e.jsxs(e.Fragment,{children:[e.jsx(PK,{data:i.data,onSkillClick:r}),i.body.trim()&&e.jsx(Xs,{resolveImageSrc:u,children:i.body})]}):o?e.jsx(Xs,{resolveImageSrc:u,children:a??""}):l?e.jsx("div",{className:"flex min-h-[520px] items-center justify-center rounded-lg border border-border bg-accent/10 p-6",children:e.jsx("img",{src:l,alt:t,className:"max-h-[480px] max-w-full object-contain"})}):a!==null?e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground",children:e.jsx("code",{children:a})}):e.jsx("div",{className:"rounded-lg border border-border bg-accent/10 px-4 py-3 text-sm text-muted-foreground",children:"Binary asset preview is not available for this file type."})})]})}function mb(t){const n="/company/export/files/",s=t.indexOf(n);return s===-1?null:decodeURIComponent(t.slice(s+n.length))||null}function pb(t){const n=t.split("/").slice(0,-1),s=[];let r="";for(const a of n)r=r?`${r}/${a}`:a,s.push(r);return s}function OK(){var Pe,Fe;const{selectedCompanyId:t,selectedCompany:n}=et(),{setBreadcrumbs:s}=Ft(),{pushToast:r}=ds(),a=Sn(),o=fn(),{data:i,isFetched:l}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),{data:u=[],isFetched:d}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),{data:m=[],isFetched:p}=oe({queryKey:N.projects.list(t),queryFn:()=>en.list(t),enabled:!!t}),[x,f]=c.useState(null),[h,j]=c.useState(null),[b,g]=c.useState(new Set),[y,v]=c.useState(new Set),[_,E]=c.useState(""),[S,M]=c.useState(ub),B=c.useRef(null),k=c.useRef(mb(o.pathname)),L=((Pe=i==null?void 0:i.user)==null?void 0:Pe.id)??((Fe=i==null?void 0:i.session)==null?void 0:Fe.userId)??null,$=c.useMemo(()=>u.filter(pe=>pe.status!=="terminated"),[u]),C=c.useMemo(()=>m.filter(pe=>!pe.archivedAt),[m]),{orderedAgents:I}=Xj({agents:$,companyId:t,userId:L}),{orderedProjects:K}=$l({projects:C,companyId:t,userId:L}),T=c.useMemo(()=>IK({agents:$,orderedAgents:I,projects:C,orderedProjects:K}),[I,K,$,C]),z=c.useMemo(()=>JSON.stringify(T??null),[T]),w=c.useCallback((pe,Le=!1)=>{j(pe),pe?a(`/company/export/files/${encodeURI(pe)}`,{replace:Le}):a("/company/export",{replace:Le})},[a]);c.useEffect(()=>{if(!x)return;const pe=mb(o.pathname);pe&&pe in x.files&&pe!==h?(j(pe),g(Le=>{const q=new Set(Le);for(const D of pb(pe))q.add(D);return q})):!pe&&h&&j(null)},[o.pathname,x]),c.useEffect(()=>{s([{label:"Org Chart",href:"/org"},{label:"Export"}])},[s]);const F=ge({mutationFn:()=>ls.exportPreview(t,{include:{company:!0,agents:!0,projects:!0,issues:!0},sidebarOrder:T}),onSuccess:pe=>{f(pe),v(ie=>kK(Object.keys(pe.files),pe.manifest.issues,ie));const Le=Go(pe.files),q=new Set;for(const ie of Le)ie.kind==="dir"&&ie.name!=="tasks"&&q.add(ie.path);const D=k.current;if(D&&D in pe.files){j(D);const ie=pb(D);g(new Set([...q,...ie]))}else{const ie="README.md"in pe.files?"README.md":Object.keys(pe.files)[0];ie&&w(ie,!0),g(q)}},onError:pe=>{r({tone:"error",title:"Export failed",body:pe instanceof Error?pe.message:"Failed to load export data."})}}),A=ge({mutationFn:()=>ls.exportPackage(t,{include:{company:!0,agents:!0,projects:!0,issues:!0},selectedFiles:Array.from(y).sort(),sidebarOrder:T}),onSuccess:pe=>{const Le=new Set(Object.keys(pe.files));RK(pe,Le,pe.files),r({tone:"success",title:"Export downloaded",body:`${Le.size} file${Le.size===1?"":"s"} exported as ${pe.rootPath}.zip`})},onError:pe=>{r({tone:"error",title:"Export failed",body:pe instanceof Error?pe.message:"Failed to build export package."})}});c.useEffect(()=>{!t||F.isPending||!l||!d||!p||(f(null),F.mutate())},[t,l,d,p,z]);const R=c.useMemo(()=>x?Go(x.files):[],[x]),{displayTree:Q,totalTaskChildren:H,visibleTaskChildren:U}=c.useMemo(()=>{let pe=R;_&&(pe=BN(pe,_)),pe=KN(pe,y);const Le=TK(pe,S,y,_);return{displayTree:Le.nodes,totalTaskChildren:Le.totalTaskChildren,visibleTaskChildren:Le.visibleTaskChildren}},[R,_,y,S]),Z=c.useMemo(()=>{var q,D;if(!x)return{};const pe={...x.files},Le=x.crewspaceExtensionPath;if(Le&&typeof x.files[Le]=="string"&&(pe[Le]=AK(x.files[Le],y)),typeof x.files["README.md"]=="string"){const ie=((q=x.manifest.company)==null?void 0:q.name)??(n==null?void 0:n.name)??"Company",Ie=((D=x.manifest.company)==null?void 0:D.description)??null;pe["README.md"]=$K(x.manifest,y,ie,Ie)}return pe},[x,y,n==null?void 0:n.name]),V=c.useMemo(()=>af(R),[R]),W=y.size,J=c.useMemo(()=>x?x.warnings.filter(pe=>!/terminated agent/i.test(pe)):[],[x]);function Y(pe){g(Le=>{const q=new Set(Le);return q.has(pe)?q.delete(pe):q.add(pe),q})}function de(pe,Le){x&&v(q=>{const D=new Set(q);if(Le==="file")D.has(pe)?D.delete(pe):D.add(pe);else{const ie=Go(x.files),Ie=(Be,be)=>{for(const he of Be){if(he.path===be)return he;const Se=Ie(he.children,be);if(Se)return Se}return null},ue=Ie(ie,pe);if(ue){const Be=ql(ue.children,"file");for(const he of ue.children)he.kind==="file"&&Be.add(he.path);const be=[...Be].every(he=>D.has(he));for(const he of Be)be?D.delete(he):D.add(he)}}return D})}function fe(pe){const Le=_.length>0,q=pe.length>0;if(q&&!Le&&(B.current=new Set(b)),E(pe),q){const D=EK(R,pe);g(ie=>{const Ie=new Set(ie);for(const ue of D)Ie.add(ue);return Ie})}else Le&&B.current&&(g(B.current),B.current=null)}function Ce(pe){if(!x)return;const Le=x.manifest.skills.find(D=>D.key===pe||D.slug===pe),q=(Le==null?void 0:Le.path)??`skills/${pe}/SKILL.md`;q in x.files&&(w(q),g(D=>{const ie=new Set(D);ie.add("skills");const Ie=q.split("/").slice(0,-1);let ue="";for(const Be of Ie)ue=ue?`${ue}/${Be}`:Be,ie.add(ue);return ie}))}function le(){!x||y.size===0||A.isPending||A.mutate()}if(!t)return e.jsx(tn,{icon:el,message:"Select a company to export."});if(F.isPending&&!x)return e.jsx(mn,{variant:"detail"});if(!x)return e.jsx(tn,{icon:el,message:"Loading export data..."});const Re=h?Z[h]??null:null;return e.jsxs("div",{children:[e.jsx("div",{className:"sticky top-0 z-10 border-b border-border bg-background px-5 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"font-medium",children:[(n==null?void 0:n.name)??"Company"," export"]}),e.jsxs("span",{className:"text-muted-foreground",children:[W," / ",V," file",V===1?"":"s"," selected"]}),J.length>0&&e.jsxs("span",{className:"text-amber-500",children:[J.length," warning",J.length===1?"":"s"]})]}),e.jsxs(G,{size:"sm",onClick:le,disabled:W===0||A.isPending,children:[e.jsx(ei,{className:"mr-1.5 h-3.5 w-3.5"}),A.isPending?"Building export...":`Export ${W} file${W===1?"":"s"}`]})]})}),J.length>0&&e.jsx("div",{className:"mx-5 mt-3 rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:J.map(pe=>e.jsx("div",{className:"text-xs text-amber-500",children:pe},pe))}),e.jsxs("div",{className:"grid h-[calc(100vh-12rem)] gap-0 xl:grid-cols-[19rem_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex flex-col border-r border-border overflow-hidden",children:[e.jsx("div",{className:"border-b border-border px-4 py-3 shrink-0",children:e.jsx("h2",{className:"text-base font-semibold",children:"Package files"})}),e.jsx("div",{className:"border-b border-border px-3 py-2 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-2 py-1",children:[e.jsx(ws,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx("input",{type:"text",value:_,onChange:pe=>fe(pe.target.value),placeholder:"Search files...",className:"w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsx(ou,{nodes:Q,selectedFile:h,expandedDirs:b,checkedFiles:y,onToggleDir:Y,onSelectFile:w,onToggleCheck:de}),H>U&&!_&&e.jsx("div",{className:"px-4 py-2",children:e.jsxs("button",{type:"button",onClick:()=>M(pe=>pe+ub),className:"w-full rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent/30 hover:text-foreground transition-colors",children:["Show more issues (",U," of ",H,")"]})})]})]}),e.jsx("div",{className:"min-w-0 overflow-y-auto pl-6",children:e.jsx(DK,{selectedFile:h,content:Re,allFiles:Z,onSkillClick:Ce})})]})]})}function xb(t){const n=new Map,s=t.manifest;for(const r of t.plan.agentPlans){const a=s.agents.find(o=>o.slug===r.slug);if(a){const o=ca(a.path);n.set(o,r.action)}}for(const r of t.plan.projectPlans){const a=s.projects.find(o=>o.slug===r.slug);if(a){const o=ca(a.path);n.set(o,r.action)}}for(const r of t.plan.issuePlans){const a=s.issues.find(o=>o.slug===r.slug);if(a){const o=ca(a.path);n.set(o,r.action)}}for(const r of s.skills){const a=ca(r.path);n.set(a,"create");for(const o of r.fileInventory)t.files[o.path]&&n.set(o.path,"create")}if(s.company){const r=ca(s.company.path);n.set(r,t.plan.companyAction==="none"?"skip":t.plan.companyAction)}return n}function ca(t){return t.endsWith(".md")?t:`${t}.md`}const fd={create:"text-emerald-500 border-emerald-500/30",update:"text-amber-500 border-amber-500/30",overwrite:"text-red-500 border-red-500/30",replace:"text-red-500 border-red-500/30",skip:"text-muted-foreground border-border",none:"text-muted-foreground border-border"};function LK({data:t}){return e.jsx("div",{className:"rounded-md border border-border bg-accent/20 px-4 py-3 mb-4",children:e.jsx("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-sm",children:Object.entries(t).map(([n,s])=>e.jsxs("div",{className:"contents",children:[e.jsx("dt",{className:"text-muted-foreground whitespace-nowrap py-0.5",children:Xw[n]??n}),e.jsx("dd",{className:"py-0.5",children:Array.isArray(s)?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(r=>e.jsx("span",{className:"inline-flex items-center rounded-md border border-border bg-background px-2 py-0.5 text-xs",children:r},r))}):e.jsx("span",{children:s})})]},n))})})}function FK(t,n,s){const r=t.kind==="dir"?s.get(t.path):void 0,a=t.action?e.jsx("span",{className:O("shrink-0 rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-wide",fd[t.action]??fd.skip),children:n?t.action:"skip"}):null;return!a&&!r?null:e.jsxs("span",{className:"inline-flex items-center gap-1.5 shrink-0",children:[r&&n&&e.jsxs("span",{className:"text-[10px] text-cyan-500 font-mono truncate max-w-[7rem]",title:r,children:["→ ",r]}),a]})}function qK(t,n){return n?void 0:"opacity-50"}function UK({selectedFile:t,content:n,allFiles:s,action:r,renamedTo:a}){if(!t||n===null)return e.jsx(tn,{icon:el,message:"Select a file to preview its contents."});const o=LN(n),i=t.endsWith(".md")&&o!==null,l=i&&o?Yw(o):null,u=qN(t,n)?xd(t,n):null,d=r?fd[r]??fd.skip:"",m=i?p=>{if(/^(?:https?:|data:)/i.test(p))return null;const f=(t.includes("/")?t.slice(0,t.lastIndexOf("/")+1):"")+p,h=s[f]??s[p];return h?xd(f in s?f:p,h):null}:void 0;return e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"border-b border-border px-5 py-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-mono text-sm",children:t}),a&&e.jsxs("span",{className:"shrink-0 font-mono text-sm text-cyan-500",children:["→ ",a]})]}),r&&e.jsx("span",{className:O("shrink-0 rounded-full border px-2 py-0.5 text-xs uppercase tracking-wide",d),children:r})]})}),e.jsx("div",{className:"min-h-[560px] px-5 py-5",children:l?e.jsxs(e.Fragment,{children:[e.jsx(LK,{data:l.data}),l.body.trim()&&e.jsx(Xs,{resolveImageSrc:m,children:l.body})]}):i?e.jsx(Xs,{resolveImageSrc:m,children:o??""}):u?e.jsx("div",{className:"flex min-h-[520px] items-center justify-center rounded-lg border border-border bg-accent/10 p-6",children:e.jsx("img",{src:u,alt:t,className:"max-h-[480px] max-w-full object-contain"})}):o!==null?e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground",children:e.jsx("code",{children:o})}):e.jsx("div",{className:"rounded-lg border border-border bg-accent/10 px-4 py-3 text-sm text-muted-foreground",children:"Binary asset preview is not available for this file type."})})]})}function fb(t){const n=[],s=t.manifest;for(const r of t.plan.agentPlans)if(r.existingAgentId){const a=s.agents.find(o=>o.slug===r.slug);n.push({slug:r.slug,kind:"agent",originalName:(a==null?void 0:a.name)??r.slug,plannedName:r.plannedName,filePath:a?ca(a.path):null,action:r.action==="update"?"update":"rename"})}for(const r of t.plan.projectPlans)if(r.existingProjectId){const a=s.projects.find(o=>o.slug===r.slug);n.push({slug:r.slug,kind:"project",originalName:(a==null?void 0:a.name)??r.slug,plannedName:r.plannedName,filePath:a?ca(a.path):null,action:r.action==="update"?"update":"rename"})}return n}function BK(t,n,s,r){if(t==="local")return r?r.split("/").pop()??null:s&&s.replace(/\.zip$/i,"")||null;if(t==="github"){const a=n.trim();if(!a)return null;try{const i=new URL(a.startsWith("http")?a:`https://${a}`).pathname.split("/").filter(Boolean);return i.length>0?i[i.length-1]:null}catch{return null}}return null}function KK(t,n){return t?`${t}-${n}`:n}function zK(t,n,s){const r=t==null?void 0:t.manifest.sidebar;if(!r||!(s!=null&&s.trim()))return;const a=new Map(n.agents.filter(u=>typeof u.id=="string"&&u.id.length>0).map(u=>[u.slug,u.id])),o=new Map(n.projects.filter(u=>typeof u.id=="string"&&u.id.length>0).map(u=>[u.slug,u.id])),i=r.agents.map(u=>a.get(u)).filter(u=>!!u),l=r.projects.map(u=>o.get(u)).filter(u=>!!u);i.length>0&&Yj(Zj(n.company.id,s),i),l.length>0&&Kj(Bj(n.company.id,s),l)}function WK({conflicts:t,nameOverrides:n,skippedSlugs:s,confirmedSlugs:r,onRename:a,onToggleSkip:o,onToggleConfirm:i}){return t.length===0?null:e.jsx("div",{className:"mx-5 mt-3",children:e.jsxs("div",{className:"rounded-md border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-4 py-2.5",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Renames"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," item",t.length===1?"":"s"]})]}),e.jsx("div",{className:"divide-y divide-border",children:t.map(l=>{const u=s.has(l.slug),d=r.has(l.slug),m=n[l.slug]??l.plannedName;return e.jsxs("div",{className:O("flex items-center gap-3 px-4 py-2.5 text-sm",u&&"opacity-40",d&&!u&&"bg-emerald-500/5"),children:[e.jsx("button",{type:"button",className:O("shrink-0 rounded-md border px-2.5 py-1 text-xs transition-colors",u?"border-foreground bg-accent text-foreground":"border-border text-muted-foreground hover:bg-accent/50"),onClick:()=>o(l.slug,l.filePath),children:u?"skipped":"skip"}),e.jsx("span",{className:O("shrink-0 rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-wide",u?"text-muted-foreground border-border":d?"text-emerald-500 border-emerald-500/30":"text-amber-500 border-amber-500/30"),children:l.kind}),e.jsx("span",{className:O("shrink-0 font-mono text-xs",u?"text-muted-foreground line-through":"text-muted-foreground"),children:l.originalName}),!u&&e.jsxs(e.Fragment,{children:[e.jsx(Fo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),d?e.jsx("span",{className:"min-w-0 flex-1 font-mono text-xs text-emerald-500",children:m}):e.jsx("input",{className:"min-w-0 flex-1 rounded-md border border-border bg-transparent px-2 py-1 font-mono text-xs outline-none focus:border-foreground",value:m,onChange:p=>a(l.slug,p.target.value)})]}),!u&&e.jsx("button",{type:"button",className:O("ml-auto shrink-0 rounded-md border px-2.5 py-1 text-xs transition-colors inline-flex items-center gap-1.5",d?"border-emerald-500/30 bg-emerald-500/10 text-emerald-500":"border-border text-muted-foreground hover:bg-accent/50"),onClick:()=>i(l.slug),children:d?e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-3 w-3"}),"confirmed"]}):"confirm rename"})]},l.slug)})})]})})}const HK=$$().map(t=>({value:t.type,label:tu[t.type]??t.label}));function VK({agents:t,adapterOverrides:n,expandedSlugs:s,configValues:r,onChangeAdapter:a,onToggleExpand:o,onChangeConfig:i}){return t.length===0?null:e.jsx("div",{className:"mx-5 mt-3",children:e.jsxs("div",{className:"rounded-md border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-4 py-2.5",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Adapters"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," agent",t.length===1?"":"s"]})]}),e.jsx("div",{className:"divide-y divide-border",children:t.map(l=>{const u=n[l.slug]??l.adapterType,d=s.has(l.slug),m=r[l.slug]??{...io,adapterType:u};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 text-sm",children:[e.jsx("span",{className:O("shrink-0 rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-wide","text-blue-500 border-blue-500/30"),children:"agent"}),e.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:l.name}),e.jsx(Fo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("select",{className:"min-w-0 flex-1 rounded-md border border-border bg-transparent px-2 py-1 text-xs outline-none focus:border-foreground",value:u,onChange:p=>a(l.slug,p.target.value),children:HK.map(p=>e.jsx("option",{value:p.value,children:p.label},p.value))}),e.jsxs("button",{type:"button",className:O("ml-auto shrink-0 rounded-md border px-2.5 py-1 text-xs transition-colors inline-flex items-center gap-1.5",d?"border-foreground bg-accent text-foreground":"border-border text-muted-foreground hover:bg-accent/50"),onClick:()=>o(l.slug),children:[e.jsx(sn,{className:O("h-3 w-3 transition-transform",d&&"rotate-90")}),"configure adapter"]})]}),d&&e.jsx("div",{className:"border-t border-border bg-accent/10 px-4 py-3 space-y-3",children:e.jsx(sf,{mode:"create",values:m,onChange:p=>i(l.slug,p),showAdapterTypeField:!1,showAdapterTestEnvironmentButton:!1,showCreateRunPolicySection:!1,hideInstructionsFile:!0,sectionLayout:"cards"})})]},l.slug)})})]})})}async function QK(t){if(!/\.zip$/i.test(t.name))throw new Error("Select a .zip company package.");const n=await yK(await t.arrayBuffer());if(Object.keys(n.files).length===0)throw new Error("No package files were found in the selected zip archive.");return{name:t.name,rootPath:n.rootPath,files:n.files}}function GK(){var ce,Te;const{selectedCompanyId:t,selectedCompany:n,setSelectedCompanyId:s}=et(),{setBreadcrumbs:r}=Ft(),{pushToast:a}=ds(),o=at(),i=c.useRef(null),{data:l}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),u=((ce=l==null?void 0:l.user)==null?void 0:ce.id)??((Te=l==null?void 0:l.session)==null?void 0:Te.userId)??null,[d,m]=c.useState("github"),[p,x]=c.useState(""),[f,h]=c.useState(null),[j,b]=c.useState("new"),[g,y]=c.useState(""),[v,_]=c.useState(null),[E,S]=c.useState(null),[M,B]=c.useState(new Set),[k,L]=c.useState(new Set),[$,C]=c.useState({}),[I,K]=c.useState(new Set),[T,z]=c.useState(new Set),[w,F]=c.useState("rename"),[A,R]=c.useState({}),[Q,H]=c.useState(new Set),[U,Z]=c.useState({}),{data:V}=oe({queryKey:t?N.agents.list(t):["agents","none"],queryFn:()=>We.list(t),enabled:!!t}),W=c.useMemo(()=>{if(!V)return"claude_local";const ae=V.find(je=>je.role==="ceo");return(ae==null?void 0:ae.adapterType)??"claude_local"},[V]),J="Upload a .zip exported directly from CrewSpace. Re-zipped archives created by Finder, Explorer, or other zip tools may not import correctly.";c.useEffect(()=>{r([{label:"Org Chart",href:"/org"},{label:"Import"}])},[r]);function Y(){if(d==="local")return f?{type:"inline",rootPath:f.rootPath,files:f.files}:null;const ae=p.trim();return ae?{type:"github",url:ae}:null}const de=ge({mutationFn:()=>{const ae=Y();if(!ae)throw new Error("No source configured.");return ls.importPreview({source:ae,include:{company:!0,agents:!0,projects:!0,issues:!0},target:j==="new"?{mode:"new_company",newCompanyName:g||null}:{mode:"existing_company",companyId:t},collisionStrategy:w})},onSuccess:ae=>{_(ae);const je=fb(ae),ke=BK(d,p,(f==null?void 0:f.name)??null,(f==null?void 0:f.rootPath)??null),Xe={};for(const yt of je)yt.action==="rename"&&ke&&(Xe[yt.slug]=KK(ke,yt.originalName));C(Xe),K(new Set),z(new Set);const lt={};for(const yt of ae.manifest.agents)lt[yt.slug]=W;R(lt),H(new Set),Z({});const It=new Set(Object.keys(ae.files));if(j==="existing"&&ae.manifest.company&&ae.plan.companyAction==="update"){const yt=ca(ae.manifest.company.path);It.delete(yt)}L(It);const Ue=xb(ae),pt=Go(ae.files,Ue),ht=new Set;for(const yt of pt)yt.kind==="dir"&&ht.add(yt.path);for(const[yt,hn]of Ue)if(hn==="update"){const pn=yt.split("/").filter(Boolean);let re="";for(let $e=0;$e<pn.length-1;$e++)re=re?`${re}/${pn[$e]}`:pn[$e],ht.add(re)}B(ht);const ln=Object.keys(ae.files)[0];ln&&S(ln)},onError:ae=>{a({tone:"error",title:"Preview failed",body:ae instanceof Error?ae.message:"Failed to preview import."})}});function fe(){if(!v)return;const ae={};for(const[je,ke]of Object.entries($))ke.trim()&&(ae[je]=ke.trim());return Object.keys(ae).length>0?ae:void 0}function Ce(){const ae=Array.from(k).sort();return ae.length>0?ae:void 0}const le=ge({mutationFn:()=>{const ae=Y();if(!ae)throw new Error("No source configured.");return ls.importBundle({source:ae,include:{company:!0,agents:!0,projects:!0,issues:!0},target:j==="new"?{mode:"new_company",newCompanyName:g||null}:{mode:"existing_company",companyId:t},collisionStrategy:w,nameOverrides:fe(),selectedFiles:Ce(),adapterOverrides:me()})},onSuccess:async ae=>{var lt,It;await o.invalidateQueries({queryKey:N.companies.all});const je=await ls.get(ae.company.id),ke=u?null:await o.fetchQuery({queryKey:N.auth.session,queryFn:()=>Bn.getSession()}),Xe=u??((lt=ke==null?void 0:ke.user)==null?void 0:lt.id)??((It=ke==null?void 0:ke.session)==null?void 0:It.userId)??null;zK(v,ae,Xe),s(je.id),a({tone:"success",title:"Import complete",body:`${ae.company.name}: ${ae.agents.length} agent${ae.agents.length===1?"":"s"} processed.`}),window.location.assign(`/${je.issuePrefix}/dashboard`)},onError:ae=>{a({tone:"error",title:"Import failed",body:ae instanceof Error?ae.message:"Failed to apply import."})}});async function Re(ae){const je=ae.target.files;if(!(!je||je.length===0))try{const ke=await QK(je[0]);h(ke),_(null)}catch(ke){a({tone:"error",title:"Package read failed",body:ke instanceof Error?ke.message:"Failed to read folder."})}}const Pe=c.useMemo(()=>v?xb(v):new Map,[v]),Fe=c.useMemo(()=>v?Go(v.files,Pe):[],[v,Pe]),pe=c.useMemo(()=>v?fb(v):[],[v]),Le=c.useMemo(()=>{const ae=new Map;if(!v)return ae;for(const je of pe){if(!je.filePath||I.has(je.slug))continue;const Xe=$[je.slug]??je.plannedName;if(Xe===je.originalName)continue;const lt=je.filePath.split("/").slice(0,-1).join("/");lt&&ae.set(lt,Xe),ae.set(je.filePath,Xe)}return ae},[v,pe,$,I]),q=c.useMemo(()=>af(Fe),[Fe]),D=k.size;function ie(ae){B(je=>{const ke=new Set(je);return ke.has(ae)?ke.delete(ae):ke.add(ae),ke})}function Ie(ae,je){v&&L(ke=>{const Xe=new Set(ke);if(je==="file")Xe.has(ae)?Xe.delete(ae):Xe.add(ae);else{const lt=(Ue,pt)=>{for(const ht of Ue){if(ht.path===pt)return ht;const ln=lt(ht.children,pt);if(ln)return ln}return null},It=lt(Fe,ae);if(It){const Ue=ql(It.children,"file");for(const ht of It.children)ht.kind==="file"&&Ue.add(ht.path);const pt=[...Ue].every(ht=>Xe.has(ht));for(const ht of Ue)pt?Xe.delete(ht):Xe.add(ht)}}return Xe})}function ue(ae,je){C(ke=>({...ke,[ae]:je})),z(ke=>{if(!ke.has(ae))return ke;const Xe=new Set(ke);return Xe.delete(ae),Xe})}function Be(ae){z(je=>{const ke=new Set(je);return ke.has(ae)?ke.delete(ae):ke.add(ae),ke})}function be(ae,je){K(ke=>{const Xe=new Set(ke),lt=Xe.has(ae);return lt?Xe.delete(ae):Xe.add(ae),je&&L(It=>{const Ue=new Set(It);return lt?Ue.add(je):Ue.delete(je),Ue}),Xe})}function he(ae,je){R(ke=>({...ke,[ae]:je})),Z(ke=>{const Xe={...ke};return delete Xe[ae],Xe})}function Se(ae){H(je=>{const ke=new Set(je);return ke.has(ae)?ke.delete(ae):ke.add(ae),ke})}function we(ae,je){Z(ke=>({...ke,[ae]:{...ke[ae]??{...io,adapterType:A[ae]??"claude_local"},...je}}))}const ee=c.useMemo(()=>v?v.manifest.agents.map(ae=>({slug:ae.slug,name:ae.name,adapterType:ae.adapterType})):[],[v]);function me(){if(ee.length===0)return;const ae={};for(const je of ee){const ke=A[je.slug]??je.adapterType,Xe=U[je.slug],lt={adapterType:ke};if(Xe){const It=oo(ke);lt.adapterConfig=It.buildAdapterConfig(Xe)}ae[je.slug]=lt}return Object.keys(ae).length>0?ae:void 0}const ye=d==="local"?!!f:p.trim().length>0,Ke=v?v.errors.length>0:!1,qe=E&&v?v.files[E]??null:null,se=E?Pe.get(E)??null:null;return t?e.jsxs("div",{children:[e.jsxs("div",{className:"border-b border-border px-5 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold",children:"Import source"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Choose a GitHub repo or upload a local CrewSpace zip package."})]}),e.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:[{key:"github",icon:Sc,label:"GitHub repo"},{key:"local",icon:ol,label:"Local zip"}].map(({key:ae,icon:je,label:ke})=>e.jsx("button",{type:"button",className:O("rounded-md border px-3 py-2 text-left text-sm transition-colors",d===ae?"border-foreground bg-accent":"border-border hover:bg-accent/50"),onClick:()=>{m(ae),_(null)},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{className:"h-4 w-4"}),ke]})},ae))}),d==="local"?e.jsxs("div",{className:"rounded-md border border-dashed border-border px-3 py-3",children:[e.jsx("input",{ref:i,type:"file",accept:".zip,application/zip",className:"hidden",onChange:Re}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>{var ae;return(ae=i.current)==null?void 0:ae.click()},children:"Choose zip"}),f&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[f.name," with"," ",Object.keys(f.files).length," file",Object.keys(f.files).length===1?"":"s"]})]}),!f&&e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:J})]}):e.jsx(ct,{label:"GitHub URL",hint:"Repo tree path or blob URL to COMPANY.md (e.g. github.com/owner/repo/tree/main/company).",children:e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",type:"text",value:p,placeholder:"https://github.com/owner/repo/tree/main/company",onChange:ae=>{x(ae.target.value),_(null)}})}),e.jsx(ct,{label:"Target",hint:"Import into this company or create a new one.",children:e.jsxs("select",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",value:j,onChange:ae=>{b(ae.target.value),_(null)},children:[e.jsx("option",{value:"new",children:"Create new company"}),e.jsxs("option",{value:"existing",children:["Existing company: ",n==null?void 0:n.name]})]})}),j==="new"&&e.jsx(ct,{label:"New company name",hint:"Optional override. Leave blank to use the package name.",children:e.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",type:"text",value:g,onChange:ae=>y(ae.target.value),placeholder:"Imported Company"})}),e.jsx(ct,{label:"Collision strategy",hint:"Board imports can rename, skip, or replace matching company content.",children:e.jsxs("select",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",value:w,onChange:ae=>{F(ae.target.value),_(null)},children:[e.jsx("option",{value:"rename",children:"Rename on conflict"}),e.jsx("option",{value:"skip",children:"Skip on conflict"}),e.jsx("option",{value:"replace",children:"Replace existing"})]})}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(G,{size:"sm",variant:"outline",onClick:()=>de.mutate(),disabled:de.isPending||!ye,children:de.isPending?"Previewing...":"Preview import"})})]}),v&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sticky top-0 z-10 border-b border-border bg-background px-5 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsx("span",{className:"font-medium",children:"Import preview"}),e.jsxs("span",{className:"text-muted-foreground",children:[D," / ",q," file",q===1?"":"s"," selected"]}),pe.length>0&&e.jsxs("span",{className:"text-amber-500",children:[pe.length," conflict",pe.length===1?"":"s"]}),v.errors.length>0&&e.jsxs("span",{className:"text-destructive",children:[v.errors.length," error",v.errors.length===1?"":"s"]})]})}),e.jsx(WK,{conflicts:pe,nameOverrides:$,skippedSlugs:I,confirmedSlugs:T,onRename:ue,onToggleSkip:be,onToggleConfirm:Be}),e.jsx(VK,{agents:ee,adapterOverrides:A,expandedSlugs:Q,configValues:U,onChangeAdapter:he,onToggleExpand:Se,onChangeConfig:we}),e.jsx("div",{className:"mx-5 mt-3 flex justify-end",children:e.jsxs(G,{size:"sm",onClick:()=>le.mutate(),disabled:le.isPending||Ke||D===0,children:[e.jsx(ei,{className:"mr-1.5 h-3.5 w-3.5"}),le.isPending?"Importing...":`Import ${D} file${D===1?"":"s"}`]})}),v.warnings.length>0&&e.jsx("div",{className:"mx-5 mt-3 rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:v.warnings.map(ae=>e.jsx("div",{className:"text-xs text-amber-500",children:ae},ae))}),v.errors.length>0&&e.jsx("div",{className:"mx-5 mt-3 rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3",children:v.errors.map(ae=>e.jsx("div",{className:"text-xs text-destructive",children:ae},ae))}),e.jsxs("div",{className:"grid h-[calc(100vh-16rem)] gap-0 xl:grid-cols-[19rem_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex flex-col border-r border-border overflow-hidden",children:[e.jsx("div",{className:"border-b border-border px-4 py-3 shrink-0",children:e.jsx("h2",{className:"text-base font-semibold",children:"Package files"})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(ou,{nodes:Fe,selectedFile:E,expandedDirs:M,checkedFiles:k,onToggleDir:ie,onSelectFile:S,onToggleCheck:Ie,renderFileExtra:(ae,je)=>FK(ae,je,Le),fileRowClassName:qK})})]}),e.jsx("div",{className:"min-w-0 overflow-y-auto pl-6",children:e.jsx(UK,{selectedFile:E,content:qe,allFiles:(v==null?void 0:v.files)??{},action:se,renamedTo:E?Le.get(E)??null:null})})]})]})]}):e.jsx(tn,{icon:ei,message:"Select a company to import into."})}function JK({filters:t,onRemove:n,onClear:s}){return t.length===0?null:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.map(r=>e.jsxs(Wt,{variant:"secondary",className:"gap-1 pr-1",children:[e.jsxs("span",{className:"text-muted-foreground",children:[r.label,":"]}),e.jsx("span",{children:r.value}),e.jsx("button",{className:"ml-1 rounded-full hover:bg-accent p-0.5",onClick:()=>n(r.key),children:e.jsx(zt,{className:"h-3 w-3"})})]},r.key)),e.jsx(G,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:s,children:"Clear all"})]})}function _t({title:t,children:n}){return e.jsxs("section",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide",children:t}),e.jsx(yn,{}),n]})}function At({title:t,children:n}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:t}),n]})}function On({name:t,cssVar:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-md border border-border shrink-0",style:{backgroundColor:`var(${n})`}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-mono",children:n}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t})]})]})}function ZK(){const[t,n]=c.useState("todo"),[s,r]=c.useState("medium"),[a,o]=c.useState("in_progress"),[i,l]=c.useState(!0),[u,d]=c.useState(!1),[m,p]=c.useState("Click to edit this text"),[x,f]=c.useState("Editable Title"),[h,j]=c.useState("This is an editable description. Click to edit it — the textarea auto-sizes to fit the content without layout shift."),[b,g]=c.useState([{key:"status",label:"Status",value:"Active"},{key:"priority",label:"Priority",value:"High"}]);return e.jsxs("div",{className:"space-y-10 max-w-4xl",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Design Guide"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Every component, style, and pattern used across CrewSpace."})]}),e.jsxs(_t,{title:"Component Coverage",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"This page should be updated when new UI primitives or app-level patterns ship."}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsx(At,{title:"UI primitives",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:["avatar","badge","breadcrumb","button","card","checkbox","collapsible","command","dialog","dropdown-menu","input","label","popover","scroll-area","select","separator","sheet","skeleton","tabs","textarea","tooltip"].map(y=>e.jsx(Wt,{variant:"outline",className:"font-mono text-[10px]",children:y},y))})}),e.jsx(At,{title:"App components",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:["StatusBadge","StatusIcon","PriorityIcon","EntityRow","EmptyState","MetricCard","FilterBar","InlineEditor","PageSkeleton","Identity","CommentThread","MarkdownEditor","PropertiesPanel","Sidebar","CommandPalette"].map(y=>e.jsx(Wt,{variant:"ghost",className:"font-mono text-[10px]",children:y},y))})})]})]}),e.jsxs(_t,{title:"Colors",children:[e.jsx(At,{title:"Core",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(On,{name:"Background",cssVar:"--background"}),e.jsx(On,{name:"Foreground",cssVar:"--foreground"}),e.jsx(On,{name:"Card",cssVar:"--card"}),e.jsx(On,{name:"Primary",cssVar:"--primary"}),e.jsx(On,{name:"Primary foreground",cssVar:"--primary-foreground"}),e.jsx(On,{name:"Secondary",cssVar:"--secondary"}),e.jsx(On,{name:"Muted",cssVar:"--muted"}),e.jsx(On,{name:"Muted foreground",cssVar:"--muted-foreground"}),e.jsx(On,{name:"Accent",cssVar:"--accent"}),e.jsx(On,{name:"Destructive",cssVar:"--destructive"}),e.jsx(On,{name:"Border",cssVar:"--border"}),e.jsx(On,{name:"Ring",cssVar:"--ring"})]})}),e.jsx(At,{title:"Sidebar",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(On,{name:"Sidebar",cssVar:"--sidebar"}),e.jsx(On,{name:"Sidebar border",cssVar:"--sidebar-border"})]})}),e.jsx(At,{title:"Chart",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(On,{name:"Chart 1",cssVar:"--chart-1"}),e.jsx(On,{name:"Chart 2",cssVar:"--chart-2"}),e.jsx(On,{name:"Chart 3",cssVar:"--chart-3"}),e.jsx(On,{name:"Chart 4",cssVar:"--chart-4"}),e.jsx(On,{name:"Chart 5",cssVar:"--chart-5"})]})})]}),e.jsx(_t,{title:"Typography",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-bold",children:"Page Title — text-xl font-bold"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Section Title — text-lg font-semibold"}),e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide",children:"Section Heading — text-sm font-semibold uppercase tracking-wide"}),e.jsx("p",{className:"text-sm font-medium",children:"Card Title — text-sm font-medium"}),e.jsx("p",{className:"text-sm font-semibold",children:"Card Title Alt — text-sm font-semibold"}),e.jsx("p",{className:"text-sm",children:"Body text — text-sm"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Muted description — text-sm text-muted-foreground"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tiny label — text-xs text-muted-foreground"}),e.jsx("p",{className:"text-sm font-mono text-muted-foreground",children:"Mono identifier — text-sm font-mono text-muted-foreground"}),e.jsx("p",{className:"text-2xl font-bold",children:"Large stat — text-2xl font-bold"}),e.jsx("p",{className:"font-mono text-xs",children:"Log/code text — font-mono text-xs"})]})}),e.jsx(_t,{title:"Radius",children:e.jsx("div",{className:"flex items-end gap-4 flex-wrap",children:[["sm","var(--radius-sm)"],["md","var(--radius-md)"],["lg","var(--radius-lg)"],["xl","var(--radius-xl)"],["full","9999px"]].map(([y,v])=>e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("div",{className:"h-12 w-12 bg-primary",style:{borderRadius:v}}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y})]},y))})}),e.jsxs(_t,{title:"Buttons",children:[e.jsx(At,{title:"Variants",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(G,{variant:"default",children:"Default"}),e.jsx(G,{variant:"secondary",children:"Secondary"}),e.jsx(G,{variant:"outline",children:"Outline"}),e.jsx(G,{variant:"ghost",children:"Ghost"}),e.jsx(G,{variant:"destructive",children:"Destructive"}),e.jsx(G,{variant:"link",children:"Link"})]})}),e.jsx(At,{title:"Sizes",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(G,{size:"xs",children:"Extra Small"}),e.jsx(G,{size:"sm",children:"Small"}),e.jsx(G,{size:"default",children:"Default"}),e.jsx(G,{size:"lg",children:"Large"})]})}),e.jsx(At,{title:"Icon buttons",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(G,{variant:"ghost",size:"icon-xs",children:e.jsx(ws,{})}),e.jsx(G,{variant:"ghost",size:"icon-sm",children:e.jsx(ws,{})}),e.jsx(G,{variant:"outline",size:"icon",children:e.jsx(ws,{})}),e.jsx(G,{variant:"outline",size:"icon-lg",children:e.jsx(ws,{})})]})}),e.jsx(At,{title:"With icons",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(G,{children:[e.jsx(Ot,{})," New Issue"]}),e.jsxs(G,{variant:"outline",children:[e.jsx(ol,{})," Upload"]}),e.jsxs(G,{variant:"destructive",children:[e.jsx(Ls,{})," Delete"]}),e.jsxs(G,{size:"sm",children:[e.jsx(Ot,{})," Add"]})]})}),e.jsx(At,{title:"States",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(G,{disabled:!0,children:"Disabled"}),e.jsx(G,{variant:"outline",disabled:!0,children:"Disabled Outline"})]})})]}),e.jsx(_t,{title:"Badges",children:e.jsx(At,{title:"Variants",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Wt,{variant:"default",children:"Default"}),e.jsx(Wt,{variant:"secondary",children:"Secondary"}),e.jsx(Wt,{variant:"outline",children:"Outline"}),e.jsx(Wt,{variant:"destructive",children:"Destructive"}),e.jsx(Wt,{variant:"ghost",children:"Ghost"})]})})}),e.jsxs(_t,{title:"Status System",children:[e.jsx(At,{title:"StatusBadge (all statuses)",children:e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:["active","running","paused","idle","archived","planned","achieved","completed","failed","timed_out","succeeded","error","pending_approval","backlog","todo","in_progress","in_review","blocked","done","terminated","cancelled","pending","revision_requested","approved","rejected"].map(y=>e.jsx(Dt,{status:y},y))})}),e.jsxs(At,{title:"StatusIcon (interactive)",children:[e.jsx("div",{className:"flex items-center gap-3 flex-wrap",children:["backlog","todo","in_progress","in_review","done","cancelled","blocked"].map(y=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Pn,{status:y}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y})]},y))}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Pn,{status:t,onChange:n}),e.jsxs("span",{className:"text-sm",children:["Click the icon to change status (current: ",t,")"]})]})]}),e.jsxs(At,{title:"PriorityIcon (interactive)",children:[e.jsx("div",{className:"flex items-center gap-3 flex-wrap",children:["critical","high","medium","low"].map(y=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(vs,{priority:y}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y})]},y))}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(vs,{priority:s,onChange:r}),e.jsxs("span",{className:"text-sm",children:["Click the icon to change (current: ",s,")"]})]})]}),e.jsx(At,{title:"Agent status dots",children:e.jsx("div",{className:"flex items-center gap-4 flex-wrap",children:["running","active","paused","error","archived"].map(y=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"relative flex h-2.5 w-2.5",children:e.jsx("span",{className:`inline-flex h-full w-full rounded-full ${Fx[y]??qx}`})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y})]},y))})}),e.jsx(At,{title:"Run invocation badges",children:e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:[["timer","bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300"],["assignment","bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300"],["on_demand","bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300"],["automation","bg-muted text-muted-foreground"]].map(([y,v])=>e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[10px] font-medium ${v}`,children:y},y))})})]}),e.jsx(_t,{title:"Form Elements",children:e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(At,{title:"Input",children:[e.jsx(Xt,{placeholder:"Default input"}),e.jsx(Xt,{placeholder:"Disabled input",disabled:!0,className:"mt-2"})]}),e.jsx(At,{title:"Textarea",children:e.jsx(Ur,{placeholder:"Write something..."})}),e.jsx(At,{title:"Checkbox & Label",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{id:"check1",defaultChecked:!0}),e.jsx(En,{htmlFor:"check1",children:"Checked item"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{id:"check2"}),e.jsx(En,{htmlFor:"check2",children:"Unchecked item"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{id:"check3",disabled:!0}),e.jsx(En,{htmlFor:"check3",children:"Disabled item"})]})]})}),e.jsx(At,{title:"Inline Editor",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Title (single-line)"}),e.jsx(kr,{value:x,onSave:f,as:"h2",className:"text-xl font-bold"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Body text (single-line)"}),e.jsx(kr,{value:m,onSave:p,as:"p",className:"text-sm"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Description (multiline, auto-sizing)"}),e.jsx(kr,{value:h,onSave:j,as:"p",className:"text-sm text-muted-foreground",placeholder:"Add a description...",multiline:!0})]})]})})]})}),e.jsx(_t,{title:"Select",children:e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(At,{title:"Default size",children:[e.jsxs(Hn,{value:a,onValueChange:o,children:[e.jsx(Qn,{className:"w-full",children:e.jsx(Vn,{placeholder:"Select status"})}),e.jsxs(Gn,{children:[e.jsx(Mt,{value:"backlog",children:"Backlog"}),e.jsx(Mt,{value:"todo",children:"Todo"}),e.jsx(Mt,{value:"in_progress",children:"In Progress"}),e.jsx(Mt,{value:"in_review",children:"In Review"}),e.jsx(Mt,{value:"done",children:"Done"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Current value: ",a]})]}),e.jsx(At,{title:"Small trigger",children:e.jsxs(Hn,{defaultValue:"high",children:[e.jsx(Qn,{size:"sm",className:"w-full",children:e.jsx(Vn,{})}),e.jsxs(Gn,{children:[e.jsx(Mt,{value:"critical",children:"Critical"}),e.jsx(Mt,{value:"high",children:"High"}),e.jsx(Mt,{value:"medium",children:"Medium"}),e.jsx(Mt,{value:"low",children:"Low"})]})]})})]})}),e.jsx(_t,{title:"Dropdown Menu",children:e.jsxs(gl,{children:[e.jsx(bl,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",children:["Quick Actions",e.jsx(rn,{className:"h-4 w-4"})]})}),e.jsxs(yl,{align:"start",className:"w-56",children:[e.jsxs(Os,{children:[e.jsx(Nn,{className:"h-4 w-4"}),"Mark as done",e.jsx(UL,{children:"⌘D"})]}),e.jsxs(Os,{children:[e.jsx(ym,{className:"h-4 w-4"}),"Open docs"]}),e.jsx(au,{}),e.jsx(OL,{checked:i,onCheckedChange:y=>l(y===!0),children:"Watch issue"}),e.jsxs(Os,{variant:"destructive",children:[e.jsx(Ls,{className:"h-4 w-4"}),"Delete issue"]})]})]})}),e.jsx(_t,{title:"Popover",children:e.jsxs(Ht,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",children:"Open Popover"})}),e.jsxs(Qt,{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Agent heartbeat"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last run succeeded 24s ago. Next timer run in 9m."}),e.jsx(G,{size:"xs",children:"Wake now"})]})]})}),e.jsx(_t,{title:"Collapsible",children:e.jsxs(Sa,{open:u,onOpenChange:d,className:"space-y-2",children:[e.jsx(Ia,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",children:[u?"Hide":"Show"," advanced filters"]})}),e.jsx(_a,{className:"rounded-md border border-border p-3",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(En,{htmlFor:"owner-filter",children:"Owner"}),e.jsx(Xt,{id:"owner-filter",placeholder:"Filter by agent name"})]})})]})}),e.jsx(_t,{title:"Sheet",children:e.jsxs(bN,{children:[e.jsx(dU,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",children:"Open Side Panel"})}),e.jsxs(yN,{side:"right",children:[e.jsxs(vN,{children:[e.jsx(jN,{children:"Issue Properties"}),e.jsx(xU,{children:"Edit metadata without leaving the current page."})]}),e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(En,{htmlFor:"sheet-title",children:"Title"}),e.jsx(Xt,{id:"sheet-title",defaultValue:"Improve onboarding docs"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(En,{htmlFor:"sheet-description",children:"Description"}),e.jsx(Ur,{id:"sheet-description",defaultValue:"Capture setup pitfalls and screenshots."})]})]}),e.jsxs(pU,{children:[e.jsx(G,{variant:"outline",children:"Cancel"}),e.jsx(G,{children:"Save"})]})]})]})}),e.jsx(_t,{title:"Scroll Area",children:e.jsx(Dx,{className:"h-36 rounded-md border border-border",children:e.jsx("div",{className:"space-y-2 p-3",children:Array.from({length:12}).map((y,v)=>e.jsxs("div",{className:"rounded-md border border-border p-2 text-sm",children:["Heartbeat run #",v+1,": completed successfully"]},v))})})}),e.jsx(_t,{title:"Command (CMDK)",children:e.jsx("div",{className:"rounded-md border border-border",children:e.jsxs(_0,{children:[e.jsx(A0,{placeholder:"Type a command or search..."}),e.jsxs(E0,{children:[e.jsx(T0,{children:"No results found."}),e.jsxs(Fa,{heading:"Pages",children:[e.jsxs(Kn,{children:[e.jsx(Ka,{className:"h-4 w-4"}),"Dashboard"]}),e.jsxs(Kn,{children:[e.jsx(rs,{className:"h-4 w-4"}),"Issues"]})]}),e.jsx(Fi,{}),e.jsxs(Fa,{heading:"Actions",children:[e.jsxs(Kn,{children:[e.jsx(M1,{className:"h-4 w-4"}),"Open command palette"]}),e.jsxs(Kn,{children:[e.jsx(Ot,{className:"h-4 w-4"}),"Create new issue"]})]})]})]})})}),e.jsx(_t,{title:"Breadcrumb",children:e.jsx(c0,{children:e.jsxs(d0,{children:[e.jsx(hc,{children:e.jsx(Wm,{href:"#",children:"Projects"})}),e.jsx(Hm,{}),e.jsx(hc,{children:e.jsx(Wm,{href:"#",children:"CrewSpace App"})}),e.jsx(Hm,{}),e.jsx(hc,{children:e.jsx(u0,{children:"Issue List"})})]})})}),e.jsxs(_t,{title:"Cards",children:[e.jsx(At,{title:"Standard Card",children:e.jsxs(jn,{children:[e.jsxs(qn,{children:[e.jsx(Un,{children:"Card Title"}),e.jsx(cs,{children:"Card description with supporting text."})]}),e.jsx(wn,{children:e.jsx("p",{className:"text-sm",children:"Card content goes here. This is the main body area."})}),e.jsxs(cF,{className:"gap-2",children:[e.jsx(G,{size:"sm",children:"Action"}),e.jsx(G,{variant:"outline",size:"sm",children:"Cancel"})]})]})}),e.jsx(At,{title:"Metric Cards",children:e.jsxs("div",{className:"grid md:grid-cols-2 xl:grid-cols-4 gap-4",children:[e.jsx(ma,{icon:ss,value:12,label:"Active Agents",description:"+3 this week"}),e.jsx(ma,{icon:rs,value:48,label:"Open Issues"}),e.jsx(ma,{icon:wr,value:"$1,234",label:"Monthly Cost",description:"Under budget"}),e.jsx(ma,{icon:Xo,value:"99.9%",label:"Uptime"})]})})]}),e.jsxs(_t,{title:"Tabs",children:[e.jsx(At,{title:"Default (pill) variant",children:e.jsxs(Ss,{defaultValue:"overview",children:[e.jsxs(co,{children:[e.jsx(An,{value:"overview",children:"Overview"}),e.jsx(An,{value:"runs",children:"Runs"}),e.jsx(An,{value:"config",children:"Config"}),e.jsx(An,{value:"costs",children:"Costs"})]}),e.jsx(on,{value:"overview",children:e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"Overview tab content."})}),e.jsx(on,{value:"runs",children:e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"Runs tab content."})}),e.jsx(on,{value:"config",children:e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"Config tab content."})}),e.jsx(on,{value:"costs",children:e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"Costs tab content."})})]})}),e.jsx(At,{title:"Line variant",children:e.jsxs(Ss,{defaultValue:"summary",children:[e.jsxs(co,{variant:"line",children:[e.jsx(An,{value:"summary",children:"Summary"}),e.jsx(An,{value:"details",children:"Details"}),e.jsx(An,{value:"comments",children:"Comments"})]}),e.jsx(on,{value:"summary",children:e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"Summary content with underline tabs."})}),e.jsx(on,{value:"details",children:e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"Details content."})}),e.jsx(on,{value:"comments",children:e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"Comments content."})})]})})]}),e.jsx(_t,{title:"Entity Rows",children:e.jsxs("div",{className:"border border-border rounded-md",children:[e.jsx(gr,{leading:e.jsxs(e.Fragment,{children:[e.jsx(Pn,{status:"in_progress"}),e.jsx(vs,{priority:"high"})]}),identifier:"PAP-001",title:"Implement authentication flow",subtitle:"Assigned to Agent Alpha",trailing:e.jsx(Dt,{status:"in_progress"}),onClick:()=>{}}),e.jsx(gr,{leading:e.jsxs(e.Fragment,{children:[e.jsx(Pn,{status:"done"}),e.jsx(vs,{priority:"medium"})]}),identifier:"PAP-002",title:"Set up CI/CD pipeline",subtitle:"Completed 2 days ago",trailing:e.jsx(Dt,{status:"done"}),onClick:()=>{}}),e.jsx(gr,{leading:e.jsxs(e.Fragment,{children:[e.jsx(Pn,{status:"todo"}),e.jsx(vs,{priority:"low"})]}),identifier:"PAP-003",title:"Write API documentation",trailing:e.jsx(Dt,{status:"todo"}),onClick:()=>{}}),e.jsx(gr,{leading:e.jsxs(e.Fragment,{children:[e.jsx(Pn,{status:"blocked"}),e.jsx(vs,{priority:"critical"})]}),identifier:"PAP-004",title:"Deploy to production",subtitle:"Blocked by PAP-001",trailing:e.jsx(Dt,{status:"blocked"}),selected:!0})]})}),e.jsxs(_t,{title:"Filter Bar",children:[e.jsx(JK,{filters:b,onRemove:y=>g(v=>v.filter(_=>_.key!==y)),onClear:()=>g([])}),b.length===0&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>g([{key:"status",label:"Status",value:"Active"},{key:"priority",label:"Priority",value:"High"}]),children:"Reset filters"})]}),e.jsxs(_t,{title:"Avatars",children:[e.jsx(At,{title:"Sizes",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ta,{size:"sm",children:e.jsx(na,{children:"SM"})}),e.jsx(ta,{children:e.jsx(na,{children:"DF"})}),e.jsx(ta,{size:"lg",children:e.jsx(na,{children:"LG"})})]})}),e.jsx(At,{title:"Group",children:e.jsxs(JR,{children:[e.jsx(ta,{children:e.jsx(na,{children:"A1"})}),e.jsx(ta,{children:e.jsx(na,{children:"A2"})}),e.jsx(ta,{children:e.jsx(na,{children:"A3"})}),e.jsx(ZR,{children:"+5"})]})})]}),e.jsxs(_t,{title:"Identity",children:[e.jsx(At,{title:"Sizes",children:e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx(Ut,{name:"Agent Alpha",size:"sm"}),e.jsx(Ut,{name:"Agent Alpha"}),e.jsx(Ut,{name:"Agent Alpha",size:"lg"})]})}),e.jsx(At,{title:"Initials derivation",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Ut,{name:"CEO Agent",size:"sm"}),e.jsx(Ut,{name:"Alpha",size:"sm"}),e.jsx(Ut,{name:"Quality Assurance Lead",size:"sm"})]})}),e.jsx(At,{title:"Custom initials",children:e.jsx(Ut,{name:"Backend Service",initials:"BS",size:"sm"})})]}),e.jsx(_t,{title:"Tooltips",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",children:"Hover me"})}),e.jsx(Yn,{children:"This is a tooltip"})]}),e.jsxs(Jn,{children:[e.jsx(Zn,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon-sm",children:e.jsx(zr,{})})}),e.jsx(Yn,{children:"Settings"})]})]})}),e.jsx(_t,{title:"Dialog",children:e.jsxs(Cs,{children:[e.jsx(S0,{asChild:!0,children:e.jsx(G,{variant:"outline",children:"Open Dialog"})}),e.jsxs(Fs,{children:[e.jsxs(fa,{children:[e.jsx(ha,{children:"Dialog Title"}),e.jsx(ga,{children:"This is a sample dialog showing the standard layout with header, content, and footer."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(En,{children:"Name"}),e.jsx(Xt,{placeholder:"Enter a name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(En,{children:"Description"}),e.jsx(Ur,{placeholder:"Describe...",className:"mt-1.5"})]})]}),e.jsxs(Ho,{children:[e.jsx(G,{variant:"outline",children:"Cancel"}),e.jsx(G,{children:"Save"})]})]})]})}),e.jsx(_t,{title:"Empty State",children:e.jsx("div",{className:"border border-border rounded-md",children:e.jsx(tn,{icon:Ga,message:"No items to show. Create your first one to get started.",action:"Create Item",onAction:()=>{}})})}),e.jsx(_t,{title:"Progress Bars (Budget)",children:e.jsx("div",{className:"space-y-3",children:[{label:"Under budget (40%)",pct:40,color:"bg-green-400"},{label:"Warning (75%)",pct:75,color:"bg-yellow-400"},{label:"Over budget (95%)",pct:95,color:"bg-red-400"}].map(({label:y,pct:v,color:_})=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:y}),e.jsxs("span",{className:"text-xs font-mono",children:[v,"%"]})]}),e.jsx("div",{className:"w-full h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-[width,background-color] duration-150 ${_}`,style:{width:`${v}%`}})})]},y))})}),e.jsx(_t,{title:"Log Viewer",children:e.jsxs("div",{className:"bg-neutral-950 rounded-lg p-3 font-mono text-xs max-h-80 overflow-y-auto",children:[e.jsx("div",{className:"text-foreground",children:"[12:00:01] INFO Agent started successfully"}),e.jsx("div",{className:"text-foreground",children:"[12:00:02] INFO Processing task PAP-001"}),e.jsx("div",{className:"text-yellow-400",children:"[12:00:05] WARN Rate limit approaching (80%)"}),e.jsx("div",{className:"text-foreground",children:"[12:00:08] INFO Task PAP-001 completed"}),e.jsx("div",{className:"text-red-400",children:"[12:00:12] ERROR Connection timeout to upstream service"}),e.jsx("div",{className:"text-blue-300",children:"[12:00:12] SYS Retrying connection in 5s..."}),e.jsx("div",{className:"text-foreground",children:"[12:00:17] INFO Reconnected successfully"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-cyan-400 animate-pulse"}),e.jsx("span",{className:"inline-flex h-full w-full rounded-full bg-cyan-400"})]}),e.jsx("span",{className:"text-cyan-400",children:"Live"})]})]})}),e.jsx(_t,{title:"Property Row Pattern",children:e.jsxs("div",{className:"border border-border rounded-md p-4 space-y-1 max-w-sm",children:[e.jsxs("div",{className:"flex items-center justify-between py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsx(Dt,{status:"active"})]}),e.jsxs("div",{className:"flex items-center justify-between py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Priority"}),e.jsx(vs,{priority:"high"})]}),e.jsxs("div",{className:"flex items-center justify-between py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Assignee"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ta,{size:"sm",children:e.jsx(na,{children:"A"})}),e.jsx("span",{className:"text-xs",children:"Agent Alpha"})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Created"}),e.jsx("span",{className:"text-xs",children:"Jan 15, 2025"})]})]})}),e.jsxs(_t,{title:"Navigation Patterns",children:[e.jsx(At,{title:"Sidebar nav items",children:e.jsxs("div",{className:"w-60 border border-border rounded-md p-3 space-y-0.5 bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium bg-accent text-accent-foreground",children:[e.jsx(Ka,{className:"h-4 w-4"}),"Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground cursor-pointer",children:[e.jsx(rs,{className:"h-4 w-4"}),"Issues",e.jsx("span",{className:"ml-auto text-xs bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:"12"})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground cursor-pointer",children:[e.jsx(ss,{className:"h-4 w-4"}),"Agents"]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground cursor-pointer",children:[e.jsx(Sr,{className:"h-4 w-4"}),"Projects"]})]})}),e.jsx(At,{title:"View toggle",children:e.jsxs("div",{className:"flex items-center border border-border rounded-md w-fit",children:[e.jsxs("button",{className:"px-3 py-1.5 text-xs font-medium bg-accent text-foreground rounded-l-md",children:[e.jsx(Ki,{className:"h-3.5 w-3.5 inline mr-1"}),"List"]}),e.jsxs("button",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground hover:bg-accent/50 rounded-r-md",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 inline mr-1"}),"Org"]})]})})]}),e.jsx(_t,{title:"Grouped List (Issues pattern)",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-muted/50 rounded-t-md",children:[e.jsx(Pn,{status:"in_progress"}),e.jsx("span",{className:"text-sm font-medium",children:"In Progress"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"2"})]}),e.jsxs("div",{className:"border border-border rounded-b-md",children:[e.jsx(gr,{leading:e.jsx(vs,{priority:"high"}),identifier:"PAP-101",title:"Build agent heartbeat system",onClick:()=>{}}),e.jsx(gr,{leading:e.jsx(vs,{priority:"medium"}),identifier:"PAP-102",title:"Add cost tracking dashboard",onClick:()=>{}})]})]})}),e.jsx(_t,{title:"Comment Thread Pattern",children:e.jsxs("div",{className:"space-y-3 max-w-2xl",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Comments (2)"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Agent"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Jan 15, 2025"})]}),e.jsx("p",{className:"text-sm",children:"Started working on the authentication module. Will need API keys configured."})]}),e.jsxs("div",{className:"rounded-md border border-border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Human"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Jan 16, 2025"})]}),e.jsx("p",{className:"text-sm",children:"API keys have been added to the vault. Please proceed."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ur,{placeholder:"Leave a comment...",rows:3}),e.jsx(G,{size:"sm",children:"Comment"})]})]})}),e.jsx(_t,{title:"Cost Table Pattern",children:e.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"border-b border-border bg-accent/20",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Model"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Tokens"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Cost"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("td",{className:"px-3 py-2",children:"claude-sonnet-4-20250514"}),e.jsx("td",{className:"px-3 py-2 font-mono",children:"1.2M"}),e.jsx("td",{className:"px-3 py-2 font-mono",children:"$18.00"})]}),e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("td",{className:"px-3 py-2",children:"claude-haiku-4-20250506"}),e.jsx("td",{className:"px-3 py-2 font-mono",children:"500k"}),e.jsx("td",{className:"px-3 py-2 font-mono",children:"$1.25"})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-medium",children:"Total"}),e.jsx("td",{className:"px-3 py-2 font-mono",children:"1.7M"}),e.jsx("td",{className:"px-3 py-2 font-mono font-medium",children:"$19.25"})]})]})]})})}),e.jsxs(_t,{title:"Skeletons",children:[e.jsx(At,{title:"Individual",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ze,{className:"h-4 w-48"}),e.jsx(Ze,{className:"h-8 w-full max-w-sm"}),e.jsx(Ze,{className:"h-20 w-full"})]})}),e.jsx(At,{title:"Page Skeleton (list)",children:e.jsx("div",{className:"border border-border rounded-md p-4",children:e.jsx(mn,{variant:"list"})})}),e.jsx(At,{title:"Page Skeleton (detail)",children:e.jsx("div",{className:"border border-border rounded-md p-4",children:e.jsx(mn,{variant:"detail"})})})]}),e.jsx(_t,{title:"Separator",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Horizontal"}),e.jsx(yn,{}),e.jsxs("div",{className:"flex items-center gap-4 h-8",children:[e.jsx("span",{className:"text-sm",children:"Left"}),e.jsx(yn,{orientation:"vertical"}),e.jsx("span",{className:"text-sm",children:"Right"})]})]})}),e.jsx(_t,{title:"Common Icons (Lucide)",children:e.jsx("div",{className:"grid grid-cols-4 md:grid-cols-6 gap-4",children:[["Inbox",Ga],["ListTodo",Ki],["CircleDot",rs],["Hexagon",Sr],["Target",Ir],["LayoutDashboard",Ka],["Bot",ss],["DollarSign",wr],["History",sl],["Search",ws],["Plus",Ot],["Trash2",Ls],["Settings",zr],["User",Ns],["Mail",Wb],["Upload",ol],["Zap",Xo]].map(([y,v])=>{const _=v;return e.jsxs("div",{className:"flex flex-col items-center gap-1.5 p-2",children:[e.jsx(_,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] text-muted-foreground font-mono",children:y})]},y)})})}),e.jsx(_t,{title:"Keyboard Shortcuts",children:e.jsx("div",{className:"border border-border rounded-md divide-y divide-border text-sm",children:[["Cmd+K / Ctrl+K","Open Command Palette"],["C","New Issue (outside inputs)"],["[","Toggle Sidebar"],["]","Toggle Properties Panel"],["Cmd+Enter / Ctrl+Enter","Submit markdown comment"]].map(([y,v])=>e.jsxs("div",{className:"flex items-center justify-between px-4 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:v}),e.jsx("kbd",{className:"px-2 py-0.5 text-xs font-mono bg-muted rounded border border-border",children:y})]},y))})})]})}function YK(){var l;const{setBreadcrumbs:t}=Ft(),n=at(),[s,r]=c.useState(null);c.useEffect(()=>{t([{label:"Instance Settings"},{label:"General"}])},[t]);const a=oe({queryKey:N.instance.generalSettings,queryFn:()=>Rr.getGeneral()}),o=ge({mutationFn:async u=>Rr.updateGeneral({censorUsernameInLogs:u}),onSuccess:async()=>{r(null),await n.invalidateQueries({queryKey:N.instance.generalSettings})},onError:u=>{r(u instanceof Error?u.message:"Failed to update general settings.")}});if(a.isLoading)return e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading general settings..."});if(a.error)return e.jsx("div",{className:"text-sm text-destructive",children:a.error instanceof Error?a.error.message:"Failed to load general settings."});const i=((l=a.data)==null?void 0:l.censorUsernameInLogs)===!0;return e.jsxs("div",{className:"max-w-4xl space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rl,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h1",{className:"text-lg font-semibold",children:"General"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure instance-wide defaults that affect how operator-visible logs are displayed."})]}),s&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:s}),e.jsx("section",{className:"rounded-xl border border-border bg-card p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Censor username in logs"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Hide the username segment in home-directory paths and similar operator-visible log output. Standalone username mentions outside of paths are not yet masked in the live transcript view. This is off by default."})]}),e.jsx("button",{type:"button","data-slot":"toggle","aria-label":"Toggle username log censoring",disabled:o.isPending,className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-60",i?"bg-green-600":"bg-muted"),onClick:()=>o.mutate(!i),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",i?"translate-x-4.5":"translate-x-0.5")})})]})})]})}function mc(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function XK(t){return t.replaceAll("_"," ")}function hb(t){return`/${t.companyIssuePrefix}/agents/${encodeURIComponent(t.agentUrlKey)}`}function ez(){const{setBreadcrumbs:t}=Ft(),n=at(),[s,r]=c.useState(null);c.useEffect(()=>{t([{label:"Instance Settings"},{label:"Heartbeats"}])},[t]);const a=oe({queryKey:N.instance.schedulerHeartbeats,queryFn:()=>Yt.listInstanceSchedulerAgents(),refetchInterval:15e3}),o=ge({mutationFn:async f=>{const h=await We.get(f.id,f.companyId),j=mc(h.runtimeConfig)??{},b=mc(j.heartbeat)??{};return We.update(f.id,{runtimeConfig:{...j,heartbeat:{...b,enabled:!f.heartbeatEnabled}}},f.companyId)},onSuccess:async(f,h)=>{r(null),await Promise.all([n.invalidateQueries({queryKey:N.instance.schedulerHeartbeats}),n.invalidateQueries({queryKey:N.agents.list(h.companyId)}),n.invalidateQueries({queryKey:N.agents.detail(h.id)})])},onError:f=>{r(f instanceof Error?f.message:"Failed to update heartbeat.")}}),i=ge({mutationFn:async f=>{var g;const h=f.filter(y=>y.heartbeatEnabled);if(h.length===0)return h;const b=(await Promise.allSettled(h.map(async y=>{const v=await We.get(y.id,y.companyId),_=mc(v.runtimeConfig)??{},E=mc(_.heartbeat)??{};await We.update(y.id,{runtimeConfig:{..._,heartbeat:{...E,enabled:!1}}},y.companyId)}))).filter(y=>y.status==="rejected");if(b.length>0){const y=(g=b[0])==null?void 0:g.reason,v=y instanceof Error?y.message:"Unknown error";throw new Error(b.length===1?`Failed to disable 1 timer heartbeat: ${v}`:`Failed to disable ${b.length} of ${h.length} timer heartbeats. First error: ${v}`)}return h},onSuccess:async f=>{r(null);const h=new Set(f.map(j=>j.companyId));await Promise.all([n.invalidateQueries({queryKey:N.instance.schedulerHeartbeats}),...Array.from(h,j=>n.invalidateQueries({queryKey:N.agents.list(j)})),...f.map(j=>n.invalidateQueries({queryKey:N.agents.detail(j.id)}))])},onError:f=>{r(f instanceof Error?f.message:"Failed to disable all heartbeats.")}}),l=a.data??[],u=l.filter(f=>f.schedulerActive).length,d=l.length-u,m=l.filter(f=>f.heartbeatEnabled).length,p=m>0,x=c.useMemo(()=>{const f=new Map;for(const h of l){let j=f.get(h.companyId);j||(j={companyName:h.companyName,agents:[]},f.set(h.companyId,j)),j.agents.push(h)}return[...f.values()]},[l]);return a.isLoading?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading scheduler heartbeats..."}):a.error?e.jsx("div",{className:"text-sm text-destructive",children:a.error instanceof Error?a.error.message:"Failed to load scheduler heartbeats."}):e.jsxs("div",{className:"max-w-5xl space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h1",{className:"text-lg font-semibold",children:"Scheduler Heartbeats"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Agents with a timer heartbeat enabled across all of your companies."})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:u})," active"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:d})," disabled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:x.length})," ",x.length===1?"company":"companies"]}),p&&e.jsx(G,{variant:"destructive",size:"sm",className:"ml-auto h-7 text-xs",disabled:i.isPending,onClick:()=>{const f=m===1?"agent":"agents";window.confirm(`Disable timer heartbeats for all ${m} enabled ${f}?`)&&i.mutate(l)},children:i.isPending?"Disabling...":"Disable All"})]}),s&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:s}),l.length===0?e.jsx(tn,{icon:Nl,message:"No scheduler heartbeats match the current criteria."}):e.jsx("div",{className:"space-y-4",children:x.map(f=>e.jsx(jn,{children:e.jsxs(wn,{className:"p-0",children:[e.jsx("div",{className:"border-b px-3 py-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:f.companyName}),e.jsx("div",{className:"divide-y",children:f.agents.map(h=>{var b;const j=o.isPending&&((b=o.variables)==null?void 0:b.id)===h.id;return e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[e.jsx(Wt,{variant:h.schedulerActive?"default":"outline",className:"shrink-0 text-[10px] px-1.5 py-0",children:h.schedulerActive?"On":"Off"}),e.jsx(Oe,{to:hb(h),className:"font-medium truncate hover:underline",children:h.agentName}),e.jsx("span",{className:"hidden sm:inline text-muted-foreground truncate",children:XK(h.title??h.role)}),e.jsxs("span",{className:"text-muted-foreground tabular-nums shrink-0",children:[h.intervalSec,"s"]}),e.jsx("span",{className:"hidden md:inline text-muted-foreground truncate",title:h.lastHeartbeatAt?js(h.lastHeartbeatAt):void 0,children:h.lastHeartbeatAt?os(h.lastHeartbeatAt):"never"}),e.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.jsx(Oe,{to:hb(h),className:"text-muted-foreground hover:text-foreground",title:"Full agent config",children:e.jsx(Is,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:j,onClick:()=>o.mutate(h),children:j?"...":h.heartbeatEnabled?"Disable Timer Heartbeat":"Enable Timer Heartbeat"})]})]},h.id)})})]})},f.companyName))})]})}function tz(){var u,d;const{setBreadcrumbs:t}=Ft(),n=at(),[s,r]=c.useState(null);c.useEffect(()=>{t([{label:"Instance Settings"},{label:"Experimental"}])},[t]);const a=oe({queryKey:N.instance.experimentalSettings,queryFn:()=>Rr.getExperimental()}),o=ge({mutationFn:async m=>Rr.updateExperimental(m),onSuccess:async()=>{r(null),await Promise.all([n.invalidateQueries({queryKey:N.instance.experimentalSettings}),n.invalidateQueries({queryKey:N.health})])},onError:m=>{r(m instanceof Error?m.message:"Failed to update experimental settings.")}});if(a.isLoading)return e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading experimental settings..."});if(a.error)return e.jsx("div",{className:"text-sm text-destructive",children:a.error instanceof Error?a.error.message:"Failed to load experimental settings."});const i=((u=a.data)==null?void 0:u.enableIsolatedWorkspaces)===!0,l=((d=a.data)==null?void 0:d.autoRestartDevServerWhenIdle)===!0;return e.jsxs("div",{className:"max-w-4xl space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h1",{className:"text-lg font-semibold",children:"Experimental"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Opt into features that are still being evaluated before they become default behavior."})]}),s&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:s}),e.jsx("section",{className:"rounded-xl border border-border bg-card p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Enable Isolated Workspaces"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Show execution workspace controls in project configuration and allow isolated workspace behavior for new and existing issue runs."})]}),e.jsx("button",{type:"button","data-slot":"toggle","aria-label":"Toggle isolated workspaces experimental setting",disabled:o.isPending,className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-60",i?"bg-green-600":"bg-muted"),onClick:()=>o.mutate({enableIsolatedWorkspaces:!i}),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",i?"translate-x-4.5":"translate-x-0.5")})})]})}),e.jsx("section",{className:"rounded-xl border border-border bg-card p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Auto-Restart Dev Server When Idle"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"In `pnpm dev:once`, wait for all queued and running local agent runs to finish, then restart the server automatically when backend changes or migrations make the current boot stale."})]}),e.jsx("button",{type:"button","data-slot":"toggle","aria-label":"Toggle guarded dev-server auto-restart",disabled:o.isPending,className:O("relative inline-flex h-5 w-9 items-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-60",l?"bg-green-600":"bg-muted"),onClick:()=>o.mutate({autoRestartDevServerWhenIdle:!l}),children:e.jsx("span",{className:O("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",l?"translate-x-4.5":"translate-x-0.5")})})]})})]})}function nz(t){return t?t.split(/\r?\n/).map(s=>s.trim()).find(Boolean)??null:null}function gb(t){return nz(t.lastError)??"Plugin entered an error state without a stored error message."}function sz(){const{selectedCompany:t}=et(),{setBreadcrumbs:n}=Ft(),s=at(),{pushToast:r}=ds(),[a,o]=c.useState(""),[i,l]=c.useState(!1),[u,d]=c.useState(null),[m,p]=c.useState(""),[x,f]=c.useState(null);c.useEffect(()=>{n([{label:(t==null?void 0:t.name)??"Company",href:"/dashboard"},{label:"Settings",href:"/instance/settings/heartbeats"},{label:"Plugins"}])},[t==null?void 0:t.name,n]);const{data:h,isLoading:j,error:b}=oe({queryKey:N.plugins.all,queryFn:()=>Mn.list()}),g=oe({queryKey:N.plugins.examples,queryFn:()=>Mn.listExamples()}),y=()=>{s.invalidateQueries({queryKey:N.plugins.all}),s.invalidateQueries({queryKey:N.plugins.examples}),s.invalidateQueries({queryKey:N.plugins.uiContributions})},v=ge({mutationFn:C=>Mn.install(C),onSuccess:()=>{y(),l(!1),o(""),r({title:"Plugin installed successfully",tone:"success"})},onError:C=>{r({title:"Failed to install plugin",body:C.message,tone:"error"})}}),_=ge({mutationFn:C=>Mn.uninstall(C),onSuccess:()=>{y(),r({title:"Plugin uninstalled successfully",tone:"success"})},onError:C=>{r({title:"Failed to uninstall plugin",body:C.message,tone:"error"})}}),E=ge({mutationFn:C=>Mn.enable(C),onSuccess:()=>{y(),r({title:"Plugin enabled",tone:"success"})},onError:C=>{r({title:"Failed to enable plugin",body:C.message,tone:"error"})}}),S=ge({mutationFn:C=>Mn.disable(C),onSuccess:()=>{y(),r({title:"Plugin disabled",tone:"info"})},onError:C=>{r({title:"Failed to disable plugin",body:C.message,tone:"error"})}}),M=h??[],B=g.data??[],k=new Map(M.map(C=>[C.packageName,C])),L=new Set(B.map(C=>C.packageName)),$=c.useMemo(()=>new Map(M.map(C=>[C.id,gb(C)])),[M]);return j?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugins..."}):b?e.jsx("div",{className:"p-4 text-sm text-destructive",children:"Failed to load plugins."}):e.jsxs("div",{className:"space-y-6 max-w-5xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("h1",{className:"text-xl font-semibold",children:"Plugin Manager"})]}),e.jsxs(Cs,{open:i,onOpenChange:l,children:[e.jsx(S0,{asChild:!0,children:e.jsxs(G,{size:"sm",className:"gap-2",children:[e.jsx(Ot,{className:"h-4 w-4"}),"Install Plugin"]})}),e.jsxs(Fs,{children:[e.jsxs(fa,{children:[e.jsx(ha,{children:"Install Plugin"}),e.jsx(ga,{children:"Enter the npm package name of the plugin you wish to install."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(En,{htmlFor:"packageName",children:"npm Package Name"}),e.jsx(Xt,{id:"packageName",placeholder:"@crewspaceai/plugin-example",value:a,onChange:C=>o(C.target.value)})]})}),e.jsxs(Ho,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>v.mutate({packageName:a}),disabled:!a||v.isPending,children:v.isPending?"Installing...":"Install"})]})]})]})]}),e.jsx("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ir,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Plugins are alpha."}),e.jsx("p",{className:"text-muted-foreground",children:"The plugin runtime and API surface are still changing. Expect breaking changes while this feature settles."})]})]})}),e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold",children:"Available Plugins"}),e.jsx(Wt,{variant:"outline",children:"Examples"})]}),g.isLoading?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading bundled examples..."}):g.error?e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load bundled examples."}):B.length===0?e.jsx("div",{className:"rounded-md border border-dashed px-4 py-3 text-sm text-muted-foreground",children:"No bundled example plugins were found in this checkout."}):e.jsx("ul",{className:"divide-y rounded-md border bg-card",children:B.map(C=>{var T;const I=k.get(C.packageName),K=v.isPending&&((T=v.variables)==null?void 0:T.isLocalPath)&&v.variables.packageName===C.localPath;return e.jsx("li",{children:e.jsxs("div",{className:"flex items-center gap-4 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:C.displayName}),e.jsx(Wt,{variant:"outline",children:"Example"}),I?e.jsx(Wt,{variant:I.status==="ready"?"default":"secondary",className:I.status==="ready"?"bg-green-600 hover:bg-green-700":"",children:I.status}):e.jsx(Wt,{variant:"secondary",children:"Not installed"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:C.description}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:C.packageName})]}),e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:I?e.jsxs(e.Fragment,{children:[I.status!=="ready"&&e.jsx(G,{variant:"outline",size:"sm",disabled:E.isPending,onClick:()=>E.mutate(I.id),children:"Enable"}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(Oe,{to:`/instance/settings/plugins/${I.id}`,children:I.status==="ready"?"Open Settings":"Review"})})]}):e.jsx(G,{size:"sm",disabled:K||v.isPending,onClick:()=>v.mutate({packageName:C.localPath,isLocalPath:!0}),children:K?"Installing...":"Install Example"})})]})},C.packageName)})})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold",children:"Installed Plugins"})]}),M.length?e.jsx("ul",{className:"divide-y rounded-md border bg-card",children:M.map(C=>e.jsx("li",{children:e.jsxs("div",{className:"flex items-start gap-4 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Oe,{to:`/instance/settings/plugins/${C.id}`,className:"font-medium hover:underline truncate block",title:C.manifestJson.displayName??C.packageName,children:C.manifestJson.displayName??C.packageName}),L.has(C.packageName)&&e.jsx(Wt,{variant:"outline",children:"Example"})]}),e.jsx("div",{children:e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",title:C.packageName,children:[C.packageName," · v",C.manifestJson.version??C.version]})}),e.jsx("p",{className:"text-sm text-muted-foreground truncate mt-0.5",title:C.manifestJson.description,children:C.manifestJson.description||"No description provided."}),C.status==="error"&&e.jsx("div",{className:"mt-3 rounded-md border border-red-500/25 bg-red-500/[0.06] px-3 py-2",children:e.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-red-700 dark:text-red-300",children:[e.jsx(ir,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:"Plugin error"})]}),e.jsx("p",{className:"mt-1 text-sm text-red-700/90 dark:text-red-200/90 break-words",title:C.lastError??void 0,children:$.get(C.id)})]}),e.jsx(G,{variant:"outline",size:"sm",className:"border-red-500/30 bg-background/60 text-red-700 hover:bg-red-500/10 hover:text-red-800 dark:text-red-200 dark:hover:text-red-100",onClick:()=>f(C),children:"View full error"})]})})]}),e.jsx("div",{className:"flex shrink-0 self-center",children:e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{variant:C.status==="ready"?"default":C.status==="error"?"destructive":"secondary",className:O("shrink-0",C.status==="ready"?"bg-green-600 hover:bg-green-700":""),children:C.status}),e.jsx(G,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:C.status==="ready"?"Disable":"Enable",onClick:()=>{C.status==="ready"?S.mutate(C.id):E.mutate(C.id)},disabled:E.isPending||S.isPending,children:e.jsx($1,{className:O("h-4 w-4",C.status==="ready"?"text-green-600":"")})}),e.jsx(G,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Uninstall",onClick:()=>{d(C.id),p(C.manifestJson.displayName??C.packageName)},disabled:_.isPending,children:e.jsx(D1,{className:"h-4 w-4"})})]}),e.jsx(G,{variant:"outline",size:"sm",className:"mt-2 h-8",asChild:!0,children:e.jsxs(Oe,{to:`/instance/settings/plugins/${C.id}`,children:[e.jsx(zr,{className:"h-4 w-4"}),"Configure"]})})]})})]})},C.id))}):e.jsx(jn,{className:"bg-muted/30",children:e.jsxs(wn,{className:"flex flex-col items-center justify-center py-10",children:[e.jsx(Bo,{className:"h-10 w-10 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm font-medium",children:"No plugins installed"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Install a plugin to extend functionality."})]})})]}),e.jsx(Cs,{open:u!==null,onOpenChange:C=>{C||d(null)},children:e.jsxs(Fs,{children:[e.jsxs(fa,{children:[e.jsx(ha,{children:"Uninstall Plugin"}),e.jsxs(ga,{children:["Are you sure you want to uninstall ",e.jsx("strong",{children:m}),"? This action cannot be undone."]})]}),e.jsxs(Ho,{children:[e.jsx(G,{variant:"outline",onClick:()=>d(null),children:"Cancel"}),e.jsx(G,{variant:"destructive",disabled:_.isPending,onClick:()=>{u&&_.mutate(u,{onSettled:()=>d(null)})},children:_.isPending?"Uninstalling...":"Uninstall"})]})]})}),e.jsx(Cs,{open:x!==null,onOpenChange:C=>{C||f(null)},children:e.jsxs(Fs,{className:"sm:max-w-2xl",children:[e.jsxs(fa,{children:[e.jsx(ha,{children:"Error Details"}),e.jsxs(ga,{children:[(x==null?void 0:x.manifestJson.displayName)??(x==null?void 0:x.packageName)??"Plugin"," hit an error state."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-md border border-red-500/25 bg-red-500/[0.06] px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ir,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-700 dark:text-red-300"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsx("p",{className:"font-medium text-red-700 dark:text-red-300",children:"What errored"}),e.jsx("p",{className:"text-red-700/90 dark:text-red-200/90 break-words",children:x?gb(x):"No error summary available."})]})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Full error output"}),e.jsx("pre",{className:"max-h-[50vh] overflow-auto rounded-md border bg-muted/40 p-3 text-xs leading-5 whitespace-pre-wrap break-words",children:(x==null?void 0:x.lastError)??"No stored error message."})]})]}),e.jsx(Ho,{children:e.jsx(G,{variant:"outline",onClick:()=>f(null),children:"Close"})})]})})]})}const rz=200;function mo(t){return t.enum?"enum":t.const!==void 0?"const":t.format==="secret-ref"?"secret-ref":Array.isArray(t.type)?t.type.find(n=>n!=="null")??"string":t.type??"string"}function az(t,n){return n.title?n.title:t.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function mf(t){var s;if(t.default!==void 0)return t.default;switch(mo(t)){case"string":case"secret-ref":return"";case"number":case"integer":return t.minimum??0;case"boolean":return!1;case"enum":return((s=t.enum)==null?void 0:s[0])??"";case"array":return[];case"object":{if(!t.properties)return{};const r={};for(const[a,o]of Object.entries(t.properties))r[a]=mf(o);return r}default:return""}}function bb(t,n,s){const r=mo(n);if(s&&(t==null||t===""))return"This field is required";if(t==null||t==="")return null;if(r==="string"||r==="secret-ref"){const a=String(t);if(n.minLength!=null&&a.length<n.minLength)return`Must be at least ${n.minLength} characters`;if(n.maxLength!=null&&a.length>n.maxLength)return`Must be at most ${n.maxLength} characters`;if(n.pattern&&n.pattern.length<=512)try{if(!new RegExp(n.pattern).test(a))return`Must match pattern: ${n.pattern}`}catch{}}if(r==="number"||r==="integer"){const a=Number(t);if(isNaN(a))return"Must be a valid number";if(n.minimum!=null&&a<n.minimum)return`Must be at least ${n.minimum}`;if(n.maximum!=null&&a>n.maximum)return`Must be at most ${n.maximum}`;if(n.exclusiveMinimum!=null&&a<=n.exclusiveMinimum)return`Must be greater than ${n.exclusiveMinimum}`;if(n.exclusiveMaximum!=null&&a>=n.exclusiveMaximum)return`Must be less than ${n.exclusiveMaximum}`;if(r==="integer"&&!Number.isInteger(a))return"Must be a whole number";if(n.multipleOf!=null&&a%n.multipleOf!==0)return`Must be a multiple of ${n.multipleOf}`}if(r==="array"){const a=t;if(n.minItems!=null&&a.length<n.minItems)return`Must have at least ${n.minItems} items`;if(n.maxItems!=null&&a.length>n.maxItems)return`Must have at most ${n.maxItems} items`}return null}function hd(t,n,s=[]){const r={},a=t.properties??{},o=new Set(t.required??[]);for(const[i,l]of Object.entries(a)){const u=[...s,i],d=`/${u.join("/")}`,m=n[i],p=o.has(i),x=mo(l),f=bb(m,l,p);if(f&&(r[d]=f),x==="object"&&l.properties&&typeof m=="object"&&m!==null&&Object.assign(r,hd(l,m,u)),x==="array"&&l.items&&Array.isArray(m)){const h=l.items,j=mo(h)==="object";m.forEach((b,g)=>{const y=[...u,String(g)],v=`/${y.join("/")}`;if(j)Object.assign(r,hd(h,b,y));else{const _=bb(b,h,!1);_&&(r[v]=_)}})}}return r}function pm(t){const n={},s=t.properties??{};for(const[r,a]of Object.entries(s)){const o=mf(a);o!==void 0&&(n[r]=o)}return n}const Ul=Bt.memo(({label:t,description:n,required:s,error:r,disabled:a,children:o})=>e.jsxs("div",{className:O("space-y-2",a&&"opacity-60"),children:[e.jsx("div",{className:"flex items-center justify-between",children:t&&e.jsxs(En,{className:"text-sm font-medium",children:[t,s&&e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]})}),o,n&&e.jsx("p",{className:"text-[12px] text-muted-foreground leading-relaxed",children:n}),r&&e.jsx("p",{className:"text-[12px] font-medium text-destructive",children:r})]}));Ul.displayName="FieldWrapper";const zN=Bt.memo(({id:t,value:n,onChange:s,disabled:r,label:a,isRequired:o,description:i,error:l})=>e.jsxs("div",{className:"flex items-start space-x-3 space-y-0",children:[e.jsx(Gs,{id:t,checked:!!n,onCheckedChange:s,disabled:r}),e.jsxs("div",{className:"grid gap-1.5 leading-none",children:[a&&e.jsxs(En,{htmlFor:t,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:[a,o&&e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),i&&e.jsx("p",{className:"text-xs text-muted-foreground",children:i}),l&&e.jsx("p",{className:"text-xs font-medium text-destructive",children:l})]})]}));zN.displayName="BooleanField";const WN=Bt.memo(({value:t,onChange:n,disabled:s,label:r,isRequired:a,description:o,error:i,options:l})=>e.jsx(Ul,{label:r,description:o,required:a,error:i,disabled:s,children:e.jsxs(Hn,{value:String(t??""),onValueChange:n,disabled:s,children:[e.jsx(Qn,{className:"w-full",children:e.jsx(Vn,{placeholder:"Select an option"})}),e.jsx(Gn,{children:l.map(u=>e.jsx(Mt,{value:String(u),children:String(u)},String(u)))})]})}));WN.displayName="EnumField";const HN=Bt.memo(({value:t,onChange:n,disabled:s,label:r,isRequired:a,description:o,error:i,defaultValue:l})=>{const[u,d]=c.useState(!1);return e.jsx(Ul,{label:r,description:o||"This secret is stored securely via the CrewSpace secret provider.",required:a,error:i,disabled:s,children:e.jsxs("div",{className:"relative",children:[e.jsx(Xt,{type:u?"text":"password",value:String(t??""),onChange:m=>n(m.target.value),placeholder:String(l??""),disabled:s,className:"pr-10","aria-invalid":!!i}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>d(!u),disabled:s,children:[u?e.jsx(al,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(pi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"sr-only",children:u?"Hide secret":"Show secret"})]})]})})});HN.displayName="SecretField";const VN=Bt.memo(({value:t,onChange:n,disabled:s,label:r,isRequired:a,description:o,error:i,defaultValue:l,type:u})=>e.jsx(Ul,{label:r,description:o,required:a,error:i,disabled:s,children:e.jsx(Xt,{type:"number",step:u==="integer"?"1":"any",value:t!==void 0?String(t):"",onChange:d=>{const m=d.target.value;n(m===""?void 0:Number(m))},placeholder:String(l??""),disabled:s,"aria-invalid":!!i})}));VN.displayName="NumberField";const QN=Bt.memo(({value:t,onChange:n,disabled:s,label:r,isRequired:a,description:o,error:i,defaultValue:l,format:u,maxLength:d})=>{const m=u==="textarea"||d&&d>rz;return e.jsx(Ul,{label:r,description:o,required:a,error:i,disabled:s,children:m?e.jsx(Ur,{value:String(t??""),onChange:p=>n(p.target.value),placeholder:String(l??""),disabled:s,className:"min-h-[100px]","aria-invalid":!!i}):e.jsx(Xt,{type:"text",value:String(t??""),onChange:p=>n(p.target.value),placeholder:String(l??""),disabled:s,"aria-invalid":!!i})})});QN.displayName="StringField";const GN=Bt.memo(({propSchema:t,value:n,onChange:s,error:r,disabled:a,label:o,errors:i,path:l})=>{const u=Array.isArray(n)?n:[],d=t.items,m=mo(d)==="object";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(En,{className:"text-sm font-medium",children:o}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description})]}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",disabled:a||t.maxItems!==void 0&&u.length>=t.maxItems,onClick:()=>{const p=mf(d);s([...u,p])},children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),m?"Add item":"Add"]})]}),e.jsxs("div",{className:"space-y-3",children:[u.map((p,x)=>e.jsxs("div",{className:"group relative flex items-start space-x-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Item ",x+1]}),e.jsx(gd,{propSchema:d,value:p,label:"",path:`${l}/${x}`,onChange:f=>{const h=[...u];h[x]=f,s(h)},disabled:a,errors:i})]}),e.jsxs(G,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",disabled:a||t.minItems!==void 0&&u.length<=t.minItems,onClick:()=>{const f=[...u];f.splice(x,1),s(f)},children:[e.jsx(Ls,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Remove item"})]})]},x)),u.length===0&&e.jsx("div",{className:"rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground",children:"No items added yet."})]}),r&&e.jsx("p",{className:"text-xs font-medium text-destructive",children:r})]})});GN.displayName="ArrayField";const JN=Bt.memo(({propSchema:t,value:n,onChange:s,disabled:r,label:a,errors:o,path:i})=>{const[l,u]=c.useState(!1),d=m=>{s(m)};return e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between",onClick:()=>u(!l),children:[e.jsxs("div",{className:"text-left",children:[e.jsx(En,{className:"cursor-pointer text-sm font-semibold",children:a}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description})]}),l?e.jsx(sn,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"})]}),!l&&e.jsx("div",{className:"pt-2",children:e.jsx(ZN,{schema:t,values:n??{},onChange:d,disabled:r,errors:Object.fromEntries(Object.entries(o).filter(([m])=>m.startsWith(`${i}/`)).map(([m,p])=>[m.replace(i,""),p]))})})]})});JN.displayName="ObjectField";const gd=Bt.memo(({propSchema:t,value:n,onChange:s,error:r,disabled:a,label:o,isRequired:i,errors:l,path:u})=>{const d=mo(t),m=a||t.readOnly===!0;switch(d){case"boolean":return e.jsx(zN,{id:u,value:n,onChange:s,disabled:m,label:o,isRequired:i,description:t.description,error:r});case"enum":return e.jsx(WN,{value:n,onChange:s,disabled:m,label:o,isRequired:i,description:t.description,error:r,options:t.enum??[]});case"secret-ref":return e.jsx(HN,{value:n,onChange:s,disabled:m,label:o,isRequired:i,description:t.description,error:r,defaultValue:t.default});case"number":case"integer":return e.jsx(VN,{value:n,onChange:s,disabled:m,label:o,isRequired:i,description:t.description,error:r,defaultValue:t.default,type:d});case"array":return e.jsx(GN,{propSchema:t,value:n,onChange:s,error:r,disabled:m,label:o,errors:l,path:u});case"object":return e.jsx(JN,{propSchema:t,value:n,onChange:s,disabled:m,label:o,errors:l,path:u});default:return e.jsx(QN,{value:n,onChange:s,disabled:m,label:o,isRequired:i,description:t.description,error:r,defaultValue:t.default,format:t.format,maxLength:t.maxLength})}});gd.displayName="FormField";function ZN({schema:t,values:n,onChange:s,errors:r={},disabled:a,className:o}){const i=mo(t),l=c.useCallback(p=>{s(p)},[s]);if(i!=="object")return e.jsx("div",{className:o,children:e.jsx(gd,{propSchema:t,value:n,label:"",path:"",onChange:l,disabled:a,errors:r})});const u=c.useMemo(()=>t.properties??{},[t.properties]),d=c.useMemo(()=>new Set(t.required??[]),[t.required]),m=c.useCallback((p,x)=>{s({...n,[p]:x})},[s,n]);return Object.keys(u).length===0?e.jsx("div",{className:O("py-4 text-center text-sm text-muted-foreground",o),children:"No configuration options available."}):e.jsx("div",{className:O("space-y-6",o),children:Object.entries(u).map(([p,x])=>{const f=n[p],h=d.has(p),j=r[`/${p}`],b=az(p,x),g=`/${p}`;return e.jsx(gd,{propSchema:x,value:f,onChange:y=>m(p,y),error:j,disabled:a,label:b,isRequired:h,errors:r,path:g},p)})})}function oz(){var B;const{selectedCompany:t,selectedCompanyId:n}=et(),{setBreadcrumbs:s}=Ft(),{companyPrefix:r,pluginId:a}=Xn(),[o,i]=c.useState("configuration"),{data:l,isLoading:u}=oe({queryKey:N.plugins.detail(a),queryFn:()=>Mn.get(a),enabled:!!a}),{data:d,isLoading:m}=oe({queryKey:N.plugins.health(a),queryFn:()=>Mn.health(a),enabled:!!a&&(l==null?void 0:l.status)==="ready",refetchInterval:3e4}),{data:p}=oe({queryKey:N.plugins.dashboard(a),queryFn:()=>Mn.dashboard(a),enabled:!!a,refetchInterval:3e4}),{data:x}=oe({queryKey:N.plugins.logs(a),queryFn:()=>Mn.logs(a,{limit:50}),enabled:!!a&&(l==null?void 0:l.status)==="ready",refetchInterval:3e4}),f=(B=l==null?void 0:l.manifestJson)==null?void 0:B.instanceConfigSchema,h=f&&f.properties&&Object.keys(f.properties).length>0,{data:j,isLoading:b}=oe({queryKey:N.plugins.config(a),queryFn:()=>Mn.getConfig(a),enabled:!!a&&!!h}),{slots:g}=yi({slotTypes:["settingsPage"],enabled:!!n}),y=g.filter(k=>k.pluginId===a),v=y.length>0;if(c.useEffect(()=>{var k;s([{label:(t==null?void 0:t.name)??"Company",href:"/dashboard"},{label:"Settings",href:"/instance/settings/heartbeats"},{label:"Plugins",href:"/instance/settings/plugins"},{label:((k=l==null?void 0:l.manifestJson)==null?void 0:k.displayName)??(l==null?void 0:l.packageName)??"Plugin Details"}])},[t==null?void 0:t.name,s,r,l]),c.useEffect(()=>{i("configuration")},[a]),u)return e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugin details..."});if(!l)return e.jsx(Zt,{to:"/instance/settings/plugins",replace:!0});const _=l.status,E=l.status==="ready"?"default":l.status==="error"?"destructive":"secondary",S=l.manifestJson.description||"No description provided.",M=l.manifestJson.capabilities??[];return e.jsxs("div",{className:"space-y-6 max-w-5xl",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Oe,{to:"/instance/settings/plugins",children:e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",children:e.jsx(fo,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("h1",{className:"text-xl font-semibold",children:l.manifestJson.displayName??l.packageName}),e.jsx(Wt,{variant:E,className:"ml-2",children:_}),e.jsxs(Wt,{variant:"outline",className:"ml-1",children:["v",l.manifestJson.version??l.version]})]})]}),e.jsxs(Ss,{value:o,onValueChange:k=>i(k),className:"space-y-6",children:[e.jsx(Ca,{align:"start",items:[{value:"configuration",label:"Configuration"},{value:"status",label:"Status"}],value:o,onValueChange:k=>i(k)}),e.jsx(on,{value:"configuration",className:"space-y-6",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-5",children:[e.jsx("h2",{className:"text-base font-semibold",children:"About"}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-[minmax(0,1.4fr)_minmax(220px,0.8fr)]",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Description"}),e.jsx("p",{className:"text-sm leading-6 text-foreground/90",children:S})]}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h3",{className:"font-medium text-muted-foreground",children:"Author"}),e.jsx("p",{className:"text-foreground",children:l.manifestJson.author})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-medium text-muted-foreground",children:"Categories"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.categories.length>0?l.categories.map(k=>e.jsx(Wt,{variant:"outline",className:"capitalize",children:k},k)):e.jsx("span",{className:"text-foreground",children:"None"})})]})]})]})]}),e.jsx(yn,{}),e.jsxs("section",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h2",{className:"text-base font-semibold",children:"Settings"})}),v?e.jsx("div",{className:"space-y-3",children:y.map(k=>e.jsx(vi,{slot:k,context:{companyId:n,companyPrefix:r??null},missingBehavior:"placeholder"},`${k.pluginKey}:${k.id}`))}):h?e.jsx(iz,{pluginId:a,schema:f,initialValues:j==null?void 0:j.configJson,isLoading:b,pluginStatus:l.status,supportsConfigTest:l.supportsConfigTest===!0}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This plugin does not require any settings."})]})]})}),e.jsx(on,{value:"status",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_320px]",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(jn,{children:[e.jsxs(qn,{children:[e.jsxs(Un,{className:"text-base flex items-center gap-1.5",children:[e.jsx(gm,{className:"h-4 w-4"}),"Runtime Dashboard"]}),e.jsx(cs,{children:"Worker process, scheduled jobs, and webhook deliveries"})]}),e.jsx(wn,{className:"space-y-6",children:p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[e.jsx(gm,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Worker Process"]}),p.worker?e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx(Wt,{variant:p.worker.status==="running"?"default":"secondary",children:p.worker.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"PID"}),e.jsx("span",{className:"font-mono text-xs",children:p.worker.pid??"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Uptime"}),e.jsx("span",{className:"text-xs",children:lz(p.worker.uptime)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Pending RPCs"}),e.jsx("span",{className:"text-xs",children:p.worker.pendingRequests})]}),p.worker.totalCrashes>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between col-span-2",children:[e.jsxs("span",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ir,{className:"h-3 w-3 text-amber-500"}),"Crashes"]}),e.jsxs("span",{className:"text-xs",children:[p.worker.consecutiveCrashes," consecutive / ",p.worker.totalCrashes," total"]})]}),p.worker.lastCrashAt&&e.jsxs("div",{className:"flex justify-between col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Last Crash"}),e.jsx("span",{className:"text-xs",children:cz(p.worker.lastCrashAt)})]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No worker process registered."})]}),e.jsx(yn,{}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[e.jsx(O1,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Job Runs"]}),p.recentJobRuns.length>0?e.jsx("div",{className:"space-y-2",children:p.recentJobRuns.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(dz,{status:k.status}),e.jsx("span",{className:"truncate font-mono text-xs",title:k.jobKey??k.jobId,children:k.jobKey??k.jobId.slice(0,8)}),e.jsx(Wt,{variant:"outline",className:"px-1 py-0 text-[10px]",children:k.trigger})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[k.durationMs!=null?e.jsx("span",{children:yb(k.durationMs)}):null,e.jsx("span",{title:k.createdAt,children:vb(k.createdAt)})]})]},k.id))}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No job runs recorded yet."})]}),e.jsx(yn,{}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[e.jsx(ry,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Webhook Deliveries"]}),p.recentWebhookDeliveries.length>0?e.jsx("div",{className:"space-y-2",children:p.recentWebhookDeliveries.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(uz,{status:k.status}),e.jsx("span",{className:"truncate font-mono text-xs",title:k.webhookKey,children:k.webhookKey})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[k.durationMs!=null?e.jsx("span",{children:yb(k.durationMs)}):null,e.jsx("span",{title:k.createdAt,children:vb(k.createdAt)})]})]},k.id))}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No webhook deliveries recorded yet."})]}),e.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border/50 pt-2 text-xs text-muted-foreground",children:[e.jsx(_r,{className:"h-3 w-3"}),"Last checked: ",new Date(p.checkedAt).toLocaleTimeString()]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Runtime diagnostics are unavailable right now."})})]}),x&&x.length>0?e.jsxs(jn,{children:[e.jsxs(qn,{children:[e.jsxs(Un,{className:"text-base flex items-center gap-1.5",children:[e.jsx(Nf,{className:"h-4 w-4"}),"Recent Logs"]}),e.jsxs(cs,{children:["Last ",x.length," log entries"]})]}),e.jsx(wn,{children:e.jsx("div",{className:"max-h-64 space-y-1 overflow-y-auto font-mono text-xs",children:x.map(k=>e.jsxs("div",{className:`flex gap-2 py-0.5 ${k.level==="error"?"text-destructive":k.level==="warn"?"text-yellow-600 dark:text-yellow-400":k.level==="debug"?"text-muted-foreground/60":"text-muted-foreground"}`,children:[e.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:new Date(k.createdAt).toLocaleTimeString()}),e.jsx(Wt,{variant:"outline",className:"h-4 shrink-0 px-1 text-[10px]",children:k.level}),e.jsx("span",{className:"truncate",title:k.message,children:k.message})]},k.id))})})]}):null]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(jn,{children:[e.jsx(qn,{children:e.jsxs(Un,{className:"text-base flex items-center gap-1.5",children:[e.jsx(Nf,{className:"h-4 w-4"}),"Health Status"]})}),e.jsx(wn,{children:m?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Checking health..."}):d?e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Overall"}),e.jsx(Wt,{variant:d.healthy?"default":"destructive",children:d.status})]}),d.checks.length>0?e.jsx("div",{className:"space-y-2 border-t border-border/50 pt-2",children:d.checks.map((k,L)=>e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"truncate text-muted-foreground",title:k.name,children:k.name}),k.passed?e.jsx(L1,{className:"h-4 w-4 shrink-0 text-green-500"}):e.jsx(fi,{className:"h-4 w-4 shrink-0 text-destructive"})]},L))}):null,d.lastError?e.jsx("div",{className:"break-words rounded border border-destructive/20 bg-destructive/10 p-2 text-xs text-destructive",children:d.lastError}):null]}):e.jsxs("div",{className:"space-y-3 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Lifecycle"}),e.jsx(Wt,{variant:E,children:_})]}),e.jsx("p",{children:"Health checks run once the plugin is ready."}),l.lastError?e.jsx("div",{className:"break-words rounded border border-destructive/20 bg-destructive/10 p-2 text-xs text-destructive",children:l.lastError}):null]})})]}),e.jsxs(jn,{children:[e.jsx(qn,{children:e.jsx(Un,{className:"text-base",children:"Details"})}),e.jsxs(wn,{className:"space-y-3 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{children:"Plugin ID"}),e.jsx("span",{className:"font-mono text-xs text-right",children:l.id})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{children:"Plugin Key"}),e.jsx("span",{className:"font-mono text-xs text-right",children:l.pluginKey})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{children:"NPM Package"}),e.jsx("span",{className:"max-w-[170px] truncate text-right text-xs",title:l.packageName,children:l.packageName})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{children:"Version"}),e.jsxs("span",{className:"text-right text-foreground",children:["v",l.manifestJson.version??l.version]})]})]})]}),e.jsxs(jn,{children:[e.jsx(qn,{children:e.jsxs(Un,{className:"text-base flex items-center gap-1.5",children:[e.jsx(Ja,{className:"h-4 w-4"}),"Permissions"]})}),e.jsx(wn,{children:M.length>0?e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:M.map(k=>e.jsx("li",{className:"rounded-md bg-muted/40 px-2.5 py-2 font-mono text-xs text-foreground/85",children:k},k))}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No special permissions requested."})})]})]})]})})]})]})}function iz({pluginId:t,schema:n,initialValues:s,isLoading:r,pluginStatus:a,supportsConfigTest:o}){const i=at(),[l,u]=c.useState(()=>({...pm(n),...s??{}})),d=c.useRef(!1);c.useEffect(()=>{s&&!d.current&&(d.current=!0,u({...pm(n),...s}))},[s,n]);const[m,p]=c.useState({}),[x,f]=c.useState(null),[h,j]=c.useState(null),b=JSON.stringify(l)!==JSON.stringify({...pm(n),...s??{}}),g=ge({mutationFn:S=>Mn.saveConfig(t,S),onSuccess:()=>{f({type:"success",text:"Configuration saved."}),j(null),i.invalidateQueries({queryKey:N.plugins.config(t)}),setTimeout(()=>f(null),3e3)},onError:S=>{f({type:"error",text:S.message||"Failed to save configuration."})}}),y=ge({mutationFn:S=>Mn.testConfig(t,S),onSuccess:S=>{S.valid?j({type:"success",text:"Configuration test passed."}):j({type:"error",text:S.message||"Configuration test failed."})},onError:S=>{j({type:"error",text:S.message||"Configuration test failed."})}}),v=c.useCallback(S=>{u(S),p({}),f(null)},[]),_=c.useCallback(()=>{const S=hd(n,l);if(Object.keys(S).length>0){p(S);return}p({}),g.mutate(l)},[n,l,g]),E=c.useCallback(()=>{const S=hd(n,l);if(Object.keys(S).length>0){p(S);return}p({}),j(null),y.mutate(l)},[n,l,y]);return r?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[e.jsx(kn,{className:"h-4 w-4 animate-spin"}),"Loading configuration..."]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(ZN,{schema:n,values:l,onChange:v,errors:m,disabled:g.isPending}),x&&e.jsx("div",{className:`text-sm p-2 rounded border ${x.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:x.text}),h&&e.jsx("div",{className:`text-sm p-2 rounded border ${h.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:h.text}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(G,{onClick:_,disabled:g.isPending||!b,size:"sm",children:g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kn,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):"Save Configuration"}),a==="ready"&&o&&e.jsx(G,{variant:"outline",onClick:E,disabled:y.isPending,size:"sm",children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kn,{className:"h-3.5 w-3.5 animate-spin"}),"Testing..."]}):"Test Configuration"})]})]})}function lz(t){if(t==null)return"—";const n=Math.floor(t/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60);if(s<60)return`${s}m ${n%60}s`;const r=Math.floor(s/60);return r<24?`${r}h ${s%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function yb(t){return t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${(t/6e4).toFixed(1)}m`}function vb(t){const n=Date.now(),s=new Date(t).getTime(),r=n-s;if(r<0)return"just now";const a=Math.floor(r/1e3);if(a<60)return`${a}s ago`;const o=Math.floor(a/60);if(o<60)return`${o}m ago`;const i=Math.floor(o/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function cz(t){return new Date(t).toLocaleString()}function dz({status:t}){const n=t==="success"||t==="succeeded"?"bg-green-500":t==="failed"?"bg-red-500":t==="running"?"bg-blue-500 animate-pulse":t==="cancelled"?"bg-gray-400":"bg-amber-500";return e.jsx("span",{className:`inline-block h-2 w-2 rounded-full shrink-0 ${n}`,title:t})}function uz({status:t}){const n=t==="processed"||t==="success"?"bg-green-500":t==="failed"?"bg-red-500":t==="received"?"bg-blue-500":"bg-amber-500";return e.jsx("span",{className:`inline-block h-2 w-2 rounded-full shrink-0 ${n}`,title:t})}function jb(){const{companyPrefix:t,pluginId:n,pluginRoutePath:s}=Xn(),{companies:r,selectedCompanyId:a}=et(),{setBreadcrumbs:o}=Ft(),i=c.useMemo(()=>{if(!t)return null;const f=t.toUpperCase();return r.find(h=>h.issuePrefix.toUpperCase()===f)??null},[r,t]),l=!!t&&!i,u=c.useMemo(()=>i?i.id:t?null:a??null,[i,t,a]),d=c.useMemo(()=>{var f;return u?((f=r.find(h=>h.id===u))==null?void 0:f.issuePrefix)??null:null},[r,u]),{data:m}=oe({queryKey:N.plugins.uiContributions,queryFn:()=>Mn.listUiContributions(),enabled:!!u&&(!!n||!!s)}),p=c.useMemo(()=>{if(!m)return null;if(n){const h=m.find(b=>b.pluginId===n);if(!h)return null;const j=h.slots.find(b=>b.type==="page");return j?{...j,pluginId:h.pluginId,pluginKey:h.pluginKey,pluginDisplayName:h.displayName,pluginVersion:h.version}:null}if(!s)return null;const f=m.flatMap(h=>{const j=h.slots.find(b=>b.type==="page"&&b.routePath===s);return j?[{...j,pluginId:h.pluginId,pluginKey:h.pluginKey,pluginDisplayName:h.displayName,pluginVersion:h.version}]:[]});return f.length!==1?null:f[0]??null},[n,s,m]),x=c.useMemo(()=>({companyId:u??null,companyPrefix:d}),[u,d]);if(c.useEffect(()=>{p&&o([{label:"Plugins",href:"/instance/settings/plugins"},{label:p.pluginDisplayName}])},[p,d,o]),!u)return l?e.jsx(pl,{scope:"invalid_company_prefix",requestedPrefix:t}):e.jsx("div",{className:"space-y-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a company to view this page."})});if(!m)return e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"});if(!n&&s&&m.filter(h=>h.slots.some(j=>j.type==="page"&&j.routePath===s)).length>1)return e.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:["Multiple plugins declare the route ",e.jsx("code",{children:s}),". Use the plugin-id route until the conflict is resolved."]});if(!p){if(s)return e.jsx(pl,{scope:"board"});const f=n?`/instance/settings/plugins/${n}`:"/instance/settings/plugins";return e.jsx(Zt,{to:f,replace:!0})}return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(Oe,{to:d?`/${d}/dashboard`:"/dashboard",children:[e.jsx(fo,{className:"h-4 w-4 mr-1"}),"Back"]})})}),e.jsx(vi,{slot:p,context:x,className:"min-h-[200px]",missingBehavior:"placeholder"})]})}const Kr={sourceRunId:"65a79d5d-5f85-4392-a5cc-8fb48beb9e71",agentName:"CodexCoder",issueIdentifier:"PAP-473",issueTitle:"Humanize run transcripts across run detail and live surfaces",startedAt:"2026-03-11T15:21:05.948Z"},Ji=[{kind:"stderr",ts:"2026-03-11T15:21:05.594Z",text:'[crewspace] Skipping saved session resume for task "PAP-473" because wake reason is issue_assigned.'},{kind:"init",ts:"2026-03-11T15:21:05.948Z",model:"codex",sessionId:"sess_fixture_01"},{kind:"system",ts:"2026-03-11T15:21:07.249Z",text:"turn started"},{kind:"assistant",ts:"2026-03-11T15:21:18.851Z",text:"I’m starting with the CrewSpace heartbeat procedure and the repo-required docs so I can see what task is actually assigned and then work only on that scope."},{kind:"tool_call",ts:"2026-03-11T15:21:19.026Z",name:"command_execution",toolUseId:"item_1",input:{command:"sed -n '1,220p' doc/GOAL.md",cwd:"/workspace/crewspace"}},{kind:"tool_call",ts:"2026-03-11T15:21:19.026Z",name:"command_execution",toolUseId:"item_2",input:{command:"sed -n '1,320p' doc/SPEC-implementation.md",cwd:"/workspace/crewspace"}},{kind:"tool_result",ts:"2026-03-11T15:21:19.034Z",toolUseId:"item_1",content:`command: sed -n '1,220p' doc/GOAL.md
|
|
179
|
+
status: completed
|
|
180
|
+
exit_code: 0
|
|
181
|
+
|
|
182
|
+
# CrewSpace
|
|
183
|
+
|
|
184
|
+
CrewSpace is the backbone of the autonomous economy.`,isError:!1},{kind:"tool_result",ts:"2026-03-11T15:21:19.035Z",toolUseId:"item_2",content:`command: sed -n '1,320p' doc/SPEC-implementation.md
|
|
185
|
+
status: completed
|
|
186
|
+
exit_code: 0
|
|
187
|
+
|
|
188
|
+
# CrewSpace V1 Implementation Spec
|
|
189
|
+
|
|
190
|
+
CrewSpace V1 must provide a full control-plane loop for autonomous agents.`,isError:!1},{kind:"assistant",ts:"2026-03-11T15:22:08.806Z",text:"I’ve got the rendering entry points. I’m reading the existing transcript parser and the three UI surfaces together so I can collapse them onto one renderer instead of layering another one-off view."},{kind:"thinking",ts:"2026-03-11T15:22:12.044Z",text:"The current transcript UX duplicates parsing logic in multiple surfaces. A shared presentation layer will make the detail page and live surfaces behave the same way while keeping raw fallback available."},{kind:"tool_call",ts:"2026-03-11T15:22:15.401Z",name:"command_execution",toolUseId:"item_3",input:{command:'rg -n "LiveRunWidget|ActiveAgentsPanel|buildTranscript|TranscriptEntry|transcript" ui/src server/src packages',cwd:"/workspace/crewspace"}},{kind:"tool_result",ts:"2026-03-11T15:22:15.982Z",toolUseId:"item_3",content:`command: rg -n ...
|
|
191
|
+
status: completed
|
|
192
|
+
exit_code: 0
|
|
193
|
+
|
|
194
|
+
ui/src/components/ActiveAgentsPanel.tsx
|
|
195
|
+
ui/src/components/LiveRunWidget.tsx
|
|
196
|
+
ui/src/pages/AgentDetail.tsx`,isError:!1},{kind:"system",ts:"2026-03-11T15:22:21.617Z",text:"item started: web_search (id=ws_fixture_reasoning_ui)"},{kind:"system",ts:"2026-03-11T15:22:24.806Z",text:"item completed: web_search (id=ws_fixture_reasoning_ui)"},{kind:"assistant",ts:"2026-03-11T15:22:29.214Z",text:"I’ve confirmed the duplication: the run page has the only full transcript renderer, while live surfaces still collapse output into feed strings. I’m pulling markdown utilities and adapter shapes now so the new renderer can stay shared."},{kind:"tool_call",ts:"2026-03-11T15:23:04.251Z",name:"command_execution",toolUseId:"item_4",input:{command:"pnpm -r typecheck",cwd:"/workspace/crewspace"}},{kind:"tool_result",ts:"2026-03-11T15:23:26.903Z",toolUseId:"item_4",content:`command: pnpm -r typecheck
|
|
197
|
+
status: completed
|
|
198
|
+
exit_code: 0
|
|
199
|
+
|
|
200
|
+
packages/adapter-utils typecheck: Done
|
|
201
|
+
server typecheck: Done
|
|
202
|
+
ui typecheck: Done
|
|
203
|
+
cli typecheck: Done`,isError:!1},{kind:"assistant",ts:"2026-03-11T15:23:34.102Z",text:"Typecheck is clean. I’m running the remaining repo checks now so the transcript work is verified under the full workspace build, not just the UI package."},{kind:"tool_call",ts:"2026-03-11T15:23:40.511Z",name:"command_execution",toolUseId:"item_5",input:{command:"pnpm test:run",cwd:"/workspace/crewspace"}},{kind:"tool_result",ts:"2026-03-11T15:23:56.944Z",toolUseId:"item_5",content:`command: pnpm test:run
|
|
204
|
+
status: failed
|
|
205
|
+
exit_code: 1
|
|
206
|
+
|
|
207
|
+
FAIL packages/db/src/runtime-config.test.ts
|
|
208
|
+
FAIL src/__tests__/worktree.test.ts
|
|
209
|
+
|
|
210
|
+
All transcript-adapter tests passed after snapshot updates.`,isError:!0},{kind:"thinking",ts:"2026-03-11T15:24:02.188Z",text:"The remaining failures are unrelated to transcript rendering, so I should isolate them in the handoff and keep the UI change set focused."},{kind:"assistant",ts:"2026-03-11T15:24:08.490Z",text:"The new parser metadata changed a few adapter test snapshots exactly where expected, and the remaining red tests are outside this change set. I’m keeping the transcript patch focused and shipping with that caveat called out."},{kind:"tool_call",ts:"2026-03-11T15:24:21.327Z",name:"command_execution",toolUseId:"item_6",input:{command:"pnpm build",cwd:"/workspace/crewspace"}},{kind:"tool_result",ts:"2026-03-11T15:24:44.030Z",toolUseId:"item_6",content:`command: pnpm build
|
|
211
|
+
status: completed
|
|
212
|
+
exit_code: 0
|
|
213
|
+
|
|
214
|
+
ui build: built successfully
|
|
215
|
+
cli build: Done`,isError:!1},{kind:"tool_call",ts:"2026-03-11T15:24:52.504Z",name:"command_execution",toolUseId:"item_7",input:{command:'git commit -m "Humanize run transcripts across run detail and live surfaces"',cwd:"/workspace/crewspace"}},{kind:"tool_result",ts:"2026-03-11T15:24:53.104Z",toolUseId:"item_7",content:`command: git commit ...
|
|
216
|
+
status: completed
|
|
217
|
+
exit_code: 0
|
|
218
|
+
|
|
219
|
+
87b8e21 Humanize run transcripts across run detail and live surfaces`,isError:!1},{kind:"assistant",ts:"2026-03-11T15:25:00.908Z",text:"Implemented the transcript UI refactor and switched the run detail page, issue live widget, and dashboard agent card onto the same rendering language."},{kind:"result",ts:"2026-03-11T15:25:05.440Z",text:"Transcript rollout complete with shared nice/raw rendering and compact live variants.",inputTokens:11240,outputTokens:3460,cachedTokens:520,costUsd:.048121,subtype:"success",isError:!1,errors:[]}],xm=[{id:"detail",label:"Run Detail",eyebrow:"Full transcript",description:"The long-form run page with the `Nice | Raw` toggle and the most inspectable transcript view.",icon:F1},{id:"live",label:"Issue Widget",eyebrow:"Live stream",description:"The issue-detail live run widget, optimized for following an active run without leaving the task page.",icon:q1},{id:"dashboard",label:"Dashboard Card",eyebrow:"Dense card",description:"The active-agents dashboard card, tuned for compact scanning while keeping the same transcript language.",icon:U1}];function YN(t){return t==="dashboard"?Ji.slice(-9):t==="live"?Ji.slice(-14):Ji}function mz({mode:t,streaming:n,density:s}){return e.jsxs("div",{className:"overflow-hidden rounded-xl border border-border/70 bg-background/80 shadow-[0_24px_60px_rgba(15,23,42,0.08)]",children:[e.jsxs("div",{className:"border-b border-border/60 bg-background/90 px-5 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Wt,{variant:"outline",className:"uppercase tracking-[0.18em] text-[10px]",children:"Run Detail"}),e.jsx(Dt,{status:n?"running":"succeeded"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:js(Kr.startedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm font-medium",children:["Transcript (",Ji.length,")"]})]}),e.jsx("div",{className:"max-h-[720px] overflow-y-auto bg-[radial-gradient(circle_at_top_left,rgba(8,145,178,0.08),transparent_36%),radial-gradient(circle_at_bottom_right,rgba(245,158,11,0.10),transparent_28%)] p-5",children:e.jsx(Ni,{entries:Ji,mode:t,density:s,streaming:n})})]})}function pz({streaming:t,mode:n,density:s}){return e.jsxs("div",{className:"overflow-hidden rounded-xl border border-cyan-500/25 bg-background/85 shadow-[0_20px_50px_rgba(6,182,212,0.10)]",children:[e.jsxs("div",{className:"border-b border-border/60 bg-cyan-500/[0.05] px-5 py-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-cyan-700 dark:text-cyan-300",children:"Live Runs"}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"Compact live transcript stream for the issue detail page."})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Ut,{name:Kr.agentName,size:"sm"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"rounded-full border border-border/70 bg-background/70 px-2 py-1 font-mono",children:Kr.sourceRunId.slice(0,8)}),e.jsx(Dt,{status:t?"running":"succeeded"}),e.jsx("span",{children:js(Kr.startedAt)})]})]}),e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2.5 py-1 text-[11px] text-muted-foreground",children:["Open run",e.jsx(Is,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"max-h-[460px] overflow-y-auto pr-1",children:e.jsx(Ni,{entries:YN("live"),mode:n,density:s,limit:s==="compact"?10:12,streaming:t})})]})]})}function xz({streaming:t,mode:n,density:s}){return e.jsx("div",{className:"max-w-md",children:e.jsxs("div",{className:O("flex h-[320px] flex-col overflow-hidden rounded-xl border shadow-[0_20px_40px_rgba(15,23,42,0.10)]",t?"border-cyan-500/25 bg-cyan-500/[0.04]":"border-border bg-background/75"),children:[e.jsxs("div",{className:"border-b border-border/60 px-4 py-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:O("inline-flex h-2.5 w-2.5 rounded-full",t?"bg-cyan-500 shadow-[0_0_0_6px_rgba(34,211,238,0.12)]":"bg-muted-foreground/35")}),e.jsx(Ut,{name:Kr.agentName,size:"sm"})]}),e.jsx("div",{className:"mt-2 text-[11px] text-muted-foreground",children:t?"Live now":"Finished 2m ago"})]}),e.jsx("span",{className:"rounded-full border border-border/70 bg-background/70 px-2 py-1 text-[10px] text-muted-foreground",children:e.jsx(Is,{className:"h-2.5 w-2.5"})})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-border/60 bg-background/60 px-3 py-2 text-xs text-cyan-700 dark:text-cyan-300",children:[Kr.issueIdentifier," - ",Kr.issueTitle]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:e.jsx(Ni,{entries:YN("dashboard"),mode:n,density:s,limit:s==="compact"?6:8,streaming:t})})]})})}function fz(){const[t,n]=c.useState("detail"),[s,r]=c.useState("nice"),[a,o]=c.useState(!0),[i,l]=c.useState("comfortable"),u=xm.find(d=>d.id===t)??xm[0];return e.jsx("div",{className:"space-y-6",children:e.jsx("div",{className:"overflow-hidden rounded-2xl border border-border/70 bg-[linear-gradient(135deg,rgba(8,145,178,0.08),transparent_28%),linear-gradient(180deg,rgba(245,158,11,0.08),transparent_40%),var(--background)] shadow-[0_28px_70px_rgba(15,23,42,0.10)]",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[260px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"border-b border-border/60 bg-background/75 p-5 lg:border-b-0 lg:border-r",children:[e.jsxs("div",{className:"mb-5",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-cyan-500/25 bg-cyan-500/[0.08] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.24em] text-cyan-700 dark:text-cyan-300",children:[e.jsx(Sd,{className:"h-3.5 w-3.5"}),"UX Lab"]}),e.jsx("h1",{className:"mt-4 text-2xl font-semibold tracking-tight",children:"Run Transcript Fixtures"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Built from a real CrewSpace development run, then sanitized so no secrets, local paths, or environment details survive into the fixture."})]}),e.jsx("div",{className:"space-y-2",children:xm.map(d=>{const m=d.icon;return e.jsx("button",{type:"button",onClick:()=>n(d.id),className:O("w-full rounded-xl border px-4 py-3 text-left transition-all",t===d.id?"border-cyan-500/35 bg-cyan-500/[0.10] shadow-[0_12px_24px_rgba(6,182,212,0.12)]":"border-border/70 bg-background/70 hover:border-cyan-500/20 hover:bg-cyan-500/[0.04]"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"rounded-lg border border-current/15 p-2 text-cyan-700 dark:text-cyan-300",children:e.jsx(m,{className:"h-4 w-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:d.eyebrow}),e.jsx("span",{className:"mt-1 block text-sm font-medium",children:d.label}),e.jsx("span",{className:"mt-1 block text-xs text-muted-foreground",children:d.description})]})]})},d.id)})})]}),e.jsxs("main",{className:"min-w-0 p-5",children:[e.jsxs("div",{className:"mb-5 flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground",children:u.eyebrow}),e.jsx("h2",{className:"mt-1 text-2xl font-semibold",children:u.label}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm text-muted-foreground",children:u.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Wt,{variant:"outline",className:"rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.18em]",children:["Source run ",Kr.sourceRunId.slice(0,8)]}),e.jsx(Wt,{variant:"outline",className:"rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.18em]",children:Kr.issueIdentifier})]})]}),e.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Controls"}),e.jsx("div",{className:"inline-flex rounded-full border border-border/70 bg-background/80 p-1",children:["nice","raw"].map(d=>e.jsx("button",{type:"button",className:O("rounded-full px-3 py-1 text-xs font-medium capitalize transition-colors",s===d?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"),onClick:()=>r(d),children:d},d))}),e.jsx("div",{className:"inline-flex rounded-full border border-border/70 bg-background/80 p-1",children:["comfortable","compact"].map(d=>e.jsx("button",{type:"button",className:O("rounded-full px-3 py-1 text-xs font-medium capitalize transition-colors",i===d?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"),onClick:()=>l(d),children:d},d))}),e.jsx(G,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>o(d=>!d),children:a?"Show settled state":"Show streaming state"})]}),t==="detail"?e.jsx("div",{className:O(i==="compact"&&"max-w-5xl"),children:e.jsx(mz,{mode:s,streaming:a,density:i})}):t==="live"?e.jsx("div",{className:O(i==="compact"&&"max-w-4xl"),children:e.jsx(pz,{streaming:a,mode:s,density:i})}):e.jsx(xz,{streaming:a,mode:s,density:i})]})]})})})}const Ba=200,vc=100,jl=32,hz=80,bd=60;function Jo(t){if(t.reports.length===0)return Ba;const n=t.reports.reduce((r,a)=>r+Jo(a),0),s=(t.reports.length-1)*jl;return Math.max(Ba,n+s)}function XN(t,n,s){const r=Jo(t),a=[];if(t.reports.length>0){const o=t.reports.reduce((u,d)=>u+Jo(d),0),i=(t.reports.length-1)*jl;let l=n+(r-o-i)/2;for(const u of t.reports){const d=Jo(u);a.push(XN(u,l,s+vc+hz)),l+=d+jl}}return{id:t.id,name:t.name,role:t.role,status:t.status,x:n+(r-Ba)/2,y:s,children:a}}function gz(t){if(t.length===0)return[];t.reduce((a,o)=>a+Jo(o),0),(t.length-1)*jl;let n=bd;const s=bd,r=[];for(const a of t){const o=Jo(a);r.push(XN(a,n,s)),n+=o+jl}return r}function bz(t){const n=[];function s(r){n.push(r),r.children.forEach(s)}return t.forEach(s),n}function yz(t){const n=[];function s(r){for(const a of r.children)n.push({parent:r,child:a}),s(a)}return t.forEach(s),n}const vz={claude_local:"Claude",codex_local:"Codex",gemini_local:"Gemini",opencode_local:"OpenCode",cursor:"Cursor",hermes_local:"Hermes",openclaw_gateway:"OpenClaw Gateway",process:"Process",http:"HTTP"},jz={running:"#22d3ee",active:"#4ade80",paused:"#facc15",idle:"#facc15",error:"#f87171",terminated:"#a3a3a3"},wz="#a3a3a3";function Nz(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),s=Sn(),{openChatWithAgent:r}=Rx(),{data:a,isLoading:o}=oe({queryKey:N.org(t),queryFn:()=>We.org(t),enabled:!!t}),{data:i}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),l=c.useMemo(()=>{const k=new Map;for(const L of i??[])k.set(L.id,L);return k},[i]);c.useEffect(()=>{n([{label:"Interact with Agents"}])},[n]);const u=c.useMemo(()=>gz(a??[]),[a]),d=c.useMemo(()=>bz(u),[u]),m=c.useMemo(()=>yz(u),[u]),p=c.useMemo(()=>{if(d.length===0)return{width:800,height:600};let k=0,L=0;for(const $ of d)k=Math.max(k,$.x+Ba),L=Math.max(L,$.y+vc);return{width:k+bd,height:L+bd}},[d]),x=c.useRef(null),[f,h]=c.useState({x:0,y:0}),[j,b]=c.useState(1),[g,y]=c.useState(!1),v=c.useRef({x:0,y:0,panX:0,panY:0}),_=c.useRef(!1);c.useEffect(()=>{if(_.current||d.length===0||!x.current)return;_.current=!0;const k=x.current,L=k.clientWidth,$=k.clientHeight,C=(L-40)/p.width,I=($-40)/p.height,K=Math.min(C,I,1),T=p.width*K,z=p.height*K;b(K),h({x:(L-T)/2,y:($-z)/2})},[d,p]);const E=c.useCallback(k=>{k.button!==0||k.target.closest("[data-org-card]")||(y(!0),v.current={x:k.clientX,y:k.clientY,panX:f.x,panY:f.y})},[f]),S=c.useCallback(k=>{if(!g)return;const L=k.clientX-v.current.x,$=k.clientY-v.current.y;h({x:v.current.panX+L,y:v.current.panY+$})},[g]),M=c.useCallback(()=>{y(!1)},[]),B=c.useCallback(k=>{k.preventDefault();const L=x.current;if(!L)return;const $=L.getBoundingClientRect(),C=k.clientX-$.left,I=k.clientY-$.top,K=k.deltaY<0?1.1:.9,T=Math.min(Math.max(j*K,.2),2),z=T/j;h({x:C-z*(C-f.x),y:I-z*(I-f.y)}),b(T)},[j,f]);return t?o?e.jsx(mn,{variant:"org-chart"}):a&&a.length===0?e.jsx(tn,{icon:bm,message:"No organizational hierarchy defined."}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"mb-2 flex items-center justify-between shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{to:"/company/import",children:e.jsxs(G,{variant:"outline",size:"sm",children:[e.jsx(ol,{className:"mr-1.5 h-3.5 w-3.5"}),"Import company"]})}),e.jsx(Oe,{to:"/company/export",children:e.jsxs(G,{variant:"outline",size:"sm",children:[e.jsx(ei,{className:"mr-1.5 h-3.5 w-3.5"}),"Export company"]})})]})}),e.jsxs("div",{ref:x,className:"w-full flex-1 min-h-0 overflow-hidden relative bg-muted/20 border border-border rounded-lg",style:{cursor:g?"grabbing":"grab"},onMouseDown:E,onMouseMove:S,onMouseUp:M,onMouseLeave:M,onWheel:B,children:[e.jsxs("div",{className:"absolute top-3 right-3 z-10 flex flex-col gap-1",children:[e.jsx("button",{className:"w-7 h-7 flex items-center justify-center bg-background border border-border rounded text-sm hover:bg-accent transition-colors",onClick:()=>{const k=Math.min(j*1.2,2),L=x.current;if(L){const $=L.clientWidth/2,C=L.clientHeight/2,I=k/j;h({x:$-I*($-f.x),y:C-I*(C-f.y)})}b(k)},"aria-label":"Zoom in",children:"+"}),e.jsx("button",{className:"w-7 h-7 flex items-center justify-center bg-background border border-border rounded text-sm hover:bg-accent transition-colors",onClick:()=>{const k=Math.max(j*.8,.2),L=x.current;if(L){const $=L.clientWidth/2,C=L.clientHeight/2,I=k/j;h({x:$-I*($-f.x),y:C-I*(C-f.y)})}b(k)},"aria-label":"Zoom out",children:"−"}),e.jsx("button",{className:"w-7 h-7 flex items-center justify-center bg-background border border-border rounded text-[10px] hover:bg-accent transition-colors",onClick:()=>{if(!x.current)return;const k=x.current.clientWidth,L=x.current.clientHeight,$=(k-40)/p.width,C=(L-40)/p.height,I=Math.min($,C,1),K=p.width*I,T=p.height*I;b(I),h({x:(k-K)/2,y:(L-T)/2})},title:"Fit to screen","aria-label":"Fit chart to screen",children:"Fit"})]}),e.jsx("svg",{className:"absolute inset-0 pointer-events-none",style:{width:"100%",height:"100%"},children:e.jsx("g",{transform:`translate(${f.x}, ${f.y}) scale(${j})`,children:m.map(({parent:k,child:L})=>{const $=k.x+Ba/2,C=k.y+vc,I=L.x+Ba/2,K=L.y,T=(C+K)/2;return e.jsx("path",{d:`M ${$} ${C} L ${$} ${T} L ${I} ${T} L ${I} ${K}`,fill:"none",stroke:"var(--border)",strokeWidth:1.5},`${k.id}-${L.id}`)})})}),e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 z-10 pointer-events-none",children:e.jsx("div",{className:"flex items-center gap-1.5 bg-background/80 backdrop-blur-sm border border-border rounded-full px-3 py-1.5 shadow-xs",children:e.jsx("span",{className:"text-[11px] text-muted-foreground/70 select-none",children:"Click an agent card to view details · Click the status dot to chat"})})}),e.jsx("div",{className:"absolute inset-0",style:{transform:`translate(${f.x}px, ${f.y}px) scale(${j})`,transformOrigin:"0 0"},children:d.map(k=>{const L=l.get(k.id),$=jz[k.status]??wz;return e.jsxs("div",{"data-org-card":!0,className:"absolute bg-card border border-border rounded-lg shadow-sm hover:shadow-md hover:border-foreground/20 transition-[box-shadow,border-color] duration-150 cursor-pointer select-none",style:{left:k.x,top:k.y,width:Ba,minHeight:vc},onClick:()=>s(L?Na(L):`/agents/${k.id}`),children:[L&&e.jsxs("button",{"data-org-card":!0,title:`Chat with ${k.name}`,className:"absolute -top-1.5 -right-1.5 z-10 group/dot",onClick:C=>{C.stopPropagation(),r(L)},children:[e.jsx("span",{className:"absolute inset-0 rounded-full opacity-40 group-hover/dot:opacity-70 transition-opacity",style:{backgroundColor:$,filter:"blur(3px)",transform:"scale(1.6)"}}),(k.status==="running"||k.status==="active")&&e.jsx("span",{className:"absolute inset-0 rounded-full animate-ping opacity-60",style:{backgroundColor:$}}),e.jsx("span",{className:"relative block h-3.5 w-3.5 rounded-full border-2 border-card transition-transform group-hover/dot:scale-125",style:{backgroundColor:$}})]}),e.jsxs("div",{className:"flex items-center px-4 py-3 gap-3",children:[e.jsx("div",{className:"relative shrink-0",children:e.jsx("div",{className:"w-9 h-9 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Cn,{icon:L==null?void 0:L.icon,className:"h-4.5 w-4.5 text-foreground/70"})})}),e.jsxs("div",{className:"flex flex-col items-start min-w-0 flex-1",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground leading-tight",children:k.name}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight mt-0.5",children:(L==null?void 0:L.title)??Cz(k.role)}),L&&e.jsx("span",{className:"text-[10px] text-muted-foreground/60 font-mono leading-tight mt-1",children:vz[L.adapterType]??L.adapterType}),L&&L.capabilities&&e.jsx("span",{className:"text-[10px] text-muted-foreground/80 leading-tight mt-1 line-clamp-2",children:L.capabilities})]})]})]},k.id)})})]})]}):e.jsx(tn,{icon:bm,message:"Select a company to view the org chart."})}const kz=rx;function Cz(t){return kz[t]??t}const Bi={getGraph:t=>ne.get(`/companies/${t}/memories/graph`),create:(t,n)=>ne.post(`/companies/${t}/memories`,n),update:(t,n)=>ne.patch(`/memories/${t}`,n),remove:t=>ne.delete(`/memories/${t}`),createLink:(t,n)=>ne.post(`/companies/${t}/memories/links`,n),removeLink:t=>ne.delete(`/memories/links/${t}`),saveTaskSolution:(t,n)=>ne.post(`/companies/${t}/task-solutions`,n),findSimilarTasks:(t,n,s)=>ne.get(`/companies/${t}/agents/${n}/similar-tasks?query=${encodeURIComponent(s)}`)},wb=["#f59e0b","#818cf8","#34d399","#f472b6","#38bdf8","#fb923c","#a78bfa","#4ade80"],Sz={fact:"#6366f1",insight:"#8b5cf6",decision:"#ec4899",pattern:"#f59e0b",task:"#10b981",observation:"#3b82f6",learning:"#06b6d4"};function oa(t){return Sz[t]??"#94a3b8"}const Iz=["fact","insight","decision","pattern","task","observation","learning"];function To([t,n,s],r){const a=Math.cos(r),o=Math.sin(r);return[t*a+s*o,n,-t*o+s*a]}function Ro([t,n,s],r){const a=Math.cos(r),o=Math.sin(r);return[t,n*a-s*o,n*o+s*a]}function Po(t,n,s,r){const a=t[2]+n,o=n/Math.max(a,1);return{sx:s+t[0]*o,sy:r+t[1]*o,scale:o,depth:t[2]}}function Nb(t){const n=Math.PI*(Math.sqrt(5)-1);return Array.from({length:t},(s,r)=>{const a=1-r/Math.max(t-1,1)*2,o=Math.sqrt(Math.max(0,1-a*a)),i=n*r;return[o*Math.cos(i),a,o*Math.sin(i)]})}function ek([t,n,s],[r,a,o]){return[n*o-s*a,s*r-t*o,t*a-n*r]}function _z([t,n,s]){const r=Math.sqrt(t*t+n*n+s*s)||1;return[t/r,n/r,s/r]}function pc([t,n,s],r){return[t*r,n*r,s*r]}function kb(t,n,s){const r=Math.cos(s),a=Math.sin(s),o=t[0]*n[0]+t[1]*n[1]+t[2]*n[2],i=ek(n,t);return[t[0]*r+i[0]*a+n[0]*o*(1-r),t[1]*r+i[1]*a+n[1]*o*(1-r),t[2]*r+i[2]*a+n[2]*o*(1-r)]}function Az(t,n){const s=new Map;let r=0;for(const b of t)for(const g of b.agents)s.has(g.agentId)||s.set(g.agentId,{name:g.agentName??"Agent",count:0,colorIdx:r++}),s.get(g.agentId).count++;const a=[...s.keys()],o=Nb(Math.max(a.length,1)),i=a.map((b,g)=>{const y=s.get(b);return{id:b,name:y.name,color:wb[y.colorIdx%wb.length],memCount:y.count,pos:o[g],r:18+Math.min(y.count*1.5,10)}});new Map(i.map(b=>[b.id,b]));const l=new Map;for(const b of t){const g=b.agents.find(y=>y.isOwner)??b.agents[0];if(g){const y=l.get(g.agentId)??[];y.push(b),l.set(g.agentId,y)}}const u=[],d=i.map(b=>l.get(b.id)??[]),m=Math.max(...d.map(b=>b.length),0),p=[];for(let b=0;b<m;b++)for(let g=0;g<i.length;g++){const y=d[g];b<y.length&&p.push({m:y[b],agent:i[g]})}const x=p.length,f=Nb(Math.max(x,1));p.forEach(({m:b,agent:g},y)=>{var S;const v=f[y],_=Math.abs(v[1])<.9?[0,1,0]:[1,0,0],E=_z(ek(v,_));u.push({id:b.id,title:b.title,content:b.content??"",memoryType:b.memoryType,agentId:g.id,agentColor:g.color,dir:v,driftAxis:E,driftSpeed:(.006+y*.1618033%1*.005)*(y%2===0?1:-1),agentPos:g.pos,r:3.5+Math.min((((S=b.content)==null?void 0:S.length)??0)/120,2.5),raw:b})});const h=new Set,j=[];for(const b of n){const g=u.find(S=>S.id===b.sourceMemoryId),y=u.find(S=>S.id===b.targetMemoryId);if(!(g!=null&&g.agentId)||!(y!=null&&y.agentId)||g.agentId===y.agentId)continue;const v=i.findIndex(S=>S.id===g.agentId),_=i.findIndex(S=>S.id===y.agentId);if(v<0||_<0)continue;const E=[v,_].sort().join(":");h.has(E)||(h.add(E),j.push([v,_]))}return{agents:i,mems:u,agentEdges:j}}function Ez(t){const n=parseInt(t.slice(1,3),16),s=parseInt(t.slice(3,5),16),r=parseInt(t.slice(5,7),16);return`${n},${s},${r}`}function ts(t,n){return`rgba(${Ez(t)},${n})`}const Cb=260,Sb=.48,Ib=900;function Tz({graph:t,selectedId:n,hoveredId:s,filterAgentId:r,search:a,onSelect:o,onHover:i}){const l=c.useRef(null),u=c.useRef(null),[d,m]=c.useState({w:800,h:600}),p=c.useRef(0),x=c.useRef(-.25),f=c.useRef(1),h=c.useRef(0),j=c.useRef(0),b=c.useRef(!1),g=c.useRef({x:0,y:0}),y=c.useRef(!1),v=c.useRef(n),_=c.useRef(s),E=c.useRef(r),S=c.useRef(a);v.current=n,_.current=s,E.current=r,S.current=a,c.useEffect(()=>{const K=u.current;if(!K)return;const T=new ResizeObserver(([z])=>{m({w:z.contentRect.width,h:z.contentRect.height})});return T.observe(K),m({w:K.clientWidth,h:K.clientHeight}),()=>T.disconnect()},[]),c.useEffect(()=>{const K=l.current;if(!K)return;const T=K.getContext("2d");if(!T)return;const{agents:z,mems:w,agentEdges:F}=t,{w:A,h:R}=d,Q=A/2,H=R/2;f.current;const U=()=>{var Be,be;h.current+=.008;const Z=h.current,V=p.current,W=x.current,J=f.current,Y=Ib/J,de=Cb*J,fe=v.current,Ce=_.current,le=E.current,Re=S.current.toLowerCase(),Pe=Ce??fe;T.clearRect(0,0,A,R);const Fe=T.createRadialGradient(Q,H,0,Q,H,Math.max(A,R)*.8);Fe.addColorStop(0,"#10121a"),Fe.addColorStop(.5,"#0b0d14"),Fe.addColorStop(1,"#06080e"),T.fillStyle=Fe,T.fillRect(0,0,A,R);const pe=[],Le=de*Sb,q=z.map(he=>{let Se=pc(he.pos,Le);Se=To(Se,V+Z*.12),Se=Ro(Se,W);const we=Po(Se,Y,Q,H);return pe.push({id:he.id,sx:we.sx,sy:we.sy,scale:we.scale,depth:we.depth,type:"agent",idx:z.indexOf(he)}),we}),D=w.map(he=>{const Se=kb(he.dir,he.driftAxis,Z*he.driftSpeed);let we=pc(Se,de);we=To(we,V+Z*.12),we=Ro(we,W);const ee=Po(we,Y,Q,H);return pe.push({id:he.id,sx:ee.sx,sy:ee.sy,scale:ee.scale,depth:ee.depth,type:"mem",idx:w.indexOf(he)}),ee}),ie=(he,Se,we,ee)=>{T.strokeStyle=`rgba(150,170,220,${Se})`,T.lineWidth=.5;const me=64;for(let ye=1;ye<we;ye++){const Ke=Math.PI*ye/we,qe=Math.sin(Ke)*he,se=Math.cos(Ke)*he;T.beginPath();for(let ce=0;ce<=me;ce++){const Te=2*Math.PI*ce/me;let ae=[qe*Math.cos(Te),se,qe*Math.sin(Te)];ae=To(ae,V+Z*.12),ae=Ro(ae,W);const je=Po(ae,Y,Q,H);ce===0?T.moveTo(je.sx,je.sy):T.lineTo(je.sx,je.sy)}T.stroke()}for(let ye=0;ye<ee;ye++){const Ke=Math.PI*ye/ee;T.beginPath();for(let qe=0;qe<=me;qe++){const se=Math.PI*qe/me;let ce=[Math.sin(se)*Math.cos(Ke)*he,Math.cos(se)*he,Math.sin(se)*Math.sin(Ke)*he];ce=To(ce,V+Z*.12),ce=Ro(ce,W);const Te=Po(ce,Y,Q,H);qe===0?T.moveTo(Te.sx,Te.sy):T.lineTo(Te.sx,Te.sy)}T.stroke()}};ie(de,.055,6,6),ie(Le,.1,4,4);const Ie=T.createRadialGradient(Q,H,0,Q,H,Le*.3);Ie.addColorStop(0,"rgba(99,102,241,0.18)"),Ie.addColorStop(.5,"rgba(99,102,241,0.06)"),Ie.addColorStop(1,"rgba(99,102,241,0)"),T.fillStyle=Ie,T.beginPath(),T.arc(Q,H,Le*.3,0,Math.PI*2),T.fill(),T.beginPath(),T.arc(Q,H,3,0,Math.PI*2),T.fillStyle="rgba(99,102,241,0.6)",T.fill();for(const[he,Se]of F){const we=q[he],ee=q[Se];if(!we||!ee)continue;const me=Math.min(1,(we.scale+ee.scale)/2),ye=z[he].id===Pe||z[Se].id===Pe;T.beginPath(),T.moveTo(we.sx,we.sy),T.lineTo(ee.sx,ee.sy),T.strokeStyle=`rgba(148,163,184,${ye?.5*me:.15*me})`,T.lineWidth=ye?1.5:.7,T.setLineDash([]),T.stroke()}T.setLineDash([2,3]);for(let he=0;he<w.length;he++){const Se=w[he],we=z.findIndex(Te=>Te.id===Se.agentId);if(we<0)continue;const ee=q[we],me=D[he];if(!ee||!me)continue;const ye=!le||Se.agentId===le,Ke=!Re||Se.title.toLowerCase().includes(Re);if(!ye&&!Ke)continue;const qe=Se.id===Pe||Se.agentId===Pe,se=Math.min(1,me.scale*.7+ee.scale*.3),ce=qe?.55:.1;T.beginPath(),T.moveTo(me.sx,me.sy),T.lineTo(ee.sx,ee.sy),T.strokeStyle=ts(Se.agentColor,ce*se),T.lineWidth=qe?1.2:.4,T.stroke()}T.setLineDash([]);const ue=[...pe].sort((he,Se)=>he.depth-Se.depth);for(const he of ue)if(he.type==="agent"){const Se=z[he.idx],we=q[he.idx],ee=fe===Se.id,me=Ce===Se.id,ye=Ce?((Be=w.find(ke=>ke.id===Ce))==null?void 0:Be.agentId)===Se.id:!1,Ke=!!Pe&&!ee&&!me&&!ye&&((be=w.find(ke=>ke.id===Pe))==null?void 0:be.agentId)!==Se.id,qe=Se.r*we.scale*J,se=.4+.6*we.scale;T.globalAlpha=Ke?.15:se;const ce=qe*(1.55+Math.sin(Z*2.5+he.idx)*.08);T.beginPath(),T.arc(we.sx,we.sy,ce,0,Math.PI*2),T.strokeStyle=ts(Se.color,.22),T.lineWidth=1,T.stroke(),T.setLineDash([3,3]),T.beginPath(),T.arc(we.sx,we.sy,qe*1.28,0,Math.PI*2),T.strokeStyle=ts(Se.color,.35),T.lineWidth=.8,T.stroke(),T.setLineDash([]);const Te=T.createRadialGradient(we.sx,we.sy,0,we.sx,we.sy,qe*2.2);Te.addColorStop(0,ts(Se.color,.22)),Te.addColorStop(1,ts(Se.color,0)),T.beginPath(),T.arc(we.sx,we.sy,qe*2.2,0,Math.PI*2),T.fillStyle=Te,T.fill();const ae=T.createRadialGradient(we.sx-qe*.3,we.sy-qe*.3,0,we.sx,we.sy,qe);ae.addColorStop(0,ts(Se.color,.95)),ae.addColorStop(.7,ts(Se.color,.55)),ae.addColorStop(1,ts(Se.color,.2)),T.beginPath(),T.arc(we.sx,we.sy,qe,0,Math.PI*2),T.fillStyle=ae,T.fill(),T.strokeStyle=ts(Se.color,ee?1:.7),T.lineWidth=ee?2:1.2,T.stroke(),T.beginPath(),T.arc(we.sx,we.sy,qe*.28,0,Math.PI*2),T.fillStyle=ts(Se.color,.95),T.fill(),T.globalAlpha=Ke?.1:se;const je=Math.max(9,Math.min(13,11*we.scale*J));T.font=`600 ${je}px Inter, system-ui, sans-serif`,T.fillStyle=ts(Se.color,ee||me?1:.85),T.textAlign="center",T.fillText(Se.name,we.sx,we.sy+qe+je+2),T.font=`400 ${Math.max(7,je-2)}px 'JetBrains Mono', monospace`,T.fillStyle=ts(Se.color,.4),T.fillText(`${Se.memCount} mem`,we.sx,we.sy+qe+je*2+3),T.globalAlpha=1,T.textAlign="left"}else{const Se=w[he.idx],we=D[he.idx],ee=!le||Se.agentId===le,me=!Re||Se.title.toLowerCase().includes(Re),ye=ee&&me,Ke=Ce===Se.id,qe=fe===Se.id,se=!ye||!!Pe&&Pe!==Se.id&&Pe!==Se.agentId,ce=Se.r*we.scale*J,Te=.35+.65*we.scale;if(T.globalAlpha=se?.08:Te,Ke||qe){const ae=T.createRadialGradient(we.sx,we.sy,0,we.sx,we.sy,ce*3);ae.addColorStop(0,ts(Se.agentColor,.3)),ae.addColorStop(1,ts(Se.agentColor,0)),T.beginPath(),T.arc(we.sx,we.sy,ce*3,0,Math.PI*2),T.fillStyle=ae,T.fill()}if(T.beginPath(),T.arc(we.sx,we.sy,ce,0,Math.PI*2),T.fillStyle=ts(Se.agentColor,.12),T.fill(),T.strokeStyle=ts(Se.agentColor,qe?.95:Ke?.8:.5),T.lineWidth=qe?1.5:1,T.stroke(),T.beginPath(),T.arc(we.sx,we.sy,ce*.45,0,Math.PI*2),T.fillStyle=ts(Se.agentColor,qe||Ke?1:.9),T.fill(),T.globalAlpha=se?.06:Te,Ke||qe){const ae=Se.title.length>26?Se.title.slice(0,26)+"…":Se.title,je=Math.max(9,10*we.scale*J);T.font=`500 ${je}px Inter, system-ui, sans-serif`;const ke=T.measureText(ae).width,Xe=we.sx-ke/2,lt=we.sy-ce-8;T.fillStyle="rgba(12,14,22,0.88)",T.beginPath(),T.roundRect(Xe-5,lt-je,ke+10,je+6,3),T.fill(),T.fillStyle=Se.agentColor,T.textAlign="center",T.fillText(ae,we.sx,lt),T.textAlign="left"}T.globalAlpha=1}j.current=requestAnimationFrame(U)};return j.current=requestAnimationFrame(U),()=>cancelAnimationFrame(j.current)},[t,d]);const M=c.useCallback((K,T)=>{const{agents:z,mems:w}=t,F=Cb*f.current,A=p.current,R=x.current,Q=h.current,H=Ib/f.current,{w:U,h:Z}=d,V=U/2,W=Z/2,J=f.current;let Y=null;const de=F*Sb;for(const fe of z){let Ce=pc(fe.pos,de);Ce=To(Ce,A+Q*.12),Ce=Ro(Ce,R);const le=Po(Ce,H,V,W),Re=fe.r*le.scale*J,Pe=K-le.sx,Fe=T-le.sy,pe=Pe*Pe+Fe*Fe;pe<=(Re+4)*(Re+4)&&(!Y||pe<Y.distSq)&&(Y={id:fe.id,distSq:pe})}for(let fe=0;fe<w.length;fe++){const Ce=w[fe],le=kb(Ce.dir,Ce.driftAxis,Q*Ce.driftSpeed);let Re=pc(le,F);Re=To(Re,A+Q*.12),Re=Ro(Re,R);const Pe=Po(Re,H,V,W),Fe=Ce.r*Pe.scale*J,pe=K-Pe.sx,Le=T-Pe.sy,q=pe*pe+Le*Le,D=Math.max(Fe+6,12);q<=D*D&&(!Y||q<Y.distSq)&&(Y={id:Ce.id,distSq:q})}return(Y==null?void 0:Y.id)??null},[t,d]),B=c.useCallback(K=>{b.current=!0,y.current=!1,g.current={x:K.clientX,y:K.clientY};const T=w=>{const F=w.clientX-g.current.x,A=w.clientY-g.current.y;(Math.abs(F)>2||Math.abs(A)>2)&&(y.current=!0),p.current+=F*.006,x.current=Math.max(-Math.PI/2,Math.min(Math.PI/2,x.current+A*.006)),g.current={x:w.clientX,y:w.clientY}},z=()=>{b.current=!1,window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",z)};window.addEventListener("mousemove",T),window.addEventListener("mouseup",z)},[]),k=c.useCallback(K=>{if(y.current)return;const T=K.currentTarget.getBoundingClientRect(),z=M(K.clientX-T.left,K.clientY-T.top);o(z===n?null:z)},[M,o,n]),L=c.useCallback(K=>{if(b.current)return;const T=K.currentTarget.getBoundingClientRect(),z=M(K.clientX-T.left,K.clientY-T.top);i(z),K.currentTarget.style.cursor=z?"pointer":"grab"},[M,i]),$=c.useCallback(()=>{i(null)},[i]),C=c.useCallback(K=>{K.preventDefault();const T=K.deltaY<0?1.1:.91;f.current=Math.max(.3,Math.min(3,f.current*T))},[]),I=c.useCallback(()=>{p.current=0,x.current=-.25,f.current=1},[]);return{canvasRef:l,containerRef:u,size:d,handleMouseDown:B,handleClick:k,handleMouseMove:L,handleMouseLeave:$,handleWheel:C,resetView:I}}function Rz({nodeId:t,graph:n,allMemories:s,allLinks:r,onClose:a,onDelete:o,onLink:i,onSelectNode:l}){const u=n.agents.find(m=>m.id===t),d=n.mems.find(m=>m.id===t);if(u){const m=n.mems.filter(p=>p.agentId===u.id);return e.jsxs("aside",{className:"w-72 shrink-0 border-l border-border flex flex-col bg-background/95 backdrop-blur",children:[e.jsxs("header",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-full shrink-0",style:{background:u.color}}),e.jsx("span",{className:"text-sm font-semibold flex-1 truncate",children:u.name}),e.jsx("button",{onClick:a,className:"text-muted-foreground/50 hover:text-foreground",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"px-4 py-3 border-b border-border",children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 px-3 py-2.5",children:[e.jsx("p",{className:"text-xl font-bold",style:{color:u.color},children:u.memCount}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Memories"})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60",children:"Memory Clusters"}),e.jsx("div",{className:"flex flex-col gap-1",children:m.map(p=>e.jsxs("button",{onClick:()=>l(p.id),className:"flex items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full shrink-0",style:{background:oa(p.memoryType)}}),e.jsx("span",{className:"flex-1 truncate text-foreground/80",children:p.title}),e.jsx("span",{className:"text-[10px] capitalize rounded-full px-1.5 py-0.5",style:{color:oa(p.memoryType),background:`${oa(p.memoryType)}18`},children:p.memoryType})]},p.id))}),e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60 mt-2",children:"Activity"}),e.jsx("div",{className:"flex items-end gap-0.5 h-10",children:Array.from({length:14},(p,x)=>{const f=18+Math.sin(x*1.3+u.id.length)*12;return e.jsx("div",{className:"flex-1 rounded-t-sm",style:{height:`${f}px`,background:u.color,opacity:.25+x/14*.55}},x)})})]})]})}if(d){const m=n.agents.find(x=>x.id===d.agentId),p=r.filter(x=>x.sourceMemoryId===d.id||x.targetMemoryId===d.id).map(x=>{const f=x.sourceMemoryId===d.id?x.targetMemoryId:x.sourceMemoryId;return s.find(h=>h.id===f)}).filter(Boolean);return e.jsxs("aside",{className:"w-72 shrink-0 border-l border-border flex flex-col bg-background/95 backdrop-blur",children:[e.jsxs("header",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-full shrink-0",style:{background:oa(d.memoryType)}}),e.jsx("span",{className:"text-sm font-semibold flex-1 truncate",children:d.title}),e.jsx("button",{onClick:a,className:"text-muted-foreground/50 hover:text-foreground",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"rounded-full px-2.5 py-1 text-[10px] font-medium capitalize text-white",style:{background:oa(d.memoryType)},children:d.memoryType}),m&&e.jsxs("button",{onClick:()=>l(m.id),className:"flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10px] font-medium hover:opacity-80 transition-opacity",style:{background:`${m.color}18`,border:`1px solid ${m.color}35`,color:m.color},children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full",style:{background:m.color}}),m.name]})]}),d.content&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60 mb-1.5",children:"Content"}),e.jsx("p",{className:"text-foreground/75 leading-relaxed whitespace-pre-wrap",children:d.content})]}),e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3 font-mono text-[10px] leading-relaxed whitespace-pre",children:[e.jsx("span",{className:"text-muted-foreground/40",children:"// "}),m&&e.jsxs("span",{style:{color:m.color},children:["@",m.name]}),`
|
|
220
|
+
`,e.jsx("span",{className:"text-muted-foreground/60",children:"type: "}),e.jsxs("span",{style:{color:oa(d.memoryType)},children:['"',d.memoryType,'"']}),`
|
|
221
|
+
`,e.jsx("span",{className:"text-muted-foreground/60",children:"active: "}),e.jsx("span",{className:"text-emerald-500",children:"true"})]}),p.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60 mb-1.5",children:["Linked (",p.length,")"]}),e.jsx("div",{className:"flex flex-col gap-1",children:p.map(x=>e.jsxs("button",{onClick:()=>l(x.id),className:"flex items-center gap-2 rounded-md px-2.5 py-1.5 hover:bg-accent transition-colors text-left",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full shrink-0",style:{background:oa(x.memoryType)}}),e.jsx("span",{className:"truncate text-foreground/70",children:x.title})]},x.id))})]})]}),e.jsxs("footer",{className:"px-4 py-3 border-t border-border flex gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"flex-1 h-7 text-xs",onClick:()=>i(d.id),children:[e.jsx(oy,{className:"h-3 w-3 mr-1.5"}),"Link"]}),e.jsx(G,{size:"sm",variant:"outline",className:"h-7 text-xs text-destructive border-destructive/20 hover:border-destructive/40",onClick:()=>o(d.id),children:e.jsx(Ls,{className:"h-3 w-3"})})]})]})}return null}function Pz({onClose:t,onAdd:n}){const[s,r]=c.useState(""),[a,o]=c.useState(""),[i,l]=c.useState("fact");return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:t,children:e.jsxs("div",{className:"bg-background border border-border rounded-xl shadow-2xl w-[480px] p-5 flex flex-col gap-4",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Add Memory Node"}),e.jsx("button",{onClick:t,className:"text-muted-foreground/50 hover:text-foreground",children:e.jsx(zt,{className:"h-4 w-4"})})]}),e.jsx("input",{autoFocus:!0,value:s,onChange:u=>r(u.target.value),placeholder:"Title *",className:"w-full text-sm bg-muted/40 border border-border rounded-md px-3 py-2 outline-none focus:ring-1 focus:ring-primary placeholder:text-muted-foreground/40"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Iz.map(u=>e.jsx("button",{onClick:()=>l(u),className:O("px-2.5 py-1 text-[11px] font-medium rounded-full border capitalize transition-colors",i===u?"text-white border-transparent":"border-border text-muted-foreground hover:border-foreground/30"),style:i===u?{background:oa(u)}:{},children:u},u))}),e.jsx("textarea",{value:a,onChange:u=>o(u.target.value),placeholder:"Details (optional)…",rows:3,className:"w-full text-sm bg-muted/40 border border-border rounded-md px-3 py-2 outline-none focus:ring-1 focus:ring-primary resize-none placeholder:text-muted-foreground/40"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),e.jsx(G,{size:"sm",disabled:!s.trim(),onClick:()=>n({title:s.trim(),content:a,memoryType:i}),children:"Add Memory"})]})]})})}function Mz({sourceMemory:t,memories:n,onClose:s,onLink:r}){const[a,o]=c.useState(""),[i,l]=c.useState("related_to"),[u,d]=c.useState("");return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:s,children:e.jsxs("div",{className:"bg-background border border-border rounded-xl shadow-2xl w-[420px] p-5 flex flex-col gap-4",onClick:m=>m.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Link Memory"}),e.jsx("button",{onClick:s,className:"text-muted-foreground/50 hover:text-foreground",children:e.jsx(zt,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Linking from: ",e.jsx("span",{className:"font-medium text-foreground",children:t.title})]}),e.jsxs("select",{value:a,onChange:m=>o(m.target.value),className:"w-full text-sm bg-muted/40 border border-border rounded-md px-3 py-2 outline-none",children:[e.jsx("option",{value:"",children:"Select a memory…"}),n.filter(m=>m.id!==t.id).map(m=>e.jsx("option",{value:m.id,children:m.title},m.id))]}),e.jsx("select",{value:i,onChange:m=>l(m.target.value),className:"w-full text-sm bg-muted/40 border border-border rounded-md px-3 py-2 outline-none",children:["related_to","supports","contradicts","precedes","derived_from","example_of"].map(m=>e.jsx("option",{value:m,children:m.replace(/_/g," ")},m))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),e.jsx(G,{size:"sm",disabled:!a,onClick:()=>r(a,i,u),children:"Create Link"})]})]})})}function $z(){const{selectedCompanyId:t}=et(),n=at(),[s,r]=c.useState(null),[a,o]=c.useState(null),[i,l]=c.useState(null),[u,d]=c.useState(""),[m,p]=c.useState(!1),[x,f]=c.useState(null),{data:h,isLoading:j}=oe({queryKey:N.memories.graph(t),queryFn:()=>Bi.getGraph(t),enabled:!!t,refetchInterval:3e4}),b=(h==null?void 0:h.memories)??[],g=(h==null?void 0:h.links)??[],y=c.useMemo(()=>Az(b,g),[b,g]),{canvasRef:v,containerRef:_,size:E,handleMouseDown:S,handleClick:M,handleMouseMove:B,handleMouseLeave:k,handleWheel:L,resetView:$}=Tz({graph:y,selectedId:s,hoveredId:a,filterAgentId:i,search:u,onSelect:r,onHover:o}),C=ge({mutationFn:F=>Bi.create(t,F),onSuccess:()=>{n.invalidateQueries({queryKey:N.memories.graph(t)}),p(!1)}}),I=ge({mutationFn:F=>Bi.remove(F),onSuccess:()=>{n.invalidateQueries({queryKey:N.memories.graph(t)}),r(null)}}),K=ge({mutationFn:F=>Bi.createLink(t,{sourceMemoryId:x,targetMemoryId:F.targetId,relationshipType:F.rel,label:F.label||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:N.memories.graph(t)}),f(null)}}),T=x?b.find(F=>F.id===x)??null:null,{agents:z}=y,w=s&&(z.some(F=>F.id===s)||y.mems.some(F=>F.id===s));return e.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[e.jsxs("div",{className:"flex shrink-0 items-center gap-3 border-b border-border px-4 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ko,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"Memory Graph"}),b.length>0&&e.jsxs("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[10px] text-muted-foreground tabular-nums",children:[z.length," agents · ",b.length," nodes"]})]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative max-w-48",children:[e.jsx(ws,{className:"absolute left-2.5 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground/50"}),e.jsx("input",{value:u,onChange:F=>d(F.target.value),placeholder:"Search memories…",className:"w-full rounded-md border border-border bg-muted/40 pl-7 pr-3 py-1.5 text-xs outline-none placeholder:text-muted-foreground/40 focus:border-primary/50"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l(null),className:O("rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors border",i?"border-border text-muted-foreground hover:border-foreground/20 hover:text-foreground":"bg-foreground text-background border-transparent"),children:"All"}),z.map(F=>e.jsx("button",{onClick:()=>l(i===F.id?null:F.id),className:"rounded-full px-2.5 py-1 text-[11px] font-medium border transition-colors",style:i===F.id?{color:F.color,background:`${F.color}18`,borderColor:`${F.color}50`}:{color:"hsl(var(--muted-foreground))",background:"transparent",borderColor:"hsl(var(--border))"},children:F.name.split(" ")[0]},F.id))]})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[b.length>0&&e.jsxs("button",{onClick:$,title:"Reset view",className:"flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-[11px] text-muted-foreground hover:text-foreground hover:bg-accent transition-colors",children:[e.jsx(Wr,{className:"h-3 w-3"}),"Reset"]}),e.jsxs(G,{size:"sm",onClick:()=>p(!0),children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1.5"}),"Add Memory"]})]})]}),e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{ref:_,className:"relative flex-1 min-w-0 overflow-hidden",children:[j?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(Ko,{className:"h-8 w-8 animate-pulse text-primary/40"})}):b.length===0?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full bg-muted",children:e.jsx(Ko,{className:"h-7 w-7 text-muted-foreground/50"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"No memories yet"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground max-w-56",children:"Agents learn and grow their knowledge graph as they work."})]}),e.jsxs(G,{size:"sm",onClick:()=>p(!0),children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1.5"}),"Add First Memory"]})]})}):e.jsx("canvas",{ref:v,width:E.w,height:E.h,className:"absolute inset-0 cursor-grab active:cursor-grabbing",onMouseDown:S,onClick:M,onMouseMove:B,onMouseLeave:k,onWheel:L}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"pointer-events-none absolute bottom-3 left-3 flex flex-col gap-1.5 rounded-lg border border-border bg-background/90 px-3 py-2.5 text-[10px] backdrop-blur",children:[e.jsx("p",{className:"font-semibold text-foreground/70 mb-0.5",children:"Legend"}),e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx("div",{className:"h-3 w-3 rounded-full border border-amber-400 bg-amber-400/20"}),e.jsx("span",{children:"Agent Node"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx("div",{className:"h-2 w-2 rounded-full border border-indigo-400 bg-indigo-400/20"}),e.jsx("span",{children:"Memory Node"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx("div",{className:"w-4 border-t border-dashed border-muted-foreground/40"}),e.jsx("span",{children:"Orbit link"})]})]}),e.jsx("p",{className:"pointer-events-none absolute bottom-3 right-3 text-[10px] text-muted-foreground/40",children:"Drag to rotate · Scroll to zoom · Click to inspect"})]})]}),w&&s&&e.jsx(Rz,{nodeId:s,graph:y,allMemories:b,allLinks:g,onClose:()=>r(null),onDelete:F=>I.mutate(F),onLink:F=>{f(F),r(null)},onSelectNode:r})]}),m&&e.jsx(Pz,{onClose:()=>p(!1),onAdd:F=>C.mutate(F)}),T&&e.jsx(Mz,{sourceMemory:T,memories:b,onClose:()=>f(null),onLink:(F,A,R)=>K.mutate({targetId:F,rel:A,label:R})})]})}const Dz={running:"#22d3ee",active:"#4ade80",paused:"#facc15",idle:"#facc15",error:"#f87171",terminated:"#a3a3a3"};function jc(t){return Dz[t]??"#a3a3a3"}function _b(t){return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}async function Oz(t,n,s,r,a){const o=n.map(l=>({role:l.role==="user"?"user":"assistant",content:l.content}));let i="";try{for await(const l of We.chatStream(t.id,o,s,r))i+=l,a(i)}catch(l){if(l.name==="AbortError")return i;const u=l instanceof Error?l.message:String(l);return i||`I couldn't be reached right now (${u}).`}return i||"I didn't produce a response. Please try again."}function Lz(t){const n=Date.now()-t.getTime(),s=Math.floor(n/6e4);if(s<1)return"now";if(s<60)return`${s}m`;const r=Math.floor(s/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function Fz({allAgents:t,onStart:n}){const[s,r]=c.useState(!1),[a,o]=c.useState(""),[i,l]=c.useState(new Set),u=c.useRef(null);c.useEffect(()=>{if(!s)return;const x=f=>{var h;(h=u.current)!=null&&h.contains(f.target)||(r(!1),l(new Set))};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[s]);const d=t.filter(x=>x.name.toLowerCase().includes(a.toLowerCase())),m=x=>l(f=>{const h=new Set(f);return h.has(x)?h.delete(x):h.add(x),h}),p=()=>{const x=t.filter(f=>i.has(f.id));x.length!==0&&(n(x),r(!1),o(""),l(new Set))};return e.jsxs("div",{ref:u,className:"relative",children:[e.jsxs(G,{size:"sm",onClick:()=>r(x=>!x),children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mr-1.5"}),"New Chat"]}),s&&e.jsxs("div",{className:"absolute top-9 right-0 z-50 w-60 bg-popover border border-border rounded-lg shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(ws,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx("input",{autoFocus:!0,value:a,onChange:x=>o(x.target.value),placeholder:"Search agents…",className:"flex-1 text-xs bg-transparent outline-none text-foreground placeholder:text-muted-foreground"})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto py-1",children:d.length===0?e.jsx("p",{className:"text-xs text-muted-foreground px-3 py-2",children:"No agents found"}):d.map(x=>{const f=i.has(x.id);return e.jsxs("button",{onClick:()=>m(x.id),className:O("w-full flex items-center gap-2.5 px-3 py-2 hover:bg-accent/50 transition-colors text-left",f&&"bg-accent/30"),children:[e.jsx("div",{className:O("w-3.5 h-3.5 rounded border shrink-0 flex items-center justify-center transition-colors",f?"bg-primary border-primary":"border-border"),children:f&&e.jsx(Nn,{className:"h-2 w-2 text-primary-foreground"})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Cn,{icon:x.icon,className:"h-3 w-3 text-foreground/60"})}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-1.5 h-1.5 rounded-full border border-popover",style:{backgroundColor:jc(x.status)}})]}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-foreground truncate",children:x.name}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate",children:x.title??x.role})]})]},x.id)})}),e.jsx("div",{className:"px-3 py-2 border-t border-border",children:e.jsxs(G,{size:"sm",className:"w-full h-8 text-xs",disabled:i.size===0,onClick:p,children:["Start Chat ",i.size>0&&`(${i.size})`]})})]})]})}function qz({allAgents:t,participants:n,onAdd:s}){const[r,a]=c.useState(!1),[o,i]=c.useState(""),l=c.useRef(null);c.useEffect(()=>{if(!r)return;const m=p=>{var x;(x=l.current)!=null&&x.contains(p.target)||a(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[r]);const u=new Set(n.map(m=>m.id)),d=t.filter(m=>!u.has(m.id)&&m.name.toLowerCase().includes(o.toLowerCase()));return t.length<=n.length?null:e.jsxs("div",{ref:l,className:"relative",children:[e.jsx("button",{onClick:()=>a(m=>!m),className:"flex items-center justify-center w-6 h-6 rounded-full border border-dashed border-border hover:border-foreground/40 hover:bg-muted/50 transition-colors",title:"Add agent",children:e.jsx(Mp,{className:"h-3 w-3 text-muted-foreground"})}),r&&e.jsxs("div",{className:"absolute top-8 left-0 z-50 w-48 bg-popover border border-border rounded-lg shadow-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(ws,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx("input",{autoFocus:!0,value:o,onChange:m=>i(m.target.value),placeholder:"Add agent…",className:"flex-1 text-xs bg-transparent outline-none text-foreground placeholder:text-muted-foreground"})]}),e.jsx("div",{className:"max-h-44 overflow-y-auto py-1",children:d.map(m=>e.jsxs("button",{onClick:()=>{s(m)},className:"w-full flex items-center gap-2 px-3 py-1.5 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(Cn,{icon:m.icon,className:"h-2.5 w-2.5 text-foreground/60"})}),e.jsx("span",{className:"text-xs text-foreground truncate",children:m.name})]},m.id))})]})]})}function Uz({session:t,isActive:n,onSelect:s}){const r=t.messages[t.messages.length-1],a=t.participants.slice(0,3),o=t.participants.length-3;return e.jsxs("button",{onClick:s,className:O("w-full flex items-start gap-3 px-4 py-3 hover:bg-accent/40 transition-colors text-left border-b border-border/30",n&&"bg-primary/6 border-l-2 border-l-primary"),children:[e.jsxs("div",{className:"relative shrink-0 h-8 w-10 mt-0.5",children:[a.map((i,l)=>e.jsx("div",{className:"absolute w-6 h-6 rounded-full bg-muted border-2 border-card flex items-center justify-center",style:{left:l*6,top:l*2,zIndex:a.length-l},children:e.jsx(Cn,{icon:i.icon,className:"h-3 w-3 text-foreground/60"})},i.id)),o>0&&e.jsx("div",{className:"absolute w-6 h-6 rounded-full bg-muted border-2 border-card flex items-center justify-center",style:{left:18,top:6,zIndex:0},children:e.jsxs("span",{className:"text-[8px] text-muted-foreground font-medium",children:["+",o]})})]}),e.jsxs("div",{className:"flex flex-col min-w-0 flex-1 gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate leading-tight",children:t.participants.map(i=>i.name).join(", ")}),e.jsx("span",{className:"text-[10px] text-muted-foreground/50 shrink-0 tabular-nums",children:Lz(t.updatedAt)})]}),e.jsx("span",{className:"text-xs text-muted-foreground truncate leading-snug",children:r?`${r.role==="user"?"You: ":""}${r.content}`:"No messages yet"})]})]})}function Bz({session:t,allAgents:n,companyId:s,onUpdate:r}){var I;const{openNewIssue:a}=In(),o=at(),i=c.useRef(!0),l=c.useRef(null);c.useEffect(()=>()=>{var K;i.current=!1,(K=l.current)==null||K.abort()},[]);const[u,d]=c.useState([]),[m,p]=c.useState([]);c.useEffect(()=>{var K;d(t.participants),t.messages.length>0?p(t.messages):p([{id:"welcome",role:"agent",agentId:t.primaryAgentId,content:`Hi! I'm ${((K=t.participants[0])==null?void 0:K.name)??"here"}. How can I help?`,ts:new Date}])},[t.id]);const[x,f]=c.useState(""),[h,j]=c.useState(null),[b,g]=c.useState(null),[y,v]=c.useState(!1),_=c.useRef(null),E=c.useRef(null),S=c.useRef(!0);c.useEffect(()=>{if(S.current){S.current=!1;return}r(m,u)},[m,u]),c.useEffect(()=>{_.current&&(_.current.scrollTop=_.current.scrollHeight)},[m,h]),c.useEffect(()=>{var K;(K=E.current)==null||K.focus()},[t.id]);const M=c.useCallback(async()=>{const K=x.trim();if(!K||h)return;g(null);const T={id:`user-${Date.now()}`,role:"user",content:K,ts:new Date},z=[...m,T];p(w=>[...w,T]),f(""),l.current=new AbortController;for(const w of u){if(!i.current)break;j(w.id);const F=`agent-${w.id}-${Date.now()}`;p(Q=>[...Q,{id:F,role:"agent",agentId:w.id,content:"",ts:new Date}]);let A="";const R=await Oz(w,z,s,l.current.signal,Q=>{i.current&&(A=Q,p(H=>H.map(U=>U.id===F?{...U,content:Q}:U)))});!A&&R&&(A=R,p(Q=>Q.map(H=>H.id===F?{...H,content:R}:H))),j(null),A.trim()&&s&&i.current&&(v(!0),(async()=>{try{const Q=A.split(/[.!?]+/).map(U=>U.trim()).filter(U=>U.length>10&&U.length<200),H=Q.length>0?Q[0].slice(0,120):A.slice(0,100);if(await fetch(`/api/companies/${s}/memories`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:H,content:A,memoryType:"fact",agentIds:[w.id]})}),A.length>200){const U=m.filter(Z=>Z.role==="user").pop();await Bi.saveTaskSolution(s,{agentId:w.id,taskTitle:(U==null?void 0:U.content.slice(0,80))??H,approach:A,outcome:"Completed"})}o.invalidateQueries({queryKey:N.memories.graph(s)})}catch{}finally{v(!1)}})())}},[x,m,u,s,h]),B=K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),M())},k=K=>{d(T=>[...T,K]),p(T=>[...T,{id:`join-${K.id}-${Date.now()}`,role:"agent",agentId:K.id,content:`Hey everyone! ${K.name} here. Joining the conversation.`,ts:new Date}])},L=K=>{u.length<=1||d(T=>T.filter(z=>z.id!==K))},$=K=>u.find(T=>T.id===K),C=c.useCallback(()=>{const K=m.filter(T=>T.content.trim()).slice(-8).map(T=>{if(T.role==="user")return`**You:** ${T.content}`;const z=T.agentId?$(T.agentId):null;return`**${(z==null?void 0:z.name)??"Agent"}:** ${T.content}`}).join(`
|
|
222
|
+
|
|
223
|
+
`);a({description:K?`*From chat discussion:*
|
|
224
|
+
|
|
225
|
+
${K}`:void 0})},[m,u,a]);return e.jsxs("div",{className:"flex flex-col flex-1 min-h-0 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-border shrink-0 bg-card/30",children:e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0 flex-wrap",children:[u.map(K=>e.jsxs("div",{className:"flex items-center gap-1.5 bg-muted/60 border border-border rounded-full pl-1.5 pr-2 py-0.5",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Cn,{icon:K.icon,className:"h-2.5 w-2.5 text-foreground/70"})}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-1.5 h-1.5 rounded-full border border-card",style:{backgroundColor:jc(K.status)}})]}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:K.name}),u.length>1&&e.jsx("button",{onClick:()=>L(K.id),className:"ml-0.5 text-muted-foreground/40 hover:text-foreground transition-colors",children:e.jsx(zt,{className:"h-2.5 w-2.5"})})]},K.id)),e.jsx(qz,{allAgents:n,participants:u,onAdd:k})]})}),e.jsxs("div",{ref:_,className:"flex-1 overflow-y-auto px-5 py-5 space-y-4 min-h-0",children:[m.map(K=>{if(K.role==="agent"&&!K.content&&h)return null;if(K.role==="user")return e.jsx("div",{className:"flex justify-end",children:e.jsxs("div",{className:"flex flex-col items-end gap-1 max-w-[70%]",children:[e.jsx("div",{className:"px-4 py-2.5 text-sm leading-relaxed bg-primary text-primary-foreground rounded-2xl rounded-br-sm",children:K.content}),e.jsx("span",{className:"text-[10px] text-muted-foreground/40 px-1",children:_b(K.ts)})]})},K.id);const T=K.agentId?$(K.agentId):null,z=jc(K.agentId?(T==null?void 0:T.status)??"idle":"idle");return e.jsxs("div",{className:"flex gap-3 items-end",children:[e.jsxs("div",{className:"relative shrink-0 mb-0.5",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Cn,{icon:T?T.icon:void 0,className:"h-3.5 w-3.5 text-foreground/60"})}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full border-2 border-background",style:{backgroundColor:z}})]}),e.jsxs("div",{className:"flex flex-col gap-0.5 max-w-[70%]",children:[u.length>1&&T&&e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground px-1",children:T.name}),e.jsx("div",{className:"px-4 py-2.5 text-sm leading-relaxed bg-accent text-foreground rounded-2xl rounded-bl-sm whitespace-pre-wrap",children:K.content}),e.jsx("span",{className:"text-[10px] text-muted-foreground/40 px-1",children:_b(K.ts)})]})]},K.id)}),h&&(()=>{const K=$(h);return e.jsxs("div",{className:"flex gap-3 items-end",children:[e.jsxs("div",{className:"relative shrink-0 mb-0.5",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Cn,{icon:K?K.icon:void 0,className:"h-3.5 w-3.5 text-foreground/60"})}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full border-2 border-background",style:{backgroundColor:jc((K==null?void 0:K.status)??"idle")}})]}),e.jsx("div",{className:"bg-accent px-4 py-3 rounded-2xl rounded-bl-sm",children:e.jsx("div",{className:"flex gap-1 items-center h-4",children:[0,150,300].map(T=>e.jsx("span",{className:"w-1.5 h-1.5 bg-muted-foreground/40 rounded-full animate-bounce",style:{animationDelay:`${T}ms`}},T))})})]})})(),b&&e.jsxs("div",{className:"flex items-start gap-2 px-1",children:[e.jsx(_d,{className:"h-3.5 w-3.5 text-destructive shrink-0 mt-0.5"}),e.jsx("span",{className:"text-sm text-destructive",children:b})]}),y&&e.jsxs("div",{className:"flex items-center gap-2 px-1 text-xs text-muted-foreground/60",children:[e.jsx(Ko,{className:"h-3.5 w-3.5 animate-pulse shrink-0"}),e.jsx("span",{children:"Saving to memory graph…"})]})]}),e.jsx("div",{className:"px-5 pt-2 shrink-0",children:e.jsxs("button",{onClick:C,className:"w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg border border-dashed border-border text-xs font-medium text-muted-foreground hover:border-foreground/30 hover:text-foreground hover:bg-accent/30 transition-colors",children:[e.jsx(rs,{className:"h-3.5 w-3.5"}),"Create issue from this chat"]})}),e.jsxs("div",{className:"border-t border-border px-5 py-4 shrink-0 bg-card/20 mt-2",children:[e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ur,{ref:E,value:x,onChange:K=>f(K.target.value),onKeyDown:B,placeholder:u.length>1?`Message ${u.length} agents…`:`Message ${((I=u[0])==null?void 0:I.name)??"agent"}…`,className:"min-h-[40px] max-h-32 resize-none text-sm py-2.5 leading-relaxed",rows:1,disabled:!!h}),e.jsx(G,{size:"icon",className:"h-10 w-10 shrink-0",onClick:M,disabled:!x.trim()||!!h,children:e.jsx(B1,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground/30 mt-1.5 select-none",children:h?"Waiting for response…":"Enter to send · Shift+Enter for new line"})]})]})}function Kz({onNewChat:t}){return e.jsxs("div",{className:"flex flex-col items-center justify-center flex-1 gap-5 text-center px-6",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-muted flex items-center justify-center",children:e.jsx(wc,{className:"h-8 w-8 text-muted-foreground/40"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:"No conversation selected"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-64",children:"Start a new chat to interact with your agents in real time."})]}),e.jsxs(G,{onClick:t,children:[e.jsx(Ot,{className:"h-4 w-4 mr-2"}),"Start a Chat"]})]})}function zz(){const{sessions:t,activeSessionId:n,setActiveSessionId:s,openChatWithAgents:r,updateSession:a,bulkInitSessions:o}=Rx(),{selectedCompanyId:i}=et();c.useRef(null);const{data:l}=oe({queryKey:N.agents.list(i),queryFn:()=>We.list(i),enabled:!!i,refetchInterval:3e4}),u=c.useMemo(()=>l??[],[l]);c.useEffect(()=>{u.length>0&&o(u)},[u,o]);const d=c.useMemo(()=>t.find(h=>h.id===n)??null,[t,n]),m=c.useMemo(()=>[...t].sort((h,j)=>j.updatedAt.getTime()-h.updatedAt.getTime()),[t]),p=c.useCallback((h,j)=>{n&&a(n,h,j)},[n,a]),[x,f]=c.useState(!1);return c.useRef(null),e.jsxs("div",{className:"flex h-full min-h-0 bg-background",children:[e.jsxs("div",{className:"w-72 shrink-0 border-r border-border flex flex-col bg-card/30",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 h-13 shrink-0 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-semibold",children:"Agent Chat"}),t.length>0&&e.jsx("span",{className:"text-[10px] text-muted-foreground bg-muted rounded-full px-1.5 py-0.5 leading-none tabular-nums",children:t.length})]}),e.jsx(Fz,{allAgents:u,onStart:h=>{r(h)}})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:m.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center px-4 py-10 gap-3 text-center",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-muted flex items-center justify-center",children:e.jsx(wc,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"No conversations yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Click New Chat to get started"})]})]}):m.map(h=>e.jsx(Uz,{session:h,isActive:h.id===n,onSelect:()=>s(h.id===n?null:h.id)},h.id))})]}),d?e.jsx(Bz,{session:d,allAgents:u,companyId:i??void 0,onUpdate:p},d.id):e.jsx(Kz,{onNewChat:()=>{}})]})}function tk(t){if(!t)return"—";const n=Date.now()-new Date(t).getTime(),s=Math.floor(n/6e4);if(s<1)return"just now";if(s<60)return`${s}m ago`;const r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Wz(t){return{critical:"bg-red-500",high:"bg-orange-500",medium:"bg-yellow-500",low:"bg-blue-400"}[t]??"bg-muted-foreground"}function Hz({issue:t,onUnblock:n,selected:s,onToggleSelect:r}){return e.jsxs("div",{className:O("group flex flex-col gap-2 rounded-lg border p-3.5 transition-colors cursor-pointer",s?"border-red-400 dark:border-red-700 bg-red-100 dark:bg-red-950/40":"border-red-200 dark:border-red-900/40 bg-red-50 dark:bg-red-950/20 hover:border-red-300 dark:hover:border-red-800"),onClick:r,children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("input",{type:"checkbox",checked:s,onChange:r,onClick:a=>a.stopPropagation(),className:"mt-1 shrink-0 accent-red-500"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("span",{className:"text-[11px] font-mono text-muted-foreground",children:t.identifier}),e.jsx("div",{className:O("w-1.5 h-1.5 rounded-full shrink-0",Wz(t.priority)),title:t.priority})]}),e.jsx(Oe,{to:`/issues/${t.identifier}`,className:"text-sm font-medium text-foreground hover:text-primary line-clamp-2 leading-snug",onClick:a=>a.stopPropagation(),children:t.title}),t.description&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground line-clamp-2 leading-relaxed",children:t.description})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 ml-6",children:[e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_r,{className:"h-3 w-3"}),tk(t.updatedAt)]}),t.assigneeAgentId&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ss,{className:"h-3 w-3"}),"Agent assigned"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:a=>a.stopPropagation(),children:[e.jsxs(G,{size:"sm",variant:"outline",className:"h-6 text-[11px] px-2 gap-1 border-red-200 dark:border-red-900",onClick:n,children:[e.jsx(Wr,{className:"h-3 w-3"}),"Set to Todo"]}),e.jsx(Oe,{to:`/issues/${t.identifier}`,onClick:a=>a.stopPropagation(),children:e.jsx(G,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(Is,{className:"h-3 w-3"})})})]})]})]})}function Vz({run:t,selected:n,onToggleSelect:s}){const r={failed:"Failed",error:"Error",terminated:"Killed",timed_out:"Timed out"},a=t.error??t.stderrExcerpt;return e.jsxs("div",{className:O("group flex flex-col gap-2 rounded-lg border p-3.5 transition-colors cursor-pointer",n?"border-orange-400 dark:border-orange-700 bg-orange-100 dark:bg-orange-950/40":"border-orange-200 dark:border-orange-900/40 bg-orange-50 dark:bg-orange-950/20 hover:border-orange-300 dark:hover:border-orange-800"),onClick:s,children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:s,onClick:o=>o.stopPropagation(),className:"mt-1 shrink-0 accent-orange-500"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("span",{className:"text-xs font-medium text-foreground",children:t.agentName??"Agent"}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-orange-100 text-orange-700 dark:bg-orange-900/50 dark:text-orange-300",children:r[t.status]??t.status})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t.triggerDetail??t.invocationSource}),a&&e.jsx("p",{className:"mt-1.5 text-[11px] font-mono text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950/30 rounded px-2 py-1 line-clamp-2 leading-relaxed",children:a.slice(0,200)})]})]}),e.jsxs("div",{className:"flex items-center justify-between ml-6",children:[e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(_r,{className:"h-3 w-3"}),tk(t.finishedAt??t.createdAt)]}),e.jsx(Oe,{to:`/agents/${t.agentId}`,className:"opacity-0 group-hover:opacity-100 transition-opacity",onClick:o=>o.stopPropagation(),children:e.jsxs(G,{size:"sm",variant:"ghost",className:"h-6 text-[11px] px-2 gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),"Agent"]})})]})]})}function Qz({selectedIssueIds:t,selectedRunIds:n,selectedRuns:s,onMarkDone:r,onCreateIssues:a,onClear:o,isLoading:i}){const l=t.length+n.length;return l===0?null:e.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 rounded-xl border border-border bg-background shadow-xl px-4 py-2.5",children:[e.jsxs("span",{className:"text-sm font-medium text-foreground tabular-nums",children:[l," selected"]}),e.jsx("div",{className:"w-px h-4 bg-border"}),t.length>0&&e.jsxs(G,{size:"sm",variant:"default",className:"gap-1.5 text-xs bg-green-600 hover:bg-green-700 text-white",onClick:r,disabled:i,children:[e.jsx(ho,{className:"h-3.5 w-3.5"}),"Mark as Done (",t.length,")"]}),n.length>0&&e.jsxs(G,{size:"sm",variant:"default",className:"gap-1.5 text-xs",onClick:a,disabled:i,children:[e.jsx(Ja,{className:"h-3.5 w-3.5"}),"Create Issue (",n.length,")"]}),e.jsx(G,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:o,children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]})}function Gz(){const{selectedCompanyId:t}=et(),n=at(),[s,r]=c.useState(new Set),[a,o]=c.useState(new Set),{data:i=[],isLoading:l}=oe({queryKey:[...N.issues.list(t),"blocked"],queryFn:()=>nt.list(t,{status:"blocked"}),enabled:!!t,refetchInterval:2e4}),{data:u=[],isLoading:d}=oe({queryKey:N.heartbeats(t),queryFn:()=>Yt.list(t,void 0,100),enabled:!!t,refetchInterval:15e3}),m=c.useMemo(()=>{const _=new Set(["failed","error","terminated","timed_out"]);return u.filter(E=>_.has(E.status)).slice(0,30)},[u]),p=ge({mutationFn:_=>nt.update(_,{status:"todo"}),onSuccess:()=>{n.invalidateQueries({queryKey:N.issues.list(t)})}}),x=ge({mutationFn:_=>Promise.all(_.map(E=>nt.update(E,{status:"done"}))),onSuccess:()=>{r(new Set),n.invalidateQueries({queryKey:N.issues.list(t)})}}),f=ge({mutationFn:_=>Promise.all(_.map(E=>nt.create(t,{title:`Fix: ${E.agentName??"Agent"} run ${E.status}`,description:[E.triggerDetail??E.invocationSource,E.error??E.stderrExcerpt??""].filter(Boolean).join(`
|
|
226
|
+
|
|
227
|
+
`),priority:"high",status:"todo"}))),onSuccess:()=>{o(new Set),n.invalidateQueries({queryKey:N.issues.list(t)})}});function h(_){r(E=>{const S=new Set(E);return S.has(_)?S.delete(_):S.add(_),S})}function j(_){o(E=>{const S=new Set(E);return S.has(_)?S.delete(_):S.add(_),S})}const b=m.filter(_=>a.has(_.id)),g=l||d,y=i.length===0&&m.length===0,v=x.isPending||f.isPending;return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-border shrink-0",children:[e.jsx(Ja,{className:"h-5 w-5 text-red-500"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-base font-semibold text-foreground",children:"Alerts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Blocked issues and failed agent runs needing attention"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 text-xs",onClick:()=>{n.invalidateQueries({queryKey:N.issues.list(t)}),n.invalidateQueries({queryKey:N.heartbeats(t)})},children:[e.jsx(Za,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:g?e.jsx("div",{className:"flex items-center justify-center h-40 text-sm text-muted-foreground",children:"Loading blockers…"}):y?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-center py-20",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center",children:e.jsx(Ja,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"No blockers right now"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"All agents are running smoothly."})]})]}):e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 p-6 pb-20",children:[e.jsxs("section",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"Blocked Issues"}),e.jsx("span",{className:"text-[10px] bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300 rounded-full px-2 py-0.5 tabular-nums font-medium",children:i.length}),i.length>0&&e.jsx("button",{className:"ml-auto text-[11px] text-muted-foreground hover:text-foreground",onClick:()=>{s.size===i.length?r(new Set):r(new Set(i.map(_=>_.id)))},children:s.size===i.length?"Deselect all":"Select all"})]}),i.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-4 text-center border border-dashed border-border rounded-lg",children:"No blocked issues"}):e.jsx("div",{className:"flex flex-col gap-2",children:i.map(_=>e.jsx(Hz,{issue:_,onUnblock:()=>p.mutate(_.id),selected:s.has(_.id),onToggleSelect:()=>h(_.id)},_.id))})]}),e.jsxs("section",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"Failed Agent Runs"}),e.jsx("span",{className:"text-[10px] bg-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-300 rounded-full px-2 py-0.5 tabular-nums font-medium",children:m.length}),m.length>0&&e.jsx("button",{className:"ml-auto text-[11px] text-muted-foreground hover:text-foreground",onClick:()=>{a.size===m.length?o(new Set):o(new Set(m.map(_=>_.id)))},children:a.size===m.length?"Deselect all":"Select all"})]}),m.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-4 text-center border border-dashed border-border rounded-lg",children:"No recent failures"}):e.jsx("div",{className:"flex flex-col gap-2",children:m.map(_=>e.jsx(Vz,{run:_,selected:a.has(_.id),onToggleSelect:()=>j(_.id)},_.id))})]})]})}),e.jsx(Qz,{selectedIssueIds:[...s],selectedRunIds:[...a],selectedRuns:b,onMarkDone:()=>x.mutate([...s]),onCreateIssues:()=>f.mutate(b),onClear:()=>{r(new Set),o(new Set)},isLoading:v})]})}const yd={backlog:{label:"Backlog",icon:e.jsx(Yb,{className:"h-3.5 w-3.5 text-muted-foreground"}),border:"border-border",header:"bg-muted/30",cardBg:"bg-card hover:bg-accent/30",badge:"bg-muted text-muted-foreground"},todo:{label:"Todo",icon:e.jsx(rs,{className:"h-3.5 w-3.5 text-blue-500"}),border:"border-blue-200 dark:border-blue-900/50",header:"bg-blue-50 dark:bg-blue-950/30",cardBg:"bg-card hover:bg-blue-50/50 dark:hover:bg-blue-950/10",badge:"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"},in_progress:{label:"In Progress",icon:e.jsx(kn,{className:"h-3.5 w-3.5 text-yellow-500 animate-spin"}),border:"border-yellow-200 dark:border-yellow-900/50",header:"bg-yellow-50 dark:bg-yellow-950/30",cardBg:"bg-card hover:bg-yellow-50/50 dark:hover:bg-yellow-950/10",badge:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-300"},in_review:{label:"In Review",icon:e.jsx(pi,{className:"h-3.5 w-3.5 text-violet-500"}),border:"border-violet-200 dark:border-violet-900/50",header:"bg-violet-50 dark:bg-violet-950/30",cardBg:"bg-card hover:bg-violet-50/50 dark:hover:bg-violet-950/10",badge:"bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300"},blocked:{label:"Blocked",icon:e.jsx(K1,{className:"h-3.5 w-3.5 text-red-500"}),border:"border-red-200 dark:border-red-900/50",header:"bg-red-50 dark:bg-red-950/30",cardBg:"bg-card hover:bg-red-50/50 dark:hover:bg-red-950/10",badge:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"},done:{label:"Done",icon:e.jsx(ho,{className:"h-3.5 w-3.5 text-green-500"}),border:"border-green-200 dark:border-green-900/50",header:"bg-green-50 dark:bg-green-950/30",cardBg:"bg-card hover:bg-green-50/50 dark:hover:bg-green-950/10",badge:"bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300"},cancelled:{label:"Cancelled",icon:e.jsx(fi,{className:"h-3.5 w-3.5 text-neutral-400"}),border:"border-border",header:"bg-muted/20",cardBg:"bg-card hover:bg-accent/20 opacity-60",badge:"bg-muted text-muted-foreground"}},fp=["backlog","todo","in_progress","done"];function Jz(t){return{critical:"text-red-500",high:"text-orange-500",medium:"text-yellow-500",low:"text-blue-400"}[t]??"text-muted-foreground"}function Zz(t){return{critical:"!",high:"↑",medium:"–",low:"↓"}[t]??"–"}function Yz(t){if(!t)return"";const n=Date.now()-new Date(t).getTime(),s=Math.floor(n/6e4);if(s<1)return"just now";if(s<60)return`${s}m ago`;const r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Xz({issue:t,onStatusChange:n}){const s=yd[t.status]??yd.backlog;return e.jsx(Oe,{to:`/issues/${t.identifier}`,className:"block",children:e.jsxs("div",{className:O("rounded-md border px-3 py-2.5 transition-colors cursor-pointer",s.border,s.cardBg),children:[e.jsxs("div",{className:"flex items-start justify-between gap-1.5 mb-1",children:[e.jsx("span",{className:"text-[10px] font-mono text-muted-foreground shrink-0",children:t.identifier}),e.jsx("span",{className:O("text-[10px] font-bold shrink-0",Jz(t.priority)),children:Zz(t.priority)})]}),e.jsx("p",{className:"text-xs font-medium text-foreground leading-snug line-clamp-2",children:t.title}),t.updatedAt&&e.jsxs("p",{className:"mt-1.5 text-[10px] text-muted-foreground flex items-center gap-1",children:[e.jsx(_r,{className:"h-2.5 w-2.5"}),Yz(t.updatedAt)]})]})})}function e6({status:t,issues:n,onStatusChange:s,collapsed:r,onToggleCollapse:a}){const o=yd[t]??yd.backlog;return e.jsxs("div",{className:O("flex flex-col rounded-lg border min-w-0 transition-all",o.border,r?"w-10 shrink-0":"w-56 shrink-0"),children:[e.jsx("button",{onClick:a,className:O("flex items-center gap-2 px-3 py-2.5 rounded-t-lg border-b shrink-0 w-full text-left",o.header,o.border),children:r?e.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[e.jsx("span",{className:"text-[10px] font-medium text-foreground writing-mode-vertical rotate-180 [writing-mode:vertical-rl]",children:o.label}),e.jsx("span",{className:O("text-[9px] px-1 py-0.5 rounded font-medium",o.badge),children:n.length}),e.jsx(rn,{className:"h-3 w-3 text-muted-foreground mt-1"})]}):e.jsxs(e.Fragment,{children:[o.icon,e.jsx("span",{className:"text-xs font-semibold text-foreground flex-1",children:o.label}),e.jsx("span",{className:O("text-[10px] px-1.5 py-0.5 rounded-full font-medium tabular-nums",o.badge),children:n.length}),e.jsx(sy,{className:"h-3 w-3 text-muted-foreground"})]})}),!r&&e.jsx("div",{className:"flex-1 overflow-y-auto p-2 flex flex-col gap-1.5 min-h-[60px]",children:n.length===0?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx("p",{className:"text-[11px] text-muted-foreground/50",children:"No issues"})}):n.map(i=>e.jsx(Xz,{issue:i,onStatusChange:s},i.id))})]})}fp.join(",");function t6(){var x;const{selectedCompanyId:t}=et(),n=at(),[s,r]=c.useState(new Set),[a,o]=c.useState(!1),{data:i=[],isLoading:l}=oe({queryKey:[...N.issues.list(t),"taskboard",a],queryFn:async()=>(await Promise.all([nt.list(t,{status:"backlog",includeRoutineExecutions:a}),nt.list(t,{status:"todo",includeRoutineExecutions:a}),nt.list(t,{status:"in_progress",includeRoutineExecutions:a}),nt.list(t,{status:"done",includeRoutineExecutions:a})])).flat(),enabled:!!t,refetchInterval:3e4}),u=ge({mutationFn:({id:f,status:h})=>nt.update(f,{status:h}),onSuccess:()=>{n.invalidateQueries({queryKey:N.issues.list(t)})}}),d=c.useMemo(()=>{const f=new Map;for(const h of fp)f.set(h,[]);for(const h of i){const j=f.get(h.status);j&&j.push(h)}return f},[i]),m=c.useMemo(()=>["todo","in_progress"].reduce((f,h)=>{var j;return f+(((j=d.get(h))==null?void 0:j.length)??0)},0),[d]),p=f=>r(h=>{const j=new Set(h);return j.has(f)?j.delete(f):j.add(f),j});return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-border shrink-0",children:[e.jsx(rs,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-base font-semibold text-foreground",children:"Board"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m," active · ",((x=d.get("done"))==null?void 0:x.length)??0," done"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:a,onChange:f=>o(f.target.checked),className:"rounded"}),"Include routine tasks"]}),e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 text-xs",onClick:()=>n.invalidateQueries({queryKey:N.issues.list(t)}),children:[e.jsx(Za,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),l?e.jsx("div",{className:"flex items-center justify-center flex-1 text-sm text-muted-foreground",children:"Loading board…"}):e.jsx("div",{className:"flex-1 min-h-0 overflow-x-auto overflow-y-hidden",children:e.jsx("div",{className:"flex gap-3 p-4 h-full items-stretch min-w-max",children:fp.map(f=>e.jsx(e6,{status:f,issues:d.get(f)??[],onStatusChange:(h,j)=>u.mutate({id:h,status:j}),collapsed:s.has(f),onToggleCollapse:()=>p(f)},f))})})]})}const n6=new Set(["claude_local","codex_local","gemini_local","opencode_local","pi_local","cursor","hermes_local","openclaw_gateway"]);function s6(t){const{adapterType:n,...s}=io,r={...s,adapterType:t};return t==="codex_local"?(r.model=ii,r.dangerouslyBypassSandbox=fl):t==="gemini_local"?r.model=ci:t==="cursor"?r.model=li:t==="opencode_local"&&(r.model=""),r}function r6(){const{selectedCompanyId:t}=et(),{setBreadcrumbs:n}=Ft(),s=at(),r=Sn(),[a]=ui(),o=a.get("adapterType"),[i,l]=c.useState(""),[u,d]=c.useState(""),[m,p]=c.useState("general"),[x,f]=c.useState(null),[h,j]=c.useState(io),[b,g]=c.useState([]),[y,v]=c.useState(!1),[_,E]=c.useState(null),{data:S}=oe({queryKey:N.agents.list(t),queryFn:()=>We.list(t),enabled:!!t}),{data:M,error:B,isLoading:k,isFetching:L}=oe({queryKey:t?N.agents.adapterModels(t,h.adapterType):["agents","none","adapter-models",h.adapterType],queryFn:()=>We.adapterModels(t,h.adapterType),enabled:!!t}),{data:$}=oe({queryKey:N.companySkills.list(t??""),queryFn:()=>nr.list(t),enabled:!!t}),C=!S||S.length===0,I=C?"ceo":m;c.useEffect(()=>{n([{label:"Agents",href:"/agents"},{label:"New Agent"}])},[n]),c.useEffect(()=>{C&&(i||l("CEO"),u||d("CEO"))},[C]),c.useEffect(()=>{const A=o;A&&n6.has(A)&&j(R=>R.adapterType===A?R:s6(A))},[o]);const K=ge({mutationFn:A=>We.hire(t,A),onSuccess:A=>{s.invalidateQueries({queryKey:N.agents.list(t)}),s.invalidateQueries({queryKey:N.approvals.list(t)}),r(Na(A.agent))},onError:A=>{E(A instanceof Error?A.message:"Failed to create agent")}});function T(){return oo(h.adapterType).buildAdapterConfig(h)}function z(){if(!(!t||!i.trim())){if(E(null),h.adapterType==="opencode_local"){const A=h.model.trim();if(!A){E("OpenCode requires an explicit model in provider/model format.");return}if(B){E(B instanceof Error?B.message:"Failed to load OpenCode models.");return}if(k||L){E("OpenCode models are still loading. Please wait and try again.");return}const R=M??[];if(!R.some(Q=>Q.id===A)){E(R.length===0?"No OpenCode models discovered. Run `opencode models` and authenticate providers.":`Configured OpenCode model is unavailable: ${A}`);return}}K.mutate({name:i.trim(),role:I,...u.trim()?{title:u.trim()}:{},...x?{reportsTo:x}:{},...b.length>0?{desiredSkills:b}:{},adapterType:h.adapterType,adapterConfig:T(),runtimeConfig:{heartbeat:{enabled:h.heartbeatEnabled,intervalSec:h.intervalSec,wakeOnDemand:!0,cooldownSec:10,maxConcurrentRuns:1}},budgetMonthlyCents:0})}}const w=($??[]).filter(A=>!A.key.startsWith("crewspaceai/crewspace/"));function F(A,R){g(Q=>R?Q.includes(A)?Q:[...Q,A]:Q.filter(H=>H!==A))}return e.jsxs("div",{className:"mx-auto max-w-2xl space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold",children:"New Agent"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Advanced agent configuration"})]}),e.jsxs("div",{className:"border border-border",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsx("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Agent name",value:i,onChange:A=>l(A.target.value),autoFocus:!0})}),e.jsx("div",{className:"px-4 pb-2",children:e.jsx("input",{className:"w-full bg-transparent outline-none text-sm text-muted-foreground placeholder:text-muted-foreground/40",placeholder:"Title (e.g. VP of Engineering)",value:u,onChange:A=>d(A.target.value)})}),e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[e.jsxs(Ht,{open:y,onOpenChange:v,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:O("inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",C&&"opacity-60 cursor-not-allowed"),disabled:C,children:[e.jsx(Ip,{className:"h-3 w-3 text-muted-foreground"}),ed[I]??I]})}),e.jsx(Qt,{className:"w-36 p-1",align:"start",children:Dv.map(A=>e.jsx("button",{className:O("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",A===m&&"bg-accent"),onClick:()=>{p(A),v(!1)},children:ed[A]??A},A))})]}),e.jsx(Jw,{agents:S??[],value:x,onChange:f,disabled:C})]}),e.jsx(sf,{mode:"create",values:h,onChange:A=>j(R=>({...R,...A})),adapterModels:M}),e.jsx("div",{className:"border-t border-border px-4 py-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-medium",children:"Company skills"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Optional skills from the company library. Built-in CrewSpace runtime skills are added automatically."})]}),w.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No optional company skills installed yet."}):e.jsx("div",{className:"space-y-3",children:w.map(A=>{const R=`skill-${A.id}`,Q=b.includes(A.key);return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Gs,{id:R,checked:Q,onCheckedChange:H=>F(A.key,H===!0)}),e.jsxs("label",{htmlFor:R,className:"grid gap-1 leading-none",children:[e.jsx("span",{className:"text-sm font-medium",children:A.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:A.description??A.key})]})]},A.id)})})]})}),e.jsxs("div",{className:"border-t border-border px-4 py-3",children:[C&&e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"This will be the CEO"}),_&&e.jsx("p",{className:"text-xs text-destructive mb-2",children:_}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>r("/agents"),children:"Cancel"}),e.jsx(G,{size:"sm",disabled:!i.trim()||K.isPending,onClick:z,children:K.isPending?"Creating…":"Create agent"})]})]})]})]})}function a6(){const t=at(),n=Sn(),[s]=ui(),[r,a]=c.useState("sign_in"),[o,i]=c.useState(""),[l,u]=c.useState(""),[d,m]=c.useState(""),[p,x]=c.useState(null),f=c.useMemo(()=>s.get("next")||"/",[s]),{data:h,isLoading:j}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession(),retry:!1});c.useEffect(()=>{h&&n(f,{replace:!0})},[h,n,f]);const b=ge({mutationFn:async()=>{if(r==="sign_in"){await Bn.signInEmail({email:l.trim(),password:d});return}await Bn.signUpEmail({name:o.trim(),email:l.trim(),password:d})},onSuccess:async()=>{x(null),await t.invalidateQueries({queryKey:N.auth.session}),await t.invalidateQueries({queryKey:N.companies.all}),n(f,{replace:!0})},onError:y=>{x(y instanceof Error?y.message:"Authentication failed")}}),g=l.trim().length>0&&d.trim().length>0&&(r==="sign_in"||o.trim().length>0&&d.trim().length>=8);return j?e.jsx("div",{className:"fixed inset-0 flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})}):e.jsxs("div",{className:"fixed inset-0 flex bg-background",children:[e.jsx("div",{className:"w-full md:w-1/2 flex flex-col overflow-y-auto",children:e.jsxs("div",{className:"w-full max-w-md mx-auto my-auto px-8 py-12",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-8",children:[e.jsx(xo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"CrewSpace"})]}),e.jsx("h1",{className:"text-xl font-semibold",children:r==="sign_in"?"Sign in to CrewSpace":"Create your CrewSpace account"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r==="sign_in"?"Use your email and password to access this instance.":"Create an account for this instance. Email confirmation is not required in v1."}),e.jsxs("form",{className:"mt-6 space-y-4",method:"post",action:r==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:y=>{if(y.preventDefault(),!b.isPending){if(!g){x("Please fill in all required fields.");return}b.mutate()}},children:[r==="sign_up"&&e.jsxs("div",{children:[e.jsx("label",{htmlFor:"name",className:"text-xs text-muted-foreground mb-1 block",children:"Name"}),e.jsx("input",{id:"name",name:"name",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",value:o,onChange:y=>i(y.target.value),autoComplete:"name",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"email",className:"text-xs text-muted-foreground mb-1 block",children:"Email"}),e.jsx("input",{id:"email",name:"email",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"email",value:l,onChange:y=>u(y.target.value),autoComplete:"email",autoFocus:r==="sign_in"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"password",className:"text-xs text-muted-foreground mb-1 block",children:"Password"}),e.jsx("input",{id:"password",name:"password",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"password",value:d,onChange:y=>m(y.target.value),autoComplete:r==="sign_in"?"current-password":"new-password"})]}),p&&e.jsx("p",{className:"text-xs text-destructive",children:p}),e.jsx(G,{type:"submit",disabled:b.isPending,"aria-disabled":!g||b.isPending,className:`w-full ${!g&&!b.isPending?"opacity-50":""}`,children:b.isPending?"Working…":r==="sign_in"?"Sign In":"Create Account"})]}),e.jsxs("div",{className:"mt-5 text-sm text-muted-foreground",children:[r==="sign_in"?"Need an account?":"Already have an account?"," ",e.jsx("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:()=>{x(null),a(r==="sign_in"?"sign_up":"sign_in")},children:r==="sign_in"?"Create one":"Sign in"})]})]})}),e.jsx("div",{className:"hidden md:block w-1/2 overflow-hidden",children:e.jsx(sw,{})})]})}function o6(){const t=at(),n=Xn(),[s]=ui(),r=(n.token??"").trim(),a=(s.get("code")??"").trim(),o=c.useMemo(()=>`/board-claim/${encodeURIComponent(r)}${a?`?code=${encodeURIComponent(a)}`:""}`,[r,a]),i=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession(),retry:!1}),l=oe({queryKey:["board-claim",r,a],queryFn:()=>ms.getBoardClaimStatus(r,a),enabled:r.length>0&&a.length>0,retry:!1}),u=ge({mutationFn:()=>ms.claimBoard(r,a),onSuccess:async()=>{await t.invalidateQueries({queryKey:N.auth.session}),await t.invalidateQueries({queryKey:N.health}),await t.invalidateQueries({queryKey:N.companies.all}),await t.invalidateQueries({queryKey:N.companies.stats}),await l.refetch()}});if(!r||!a)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid board claim URL."});if(l.isLoading||i.isLoading)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading claim challenge..."});if(l.error)return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Claim challenge unavailable"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:l.error instanceof Error?l.error.message:"Challenge is invalid or expired."})]})});const d=l.data;return d?d.status==="claimed"?e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Oe,{to:"/",children:"Open board"})})]})}):i.data?e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate company ownership access from local trusted mode."}),u.error&&e.jsx("p",{className:"mt-3 text-sm text-destructive",children:u.error instanceof Error?u.error.message:"Failed to claim board ownership"}),e.jsx(G,{className:"mt-5",onClick:()=>u.mutate(),disabled:u.isPending,children:u.isPending?"Claiming…":"Claim ownership"})]})}):e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Sign in required"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Oe,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Claim challenge unavailable."})}function i6(){const t=at(),n=Xn(),[s]=ui(),r=(n.id??"").trim(),a=(s.get("token")??"").trim(),o=c.useMemo(()=>`/cli-auth/${encodeURIComponent(r)}${a?`?token=${encodeURIComponent(a)}`:""}`,[r,a]),i=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession(),retry:!1}),l=oe({queryKey:["cli-auth-challenge",r,a],queryFn:()=>ms.getCliAuthChallenge(r,a),enabled:r.length>0&&a.length>0,retry:!1}),u=ge({mutationFn:()=>ms.approveCliAuthChallenge(r,a),onSuccess:async()=>{await t.invalidateQueries({queryKey:N.auth.session}),await l.refetch()}}),d=ge({mutationFn:()=>ms.cancelCliAuthChallenge(r,a),onSuccess:async()=>{await l.refetch()}});if(!r||!a)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid CLI auth URL."});if(i.isLoading||l.isLoading)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading CLI auth challenge..."});if(l.error)return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"CLI auth challenge unavailable"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:l.error instanceof Error?l.error.message:"Challenge is invalid or expired."})]})});const m=l.data;return m?m.status==="approved"?e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"CLI access approved"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"The CrewSpace CLI can now finish authentication on the requesting machine."}),e.jsxs("p",{className:"mt-4 text-sm text-muted-foreground",children:["Command: ",e.jsx("span",{className:"font-mono text-foreground",children:m.command})]})]})}):m.status==="cancelled"||m.status==="expired"?e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:m.status==="expired"?"CLI auth challenge expired":"CLI auth challenge cancelled"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Start the CLI auth flow again from your terminal to generate a new approval request."})]})}):m.requiresSignIn||!i.data?e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Sign in required"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Oe,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Approve CrewSpace CLI access"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local CrewSpace CLI process is requesting board access to this instance."}),e.jsxs("div",{className:"mt-5 space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Command"}),e.jsx("div",{className:"font-mono text-foreground",children:m.command})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Client"}),e.jsx("div",{className:"text-foreground",children:m.clientName??"crewspaceai cli"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Requested access"}),e.jsx("div",{className:"text-foreground",children:m.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),m.requestedCompanyName&&e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Requested company"}),e.jsx("div",{className:"text-foreground",children:m.requestedCompanyName})]})]}),(u.error||d.error)&&e.jsx("p",{className:"mt-4 text-sm text-destructive",children:(u.error??d.error)instanceof Error?(u.error??d.error).message:"Failed to update CLI auth challenge"}),!m.canApprove&&e.jsx("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),e.jsxs("div",{className:"mt-5 flex gap-3",children:[e.jsx(G,{onClick:()=>u.mutate(),disabled:!m.canApprove||u.isPending||d.isPending,children:u.isPending?"Approving...":"Approve CLI access"}),e.jsx(G,{type:"button",variant:"outline",onClick:()=>d.mutate(),disabled:u.isPending||d.isPending,children:d.isPending?"Cancelling...":"Cancel"})]})]})}):e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"CLI auth challenge unavailable."})}const l6=[..._l],c6={claude_local:"Claude (local)",codex_local:"Codex (local)",gemini_local:"Gemini CLI (local)",opencode_local:"OpenCode (local)",pi_local:"Pi (local)",openclaw_gateway:"OpenClaw Gateway",cursor:"Cursor (local)",hermes_local:"Hermes Agent",process:"Process",http:"HTTP"},Ab=new Set(["claude_local","codex_local","gemini_local","opencode_local","pi_local","cursor","hermes_local"]);function d6(t){return new Date(t).toLocaleString()}function Mi(t,n){let s=t;for(const r of n){if(!s||typeof s!="object")return null;s=s[r]}return typeof s=="string"&&s.trim().length>0?s:null}function u6(){var B,k;const t=at(),s=(Xn().token??"").trim(),[r,a]=c.useState("human"),[o,i]=c.useState(""),[l,u]=c.useState("claude_local"),[d,m]=c.useState(""),[p,x]=c.useState(null),[f,h]=c.useState(null),j=oe({queryKey:N.health,queryFn:()=>Kx.get(),retry:!1}),b=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession(),retry:!1}),g=oe({queryKey:N.access.invite(s),queryFn:()=>ms.getInvite(s),enabled:s.length>0,retry:!1}),y=g.data,v=((B=y==null?void 0:y.companyName)==null?void 0:B.trim())||null,_=(y==null?void 0:y.allowedJoinTypes)??"both",E=c.useMemo(()=>(y==null?void 0:y.inviteType)==="bootstrap_ceo"?["human"]:_==="both"?["human","agent"]:[_],[y==null?void 0:y.inviteType,_]);c.useEffect(()=>{E.includes(r)||a(E[0]??"human")},[E,r]);const S=r==="human"&&((k=j.data)==null?void 0:k.deploymentMode)==="authenticated"&&!b.data,M=ge({mutationFn:async()=>{if(!y)throw new Error("Invite not found");return y.inviteType==="bootstrap_ceo"?ms.acceptInvite(s,{requestType:"human"}):r==="human"?ms.acceptInvite(s,{requestType:"human"}):ms.acceptInvite(s,{requestType:"agent",agentName:o.trim(),adapterType:l,capabilities:d.trim()||null})},onSuccess:async L=>{h(null),await t.invalidateQueries({queryKey:N.auth.session}),await t.invalidateQueries({queryKey:N.companies.all});const $=L&&typeof L=="object"&&"bootstrapAccepted"in L;x({kind:$?"bootstrap":"join",payload:L})},onError:L=>{h(L instanceof Error?L.message:"Failed to accept invite")}});if(!s)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(g.isLoading||j.isLoading||b.isLoading)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(g.error||!y)return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Invite not available"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"This invite may be expired, revoked, or already used."})]})});if((p==null?void 0:p.kind)==="bootstrap")return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Bootstrap complete"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"The first instance admin is now configured. You can continue to the board."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Oe,{to:"/",children:"Open board"})})]})});if((p==null?void 0:p.kind)==="join"){const L=p.payload,$=typeof L.claimSecret=="string"?L.claimSecret:null,C=typeof L.claimApiKeyPath=="string"?L.claimApiKeyPath:null,I=Mi(L.onboarding,["skill","url"]),K=Mi(L.onboarding,["skill","path"]),T=Mi(L.onboarding,["skill","installPath"]),z=Mi(L.onboarding,["textInstructions","url"]),w=Mi(L.onboarding,["textInstructions","path"]),F=Array.isArray(L.diagnostics)?L.diagnostics:[];return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Join request submitted"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Your request is pending admin approval. You will not have access until approved."}),e.jsxs("div",{className:"mt-4 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground",children:["Request ID: ",e.jsx("span",{className:"font-mono",children:L.id})]}),$&&C&&e.jsxs("div",{className:"mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground",children:"One-time claim secret (save now)"}),e.jsx("p",{className:"font-mono break-all",children:$}),e.jsxs("p",{className:"font-mono break-all",children:["POST ",C]})]}),(I||K||T)&&e.jsxs("div",{className:"mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground",children:"CrewSpace skill bootstrap"}),I&&e.jsxs("p",{className:"font-mono break-all",children:["GET ",I]}),!I&&K&&e.jsxs("p",{className:"font-mono break-all",children:["GET ",K]}),T&&e.jsxs("p",{className:"font-mono break-all",children:["Install to ",T]})]}),(z||w)&&e.jsxs("div",{className:"mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Agent-readable onboarding text"}),z&&e.jsxs("p",{className:"font-mono break-all",children:["GET ",z]}),!z&&w&&e.jsxs("p",{className:"font-mono break-all",children:["GET ",w]})]}),F.length>0&&e.jsxs("div",{className:"mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Connectivity diagnostics"}),F.map((A,R)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("p",{className:A.level==="warn"?"text-amber-600 dark:text-amber-400":void 0,children:["[",A.level,"] ",A.message]}),A.hint&&e.jsx("p",{className:"font-mono break-all",children:A.hint})]},`${A.code}:${R}`))]})]})})}return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:y.inviteType==="bootstrap_ceo"?"Bootstrap your CrewSpace instance":v?`Join ${v}`:"Join this CrewSpace company"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:[y.inviteType!=="bootstrap_ceo"&&v?`You were invited to join ${v}. `:null,"Invite expires ",d6(y.expiresAt),"."]}),y.inviteType!=="bootstrap_ceo"&&e.jsx("div",{className:"mt-5 flex gap-2",children:E.map(L=>e.jsxs("button",{type:"button",onClick:()=>a(L),className:`rounded-md border px-3 py-1.5 text-sm ${r===L?"border-foreground bg-foreground text-background":"border-border bg-background text-foreground"}`,children:["Join as ",L]},L))}),r==="agent"&&y.inviteType!=="bootstrap_ceo"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("label",{className:"block text-sm",children:[e.jsx("span",{className:"mb-1 block text-muted-foreground",children:"Agent name"}),e.jsx("input",{className:"w-full rounded-md border border-border bg-background px-3 py-2 text-sm",value:o,onChange:L=>i(L.target.value)})]}),e.jsxs("label",{className:"block text-sm",children:[e.jsx("span",{className:"mb-1 block text-muted-foreground",children:"Adapter type"}),e.jsx("select",{className:"w-full rounded-md border border-border bg-background px-3 py-2 text-sm",value:l,onChange:L=>u(L.target.value),children:l6.map(L=>e.jsxs("option",{value:L,disabled:!Ab.has(L),children:[c6[L],Ab.has(L)?"":" (Coming soon)"]},L))})]}),e.jsxs("label",{className:"block text-sm",children:[e.jsx("span",{className:"mb-1 block text-muted-foreground",children:"Capabilities (optional)"}),e.jsx("textarea",{className:"w-full rounded-md border border-border bg-background px-3 py-2 text-sm",rows:4,value:d,onChange:L=>m(L.target.value)})]})]}),S&&e.jsxs("div",{className:"mt-4 rounded-md border border-border bg-muted/30 p-3 text-sm",children:["Sign in or create an account before submitting a human join request.",e.jsx("div",{className:"mt-2",children:e.jsx(G,{asChild:!0,size:"sm",variant:"outline",children:e.jsx(Oe,{to:`/auth?next=${encodeURIComponent(`/invite/${s}`)}`,children:"Sign in / Create account"})})})]}),f&&e.jsx("p",{className:"mt-3 text-sm text-destructive",children:f}),e.jsx(G,{className:"mt-5",disabled:M.isPending||r==="agent"&&y.inviteType!=="bootstrap_ceo"&&o.trim().length===0||S,onClick:()=>M.mutate(),children:M.isPending?"Submitting…":y.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Submit join request"})]})})}const m6=c.lazy(()=>Kb(()=>import("./Office-JSp1M1WZ.js"),__vite__mapDeps([4,3,2,5,6,1,7])).then(t=>({default:t.Office})));function p6({hasActiveInvite:t=!1}){return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Instance setup required"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:t?"No instance admin exists yet. A bootstrap invite is already active. Check your CrewSpace startup logs for the first admin invite URL, or run this command to rotate it:":"No instance admin exists yet. Run this command in your CrewSpace environment to generate the first admin invite URL:"}),e.jsx("pre",{className:"mt-4 overflow-x-auto rounded-md border border-border bg-muted/30 p-3 text-xs",children:"pnpm crewspaceai auth bootstrap-ceo"})]})})}function x6(){var a,o;const t=fn(),n=oe({queryKey:N.health,queryFn:()=>Kx.get(),retry:!1,refetchInterval:i=>{const l=i.state.data;return(l==null?void 0:l.deploymentMode)==="authenticated"&&l.bootstrapStatus==="bootstrap_pending"?2e3:!1},refetchIntervalInBackground:!0}),s=((a=n.data)==null?void 0:a.deploymentMode)==="authenticated",r=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession(),enabled:s,retry:!1});if(n.isLoading||s&&r.isLoading)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading..."});if(n.error)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:n.error instanceof Error?n.error.message:"Failed to load app state"});if(s&&((o=n.data)==null?void 0:o.bootstrapStatus)==="bootstrap_pending")return e.jsx(p6,{hasActiveInvite:n.data.bootstrapInviteActive});if(s&&!r.data){const i=encodeURIComponent(`${t.pathname}${t.search}`);return e.jsx(Zt,{to:`/auth?next=${i}`,replace:!0})}return e.jsx(Rb,{})}function f6(){return e.jsxs(e.Fragment,{children:[e.jsx(_e,{index:!0,element:e.jsx(Zt,{to:"dashboard",replace:!0})}),e.jsx(_e,{path:"dashboard",element:e.jsx(DL,{})}),e.jsx(_e,{path:"onboarding",element:e.jsx(nk,{})}),e.jsx(_e,{path:"companies",element:e.jsx(BL,{})}),e.jsx(_e,{path:"company/settings",element:e.jsx(VB,{})}),e.jsx(_e,{path:"company/export/*",element:e.jsx(OK,{})}),e.jsx(_e,{path:"company/import",element:e.jsx(GK,{})}),e.jsx(_e,{path:"skills/*",element:e.jsx(lK,{})}),e.jsx(_e,{path:"settings",element:e.jsx(vd,{})}),e.jsx(_e,{path:"settings/*",element:e.jsx(vd,{})}),e.jsx(_e,{path:"plugins/:pluginId",element:e.jsx(jb,{})}),e.jsx(_e,{path:"org",element:e.jsx(Nz,{})}),e.jsx(_e,{path:"memory",element:e.jsx($z,{})}),e.jsx(_e,{path:"agent-chat",element:e.jsx(zz,{})}),e.jsx(_e,{path:"office",element:e.jsx(c.Suspense,{fallback:null,children:e.jsx(m6,{})})}),e.jsx(_e,{path:"blockers",element:e.jsx(Gz,{})}),e.jsx(_e,{path:"taskboard",element:e.jsx(t6,{})}),e.jsx(_e,{path:"agents",element:e.jsx(Zt,{to:"/agents/all",replace:!0})}),e.jsx(_e,{path:"agents/all",element:e.jsx(nc,{})}),e.jsx(_e,{path:"agents/active",element:e.jsx(nc,{})}),e.jsx(_e,{path:"agents/paused",element:e.jsx(nc,{})}),e.jsx(_e,{path:"agents/error",element:e.jsx(nc,{})}),e.jsx(_e,{path:"agents/new",element:e.jsx(r6,{})}),e.jsx(_e,{path:"agents/:agentId",element:e.jsx(tm,{})}),e.jsx(_e,{path:"agents/:agentId/:tab",element:e.jsx(tm,{})}),e.jsx(_e,{path:"agents/:agentId/runs/:runId",element:e.jsx(tm,{})}),e.jsx(_e,{path:"projects",element:e.jsx(HF,{})}),e.jsx(_e,{path:"projects/:projectId",element:e.jsx(Ma,{})}),e.jsx(_e,{path:"projects/:projectId/overview",element:e.jsx(Ma,{})}),e.jsx(_e,{path:"projects/:projectId/issues",element:e.jsx(Ma,{})}),e.jsx(_e,{path:"projects/:projectId/issues/:filter",element:e.jsx(Ma,{})}),e.jsx(_e,{path:"projects/:projectId/workspaces/:workspaceId",element:e.jsx(Pq,{})}),e.jsx(_e,{path:"projects/:projectId/workspaces",element:e.jsx(Ma,{})}),e.jsx(_e,{path:"projects/:projectId/configuration",element:e.jsx(Ma,{})}),e.jsx(_e,{path:"projects/:projectId/budget",element:e.jsx(Ma,{})}),e.jsx(_e,{path:"issues",element:e.jsx(Mq,{})}),e.jsx(_e,{path:"issues/all",element:e.jsx(Zt,{to:"/issues",replace:!0})}),e.jsx(_e,{path:"issues/active",element:e.jsx(Zt,{to:"/issues",replace:!0})}),e.jsx(_e,{path:"issues/backlog",element:e.jsx(Zt,{to:"/issues",replace:!0})}),e.jsx(_e,{path:"issues/done",element:e.jsx(Zt,{to:"/issues",replace:!0})}),e.jsx(_e,{path:"issues/recent",element:e.jsx(Zt,{to:"/issues",replace:!0})}),e.jsx(_e,{path:"issues/:issueId",element:e.jsx(vU,{})}),e.jsx(_e,{path:"routines",element:e.jsx(AU,{})}),e.jsx(_e,{path:"routines/:routineId",element:e.jsx(HU,{})}),e.jsx(_e,{path:"execution-workspaces/:workspaceId",element:e.jsx(YU,{})}),e.jsx(_e,{path:"goals",element:e.jsx(XU,{})}),e.jsx(_e,{path:"goals/:goalId",element:e.jsx(nB,{})}),e.jsx(_e,{path:"approvals",element:e.jsx(Zt,{to:"/approvals/pending",replace:!0})}),e.jsx(_e,{path:"approvals/pending",element:e.jsx(Gg,{})}),e.jsx(_e,{path:"approvals/all",element:e.jsx(Gg,{})}),e.jsx(_e,{path:"approvals/:approvalId",element:e.jsx(dB,{})}),e.jsx(_e,{path:"costs",element:e.jsx($B,{})}),e.jsx(_e,{path:"activity",element:e.jsx(DB,{})}),e.jsx(_e,{path:"inbox",element:e.jsx(h6,{})}),e.jsx(_e,{path:"inbox/mine",element:e.jsx(dc,{})}),e.jsx(_e,{path:"inbox/recent",element:e.jsx(dc,{})}),e.jsx(_e,{path:"inbox/unread",element:e.jsx(dc,{})}),e.jsx(_e,{path:"inbox/all",element:e.jsx(dc,{})}),e.jsx(_e,{path:"inbox/new",element:e.jsx(Zt,{to:"/inbox/mine",replace:!0})}),e.jsx(_e,{path:"design-guide",element:e.jsx(ZK,{})}),e.jsx(_e,{path:"tests/ux/runs",element:e.jsx(fz,{})}),e.jsx(_e,{path:":pluginRoutePath",element:e.jsx(jb,{})}),e.jsx(_e,{path:"*",element:e.jsx(pl,{scope:"board"})})]})}function h6(){return e.jsx(Zt,{to:`/inbox/${BT()}`,replace:!0})}function vd(){const t=fn();return e.jsx(Zt,{to:`/instance/settings/general${t.search}${t.hash}`,replace:!0})}function nk(){const{companies:t}=et(),{openOnboarding:n}=In(),{companyPrefix:s}=Xn(),r=s?t.find(i=>i.issuePrefix.toUpperCase()===s.toUpperCase())??null:null,a=r?`Add another agent to ${r.name}`:t.length>0?"Create another company":"Create your first company",o=r?"Run onboarding again to add an agent and a starter task for this company.":t.length>0?"Run onboarding again to create another company and seed its first agent.":"Get started by creating a company and your first agent.";return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:a}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:o}),e.jsx("div",{className:"mt-4",children:e.jsx(G,{onClick:()=>r?n({initialStep:2,companyId:r.id}):n(),children:r?"Add Agent":"Start Onboarding"})})]})})}function g6(){const{companies:t,selectedCompany:n,loading:s}=et(),r=fn();if(s)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading..."});const a=n??t[0]??null;return a?e.jsx(Zt,{to:`/${a.issuePrefix}/dashboard`,replace:!0}):nw({pathname:r.pathname,hasCompanies:!1})?e.jsx(Zt,{to:"/onboarding",replace:!0}):e.jsx(sk,{})}function an(){const t=fn(),{companies:n,selectedCompany:s,loading:r}=et();if(r)return e.jsx("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading..."});const a=s??n[0]??null;return a?e.jsx(Zt,{to:`/${a.issuePrefix}${t.pathname}${t.search}${t.hash}`,replace:!0}):nw({pathname:t.pathname,hasCompanies:!1})?e.jsx(Zt,{to:"/onboarding",replace:!0}):e.jsx(sk,{})}function sk(){const{openOnboarding:t}=In();return e.jsx("div",{className:"mx-auto max-w-xl py-10",children:e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Create your first company"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Get started by creating a company."}),e.jsx("div",{className:"mt-4",children:e.jsx(G,{onClick:()=>t(),children:"New Company"})})]})})}function b6(){return e.jsxs(e.Fragment,{children:[e.jsxs(fk,{children:[e.jsx(_e,{path:"auth",element:e.jsx(a6,{})}),e.jsx(_e,{path:"board-claim/:token",element:e.jsx(o6,{})}),e.jsx(_e,{path:"cli-auth/:id",element:e.jsx(i6,{})}),e.jsx(_e,{path:"invite/:token",element:e.jsx(u6,{})}),e.jsxs(_e,{element:e.jsx(x6,{}),children:[e.jsx(_e,{index:!0,element:e.jsx(g6,{})}),e.jsx(_e,{path:"onboarding",element:e.jsx(nk,{})}),e.jsx(_e,{path:"instance",element:e.jsx(Zt,{to:"/instance/settings/general",replace:!0})}),e.jsxs(_e,{path:"instance/settings",element:e.jsx(_h,{}),children:[e.jsx(_e,{index:!0,element:e.jsx(Zt,{to:"general",replace:!0})}),e.jsx(_e,{path:"general",element:e.jsx(YK,{})}),e.jsx(_e,{path:"heartbeats",element:e.jsx(ez,{})}),e.jsx(_e,{path:"experimental",element:e.jsx(tz,{})}),e.jsx(_e,{path:"plugins",element:e.jsx(sz,{})}),e.jsx(_e,{path:"plugins/:pluginId",element:e.jsx(oz,{})})]}),e.jsx(_e,{path:"companies",element:e.jsx(an,{})}),e.jsx(_e,{path:"issues",element:e.jsx(an,{})}),e.jsx(_e,{path:"issues/:issueId",element:e.jsx(an,{})}),e.jsx(_e,{path:"routines",element:e.jsx(an,{})}),e.jsx(_e,{path:"routines/:routineId",element:e.jsx(an,{})}),e.jsx(_e,{path:"skills/*",element:e.jsx(an,{})}),e.jsx(_e,{path:"settings",element:e.jsx(vd,{})}),e.jsx(_e,{path:"settings/*",element:e.jsx(vd,{})}),e.jsx(_e,{path:"agents",element:e.jsx(an,{})}),e.jsx(_e,{path:"agents/new",element:e.jsx(an,{})}),e.jsx(_e,{path:"agents/:agentId",element:e.jsx(an,{})}),e.jsx(_e,{path:"agents/:agentId/:tab",element:e.jsx(an,{})}),e.jsx(_e,{path:"agents/:agentId/runs/:runId",element:e.jsx(an,{})}),e.jsx(_e,{path:"memory",element:e.jsx(an,{})}),e.jsx(_e,{path:"agent-chat",element:e.jsx(an,{})}),e.jsx(_e,{path:"office",element:e.jsx(an,{})}),e.jsx(_e,{path:"org",element:e.jsx(an,{})}),e.jsx(_e,{path:"taskboard",element:e.jsx(an,{})}),e.jsx(_e,{path:"blockers",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects/:projectId",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects/:projectId/overview",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects/:projectId/issues",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects/:projectId/issues/:filter",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects/:projectId/workspaces",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects/:projectId/workspaces/:workspaceId",element:e.jsx(an,{})}),e.jsx(_e,{path:"projects/:projectId/configuration",element:e.jsx(an,{})}),e.jsx(_e,{path:"execution-workspaces/:workspaceId",element:e.jsx(an,{})}),e.jsx(_e,{path:"tests/ux/runs",element:e.jsx(an,{})}),e.jsx(_e,{path:":companyPrefix",element:e.jsx(_h,{}),children:f6()}),e.jsx(_e,{path:"*",element:e.jsx(pl,{scope:"global"})})]})]}),e.jsx(G$,{})]})}const y6=1e4,v6=3,j6=2e3,w6=0,N6=1;function wt(t){return typeof t=="string"&&t.length>0?t:null}function iu(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function lu(t){return t.slice(0,8)}function rk(t,n,s){const r=t.getQueryData(N.agents.list(n));if(!r)return null;const a=r.find(o=>o.id===s);return(a==null?void 0:a.name)??null}function qa(t,n){return t.length<=n?t:t.slice(0,n-1)+"…"}function k6(t,n,s,r){return s==="agent"&&r?rk(t,n,r)??`Agent ${lu(r)}`:s==="system"?"System":s==="user"&&r?"Board":"Someone"}function ak(t,n,s,r){const a=new Set([s]),o=t.getQueryData(N.issues.detail(s)),i=t.getQueryData(N.issues.list(n)),l=wt(r==null?void 0:r.identifier)??wt(r==null?void 0:r.issueIdentifier);l&&a.add(l),o!=null&&o.id&&a.add(o.id),o!=null&&o.identifier&&a.add(o.identifier);const u=i==null?void 0:i.find(d=>!!(d.id===s||d.identifier&&d.identifier===s||l&&d.identifier===l));return u!=null&&u.id&&a.add(u.id),u!=null&&u.identifier&&a.add(u.identifier),Array.from(a)}function C6(t,n,s,r){var m;const a=ak(t,n,s,r),o=a.map(p=>t.getQueryData(N.issues.detail(p))).find(p=>!!p),i=(m=t.getQueryData(N.issues.list(n)))==null?void 0:m.find(p=>a.some(x=>p.id===x||p.identifier===x)),l=o??i??null,u=wt(r==null?void 0:r.identifier)??wt(r==null?void 0:r.issueIdentifier)??(l==null?void 0:l.identifier)??`Issue ${lu(s)}`,d=wt(r==null?void 0:r.title)??wt(r==null?void 0:r.issueTitle)??(l==null?void 0:l.title)??null;return{ref:u,title:d,label:d?`${u} - ${qa(d,72)}`:u,href:`/issues/${(l==null?void 0:l.identifier)??s}`}}function S6(){return!(typeof document>"u"||document.visibilityState!=="visible"||typeof document.hasFocus=="function"&&!document.hasFocus())}function pf(t,n,s){if(!((s==null?void 0:s.isForegrounded)??S6()))return null;const o=Up(n).split("/").filter(Boolean);if(o[0]!=="issues"||!o[1])return null;const i=decodeURIComponent(o[1]),l=t.getQueryData(N.issues.detail(i))??null,u=new Set([i]);l!=null&&l.id&&u.add(l.id),l!=null&&l.identifier&&u.add(l.identifier);const d=new Set,m=t.getQueryData(N.issues.activeRun(i)),p=t.getQueryData(N.issues.liveRuns(i))??[],x=t.getQueryData(N.issues.runs(i))??[];m!=null&&m.id&&d.add(m.id);for(const f of p)f.id&&d.add(f.id);for(const f of x)f.runId&&d.add(f.runId);return{issueRefs:u,assigneeAgentId:(l==null?void 0:l.assigneeAgentId)??null,runIds:d}}function I6(t,n){const s=new Set([t]),r=wt(n==null?void 0:n.identifier)??wt(n==null?void 0:n.issueIdentifier);return r&&s.add(r),s}function _6(t,n){for(const s of t)if(n.has(s))return!0;return!1}function A6(t,n,s,r){const a=wt(s.entityType),o=wt(s.entityId);if(a!=="issue"||!o)return!1;const i=pf(t,n,r);return i?_6(i.issueRefs,I6(o,iu(s.details))):!1}function E6(t,n,s,r){const a=pf(t,n,r);if(!a)return!1;const o=wt(s.runId);if(o&&a.runIds.has(o))return!0;const i=wt(s.agentId);return!!i&&!!a.assigneeAgentId&&i===a.assigneeAgentId}function T6(t,n,s,r){const a=pf(t,n,r);if(!(a!=null&&a.assigneeAgentId))return!1;const o=wt(s.agentId);return!!o&&o===a.assigneeAgentId}const R6=new Set(["issue.created","issue.updated","issue.comment_added"]),P6=new Set(["error"]),M6=new Set(["failed","timed_out","cancelled"]);function $6(t){if(!t)return null;const n=[];if(typeof t.status=="string"&&n.push(`status -> ${t.status.replace(/_/g," ")}`),typeof t.priority=="string"&&n.push(`priority -> ${t.priority}`),typeof t.assigneeAgentId=="string"||typeof t.assigneeUserId=="string"?n.push("reassigned"):(t.assigneeAgentId===null||t.assigneeUserId===null)&&n.push("unassigned"),t.reopened===!0){const s=wt(t.reopenedFrom);n.push(s?`reopened from ${s.replace(/_/g," ")}`:"reopened")}return typeof t.title=="string"&&n.push("title changed"),typeof t.description=="string"&&n.push("description changed"),n.length>0?n.join(", "):null}function D6(t,n,s,r){const a=wt(s.entityType),o=wt(s.entityId),i=wt(s.action),l=iu(s.details),u=wt(s.actorId),d=wt(s.actorType);if(a!=="issue"||!o||!i||!R6.has(i))return null;const m=C6(t,n,o,l),p=k6(t,n,d,u);if(d==="user"&&!!r.userId&&u===r.userId||d==="agent"&&!!r.agentId&&u===r.agentId)return null;if(i==="issue.created")return{title:`${p} created ${m.ref}`,body:m.title?qa(m.title,96):void 0,tone:"success",action:{label:`View ${m.ref}`,href:m.href},dedupeKey:`activity:${i}:${o}`};if(i==="issue.updated"){if(wt(l==null?void 0:l.source)==="comment")return null;const E=$6(l),S=E?m.title?`${qa(m.title,64)} - ${E}`:E:m.title?qa(m.title,96):m.label;return{title:`${p} updated ${m.ref}`,body:qa(S,100),tone:"info",action:{label:`View ${m.ref}`,href:m.href},dedupeKey:`activity:${i}:${o}`}}const f=wt(l==null?void 0:l.commentId),h=wt(l==null?void 0:l.bodySnippet),j=(l==null?void 0:l.reopened)===!0,b=(l==null?void 0:l.updated)===!0,g=wt(l==null?void 0:l.reopenedFrom),y=j?g?`reopened from ${g.replace(/_/g," ")}`:"reopened":null,v=j?`${p} reopened and commented on ${m.ref}`:b?`${p} commented and updated ${m.ref}`:`${p} commented on ${m.ref}`,_=h?y?`${y} - ${h.replace(/^#+\s*/m,"").replace(/\n/g," ")}`:h.replace(/^#+\s*/m,"").replace(/\n/g," "):y?m.title?`${y} - ${m.title}`:y:m.title??void 0;return{title:v,body:_?qa(_,96):void 0,tone:"info",action:{label:`View ${m.ref}`,href:m.href},dedupeKey:`activity:${i}:${o}:${f??"na"}`}}function O6(t){const n=wt(t.entityType),s=wt(t.action),r=wt(t.entityId),a=iu(t.details);return n!=="join_request"||!s||!r||s!=="join.requested"&&s!=="join.request_replayed"?null:{title:`${wt(a==null?void 0:a.requestType)==="agent"?"Agent":"Someone"} wants to join`,body:"A new join request is waiting for approval.",tone:"info",action:{label:"View inbox",href:"/inbox/mine"},dedupeKey:`join-request:${r}`}}function L6(t,n,s,r){const a=wt(t.agentId),o=wt(t.status);if(!a||!o||!P6.has(o))return null;const i=o==="error"?"error":"info",l=n(a)??`Agent ${lu(a)}`,u=o==="running"?`${l} started`:`${l} errored`,d=s.getQueryData(N.agents.list(r)),m=d==null?void 0:d.find(x=>x.id===a),p=(m==null?void 0:m.title)??void 0;return{title:u,body:p,tone:i,action:{label:"View agent",href:`/agents/${a}`},dedupeKey:`agent-status:${a}:${o}`}}function F6(t,n){const s=wt(t.runId),r=wt(t.agentId),a=wt(t.status);if(!s||!r||!a||!M6.has(a))return null;const o=wt(t.error),i=wt(t.triggerDetail),l=n(r)??`Agent ${lu(r)}`,u=a==="succeeded"?"success":a==="cancelled"?"warn":"error",m=`${l} run ${a==="succeeded"?"succeeded":a==="failed"?"failed":a==="timed_out"?"timed out":"cancelled"}`;let p;return o?p=qa(o,100):i&&(p=`Trigger: ${i}`),{title:m,body:p,tone:u,ttlMs:a==="succeeded"?5e3:7e3,action:{label:"View run",href:`/agents/${r}/runs/${s}`},dedupeKey:`run-status:${s}:${a}`}}function q6(t,n,s){t.invalidateQueries({queryKey:N.liveRuns(n)}),t.invalidateQueries({queryKey:N.heartbeats(n)}),t.invalidateQueries({queryKey:N.agents.list(n)}),t.invalidateQueries({queryKey:N.dashboard(n)}),t.invalidateQueries({queryKey:N.costs(n)}),t.invalidateQueries({queryKey:N.sidebarBadges(n)});const r=wt(s.agentId);r&&(t.invalidateQueries({queryKey:N.agents.detail(r)}),t.invalidateQueries({queryKey:N.heartbeats(n,r)}))}function U6(t,n,s){t.invalidateQueries({queryKey:N.activity(n)}),t.invalidateQueries({queryKey:N.dashboard(n)}),t.invalidateQueries({queryKey:N.sidebarBadges(n)});const r=wt(s.entityType),a=wt(s.entityId);if(r==="issue"){if(t.invalidateQueries({queryKey:N.issues.list(n)}),t.invalidateQueries({queryKey:N.issues.listMineByMe(n)}),t.invalidateQueries({queryKey:N.issues.listTouchedByMe(n)}),t.invalidateQueries({queryKey:N.issues.listUnreadTouchedByMe(n)}),a){const o=iu(s.details),i=ak(t,n,a,o);for(const l of i)t.invalidateQueries({queryKey:N.issues.detail(l)}),t.invalidateQueries({queryKey:N.issues.comments(l)}),t.invalidateQueries({queryKey:N.issues.activity(l)}),t.invalidateQueries({queryKey:N.issues.runs(l)}),t.invalidateQueries({queryKey:N.issues.documents(l)}),t.invalidateQueries({queryKey:N.issues.attachments(l)}),t.invalidateQueries({queryKey:N.issues.approvals(l)}),t.invalidateQueries({queryKey:N.issues.liveRuns(l)}),t.invalidateQueries({queryKey:N.issues.activeRun(l)})}return}if(r==="agent"){t.invalidateQueries({queryKey:N.agents.list(n)}),t.invalidateQueries({queryKey:N.org(n)}),a&&(t.invalidateQueries({queryKey:N.agents.detail(a)}),t.invalidateQueries({queryKey:N.heartbeats(n,a)}));return}if(r==="project"){t.invalidateQueries({queryKey:N.projects.list(n)}),a&&t.invalidateQueries({queryKey:N.projects.detail(a)});return}if(r==="goal"){t.invalidateQueries({queryKey:N.goals.list(n)}),a&&t.invalidateQueries({queryKey:N.goals.detail(a)});return}if(r==="approval"){t.invalidateQueries({queryKey:N.approvals.list(n)});return}if(r==="join_request"){t.invalidateQueries({queryKey:N.access.joinRequests(n)});return}if(r==="cost_event"){t.invalidateQueries({queryKey:N.costs(n)}),t.invalidateQueries({queryKey:N.usageByProvider(n)}),t.invalidateQueries({queryKey:N.usageWindowSpend(n)});return}if(r==="routine"||r==="routine_trigger"||r==="routine_run"){t.invalidateQueries({queryKey:["routines"]});return}r==="company"&&t.invalidateQueries({queryKey:N.companies.all})}function B6(t,n){const s=Date.now();if(s<t.suppressUntil)return!0;const r=t.cooldownHits.get(n);if(!r)return!1;const a=r.filter(o=>s-o<y6);return t.cooldownHits.set(n,a),a.length>=v6}function K6(t,n){const s=Date.now(),r=t.cooldownHits.get(n)??[];r.push(s),t.cooldownHits.set(n,r)}function fm(t,n,s,r){if(B6(t,s))return;n(r)!==null&&K6(t,s)}function z6(t,n,s,r,a,o,i){if(r.companyId!==n)return;const l=d=>rk(t,n,d),u=r.payload??{};if(r.type!=="heartbeat.run.log"){if(r.type==="heartbeat.run.queued"||r.type==="heartbeat.run.status"){if(q6(t,n,u),r.type==="heartbeat.run.status"){const d=F6(u,l);d&&!E6(t,s,u)&&fm(o,a,"run-status",d)}return}if(r.type!=="heartbeat.run.event"){if(r.type==="agent.status"){t.invalidateQueries({queryKey:N.agents.list(n)}),t.invalidateQueries({queryKey:N.dashboard(n)}),t.invalidateQueries({queryKey:N.org(n)});const d=wt(u.agentId);d&&t.invalidateQueries({queryKey:N.agents.detail(d)});const m=L6(u,l,t,n);m&&!T6(t,s,u)&&fm(o,a,"agent-status",m);return}if(r.type==="activity.logged"){U6(t,n,u);const d=wt(u.action),m=D6(t,n,u,i)??O6(u);m&&!A6(t,s,u)&&fm(o,a,`activity:${d??"unknown"}`,m)}}}}function W6(t,n){return t&&t===n?t:null}function Eb(t){t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null}function Tb(t,n){if(t){if(t.readyState===w6){t.onopen=()=>{Eb(t),t.close(1e3,n)},t.onmessage=null,t.onerror=()=>{},t.onclose=null;return}Eb(t),t.readyState===N6&&t.close(1e3,n)}}function H6({children:t}){var j,b,g;const{selectedCompanyId:n,selectedCompany:s}=et(),r=at(),{pushToast:a}=ds(),o=fn(),i=c.useRef({cooldownHits:new Map,suppressUntil:0}),l=c.useRef(o.pathname),{data:u,status:d}=oe({queryKey:N.auth.session,queryFn:()=>Bn.getSession(),retry:!1}),m=((j=u==null?void 0:u.user)==null?void 0:j.id)??((b=u==null?void 0:u.session)==null?void 0:b.userId)??null,p=((g=u==null?void 0:u.session)==null?void 0:g.id)??m??"signed_out",x=W6(n,(s==null?void 0:s.id)??null),f=d==="success"&&u!==null&&x!==null,h=c.useRef({userId:m,agentId:null});return c.useEffect(()=>{l.current=o.pathname},[o.pathname]),c.useEffect(()=>{h.current={userId:m,agentId:null}},[m]),c.useEffect(()=>{if(!f||!x)return;let y=!1,v=0,_=null,E=null;const S=()=>{_!==null&&(window.clearTimeout(_),_=null)},M=()=>{if(y)return;v+=1;const L=Math.min(15e3,1e3*2**Math.min(v-1,4));_=window.setTimeout(()=>{_=null,B()},L)},B=()=>{if(y)return;const $=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/companies/${encodeURIComponent(x)}/events/ws`,C=new WebSocket($);E=C,C.onopen=()=>{if(y||E!==C){Tb(C,"stale_connection");return}v>0&&(i.current.suppressUntil=Date.now()+j6),v=0},C.onmessage=I=>{const K=typeof I.data=="string"?I.data:"";if(K)try{const T=JSON.parse(K);z6(r,x,l.current,T,a,i.current,{userId:h.current.userId,agentId:h.current.agentId})}catch{}},C.onerror=()=>{},C.onclose=()=>{E===C&&(E=null,!y&&M())}},k=window.setTimeout(B,0);return()=>{y=!0,window.clearTimeout(k),S();const L=E;E=null,Tb(L,"provider_unmount")}},[r,x,a,f,p]),e.jsx(e.Fragment,{children:t})}function V6(t,n){globalThis.__crewspacePluginBridge__={react:t,reactDom:n,sdkUi:{usePluginData:oT,usePluginAction:iT,useHostContext:lT,usePluginStream:dT,usePluginToast:cT}}}V6(bk,gk);"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js")});const Q6=new ck({defaultOptions:{queries:{staleTime:3e4,refetchOnWindowFocus:!0}}});vk.createRoot(document.getElementById("root")).render(e.jsx(c.StrictMode,{children:e.jsx(dk,{client:Q6,children:e.jsx(uP,{children:e.jsx(hk,{children:e.jsx(W1,{children:e.jsx(sT,{children:e.jsx(H6,{children:e.jsx(Lj,{children:e.jsx(YT,{children:e.jsx(WE,{children:e.jsx(vR,{children:e.jsx(xR,{children:e.jsx($E,{children:e.jsx(b6,{})})})})})})})})})})})})})}));export{We as a,Yt as h,nt as i,N as q,et as u};
|