corporateai 0.0.1
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/.dockerignore +10 -0
- package/.env.example +3 -0
- package/.github/workflows/publish-cli.yml +49 -0
- package/.mailmap +1 -0
- package/AGENTS.md +148 -0
- package/CONTRIBUTING.md +75 -0
- package/Dockerfile +59 -0
- package/Dockerfile.onboard-smoke +42 -0
- package/LICENSE +21 -0
- package/README.md +93 -0
- package/cli/esbuild.config.mjs +11 -0
- package/cli/package.json +24 -0
- package/cli/scripts/build-cli.mjs +5 -0
- package/cli/src/index.ts +27 -0
- package/docker-compose.quickstart.yml +18 -0
- package/docker-compose.untrusted-review.yml +33 -0
- package/docker-compose.yml +38 -0
- package/package.json +56 -0
- package/patches/embedded-postgres@18.1.0-beta.16.patch +0 -0
- package/pnpm-workspace.yaml +4 -0
- package/releases/.gitkeep +0 -0
- package/releases/v0.0.1.md +36 -0
- package/releases/v0.2.7.md +15 -0
- package/releases/v0.3.0.md +54 -0
- package/releases/v0.3.1.md +55 -0
- package/releases/v2026.318.0.md +66 -0
- package/releases/v2026.325.0.md +78 -0
- package/report/2026-03-13-08-46-token-optimization-implementation.md +48 -0
- package/scripts/backup-db.sh +17 -0
- package/scripts/build-npm.sh +80 -0
- package/scripts/check-forbidden-tokens.mjs +115 -0
- package/scripts/clean-onboard-git.sh +14 -0
- package/scripts/clean-onboard-npm.sh +13 -0
- package/scripts/clean-onboard-ref.sh +86 -0
- package/scripts/create-github-release.sh +99 -0
- package/scripts/dev-runner-paths.mjs +38 -0
- package/scripts/dev-runner.mjs +606 -0
- package/scripts/docker-onboard-smoke.sh +306 -0
- package/scripts/ensure-plugin-build-deps.mjs +47 -0
- package/scripts/generate-company-assets.ts +365 -0
- package/scripts/generate-npm-package-json.mjs +113 -0
- package/scripts/generate-org-chart-images.ts +694 -0
- package/scripts/generate-org-chart-satori-comparison.ts +225 -0
- package/scripts/generate-ui-package-json.mjs +31 -0
- package/scripts/kill-dev.sh +71 -0
- package/scripts/migrate-inline-env-secrets.ts +126 -0
- package/scripts/prepare-server-ui-dist.sh +22 -0
- package/scripts/provision-worktree.sh +333 -0
- package/scripts/release-lib.sh +306 -0
- package/scripts/release-package-map.mjs +169 -0
- package/scripts/release.sh +312 -0
- package/scripts/rollback-latest.sh +111 -0
- package/scripts/smoke/openclaw-docker-ui.sh +329 -0
- package/scripts/smoke/openclaw-gateway-e2e.sh +954 -0
- package/scripts/smoke/openclaw-join.sh +295 -0
- package/scripts/smoke/openclaw-sse-standalone.sh +146 -0
- package/scripts/workspace-compat.mjs +60 -0
- package/server/CHANGELOG.md +130 -0
- package/server/package.json +96 -0
- package/server/scripts/copy-onboarding-assets.mjs +10 -0
- package/server/scripts/dev-watch.ts +33 -0
- package/server/src/__tests__/activity-routes.test.ts +70 -0
- package/server/src/__tests__/adapter-models.test.ts +105 -0
- package/server/src/__tests__/adapter-session-codecs.test.ts +194 -0
- package/server/src/__tests__/agent-auth-jwt.test.ts +79 -0
- package/server/src/__tests__/agent-instructions-routes.test.ts +318 -0
- package/server/src/__tests__/agent-instructions-service.test.ts +361 -0
- package/server/src/__tests__/agent-permissions-routes.test.ts +275 -0
- package/server/src/__tests__/agent-shortname-collision.test.ts +69 -0
- package/server/src/__tests__/agent-skill-contract.test.ts +50 -0
- package/server/src/__tests__/agent-skills-routes.test.ts +462 -0
- package/server/src/__tests__/app-hmr-port.test.ts +19 -0
- package/server/src/__tests__/approval-routes-idempotency.test.ts +110 -0
- package/server/src/__tests__/approvals-service.test.ts +107 -0
- package/server/src/__tests__/assets.test.ts +250 -0
- package/server/src/__tests__/attachment-types.test.ts +97 -0
- package/server/src/__tests__/board-mutation-guard.test.ts +105 -0
- package/server/src/__tests__/budgets-service.test.ts +311 -0
- package/server/src/__tests__/claude-local-adapter-environment.test.ts +92 -0
- package/server/src/__tests__/claude-local-adapter.test.ts +31 -0
- package/server/src/__tests__/claude-local-skill-sync.test.ts +111 -0
- package/server/src/__tests__/cli-auth-routes.test.ts +230 -0
- package/server/src/__tests__/codex-local-adapter-environment.test.ts +143 -0
- package/server/src/__tests__/codex-local-adapter.test.ts +253 -0
- package/server/src/__tests__/codex-local-execute.test.ts +391 -0
- package/server/src/__tests__/codex-local-skill-injection.test.ts +175 -0
- package/server/src/__tests__/codex-local-skill-sync.test.ts +123 -0
- package/server/src/__tests__/companies-route-path-guard.test.ts +56 -0
- package/server/src/__tests__/company-branding-route.test.ts +196 -0
- package/server/src/__tests__/company-portability-routes.test.ts +175 -0
- package/server/src/__tests__/company-portability.test.ts +2186 -0
- package/server/src/__tests__/company-skills-routes.test.ts +113 -0
- package/server/src/__tests__/company-skills.test.ts +229 -0
- package/server/src/__tests__/costs-service.test.ts +226 -0
- package/server/src/__tests__/cursor-local-adapter-environment.test.ts +196 -0
- package/server/src/__tests__/cursor-local-adapter.test.ts +406 -0
- package/server/src/__tests__/cursor-local-execute.test.ts +263 -0
- package/server/src/__tests__/cursor-local-skill-injection.test.ts +104 -0
- package/server/src/__tests__/cursor-local-skill-sync.test.ts +145 -0
- package/server/src/__tests__/dev-runner-paths.test.ts +25 -0
- package/server/src/__tests__/dev-server-status.test.ts +66 -0
- package/server/src/__tests__/dev-watch-ignore.test.ts +42 -0
- package/server/src/__tests__/documents.test.ts +29 -0
- package/server/src/__tests__/error-handler.test.ts +53 -0
- package/server/src/__tests__/execution-workspace-policy.test.ts +170 -0
- package/server/src/__tests__/forbidden-tokens.test.ts +77 -0
- package/server/src/__tests__/gemini-local-adapter-environment.test.ts +135 -0
- package/server/src/__tests__/gemini-local-adapter.test.ts +190 -0
- package/server/src/__tests__/gemini-local-execute.test.ts +172 -0
- package/server/src/__tests__/gemini-local-skill-sync.test.ts +90 -0
- package/server/src/__tests__/health.test.ts +16 -0
- package/server/src/__tests__/heartbeat-process-recovery.test.ts +256 -0
- package/server/src/__tests__/heartbeat-run-summary.test.ts +33 -0
- package/server/src/__tests__/heartbeat-workspace-session.test.ts +334 -0
- package/server/src/__tests__/helpers/embedded-postgres.ts +7 -0
- package/server/src/__tests__/hire-hook.test.ts +181 -0
- package/server/src/__tests__/instance-settings-routes.test.ts +156 -0
- package/server/src/__tests__/invite-accept-gateway-defaults.test.ts +119 -0
- package/server/src/__tests__/invite-accept-replay.test.ts +92 -0
- package/server/src/__tests__/invite-expiry.test.ts +10 -0
- package/server/src/__tests__/invite-join-grants.test.ts +57 -0
- package/server/src/__tests__/invite-join-manager.test.ts +33 -0
- package/server/src/__tests__/invite-onboarding-text.test.ts +116 -0
- package/server/src/__tests__/issue-comment-reopen-routes.test.ts +146 -0
- package/server/src/__tests__/issue-goal-fallback.test.ts +99 -0
- package/server/src/__tests__/issues-checkout-wakeup.test.ts +48 -0
- package/server/src/__tests__/issues-goal-context-routes.test.ts +187 -0
- package/server/src/__tests__/issues-service.test.ts +317 -0
- package/server/src/__tests__/issues-user-context.test.ts +113 -0
- package/server/src/__tests__/log-redaction.test.ts +74 -0
- package/server/src/__tests__/monthly-spend-service.test.ts +90 -0
- package/server/src/__tests__/normalize-agent-mention-token.test.ts +41 -0
- package/server/src/__tests__/openclaw-gateway-adapter.test.ts +626 -0
- package/server/src/__tests__/openclaw-invite-prompt-route.test.ts +192 -0
- package/server/src/__tests__/opencode-local-adapter-environment.test.ts +97 -0
- package/server/src/__tests__/opencode-local-adapter.test.ts +226 -0
- package/server/src/__tests__/opencode-local-skill-sync.test.ts +91 -0
- package/server/src/__tests__/paperclip-env.test.ts +58 -0
- package/server/src/__tests__/paperclip-skill-utils.test.ts +63 -0
- package/server/src/__tests__/pi-local-adapter-environment.test.ts +102 -0
- package/server/src/__tests__/pi-local-skill-sync.test.ts +95 -0
- package/server/src/__tests__/plugin-dev-watcher.test.ts +68 -0
- package/server/src/__tests__/plugin-worker-manager.test.ts +43 -0
- package/server/src/__tests__/private-hostname-guard.test.ts +56 -0
- package/server/src/__tests__/project-shortname-resolution.test.ts +45 -0
- package/server/src/__tests__/quota-windows-service.test.ts +56 -0
- package/server/src/__tests__/quota-windows.test.ts +1109 -0
- package/server/src/__tests__/redaction.test.ts +66 -0
- package/server/src/__tests__/routines-e2e.test.ts +276 -0
- package/server/src/__tests__/routines-routes.test.ts +271 -0
- package/server/src/__tests__/routines-service.test.ts +424 -0
- package/server/src/__tests__/storage-local-provider.test.ts +78 -0
- package/server/src/__tests__/ui-branding.test.ts +82 -0
- package/server/src/__tests__/work-products.test.ts +95 -0
- package/server/src/__tests__/workspace-runtime.test.ts +1131 -0
- package/server/src/__tests__/worktree-config.test.ts +426 -0
- package/server/src/adapters/codex-models.ts +105 -0
- package/server/src/adapters/cursor-models.ts +171 -0
- package/server/src/adapters/http/execute.ts +42 -0
- package/server/src/adapters/http/index.ts +21 -0
- package/server/src/adapters/http/test.ts +116 -0
- package/server/src/adapters/index.ts +18 -0
- package/server/src/adapters/process/execute.ts +77 -0
- package/server/src/adapters/process/index.ts +24 -0
- package/server/src/adapters/process/test.ts +89 -0
- package/server/src/adapters/registry.ts +225 -0
- package/server/src/adapters/server-utils-compat.ts +57 -0
- package/server/src/adapters/types.ts +30 -0
- package/server/src/adapters/utils.ts +48 -0
- package/server/src/agent-auth-jwt.ts +141 -0
- package/server/src/app.ts +321 -0
- package/server/src/attachment-types.ts +74 -0
- package/server/src/auth/better-auth.ts +148 -0
- package/server/src/board-claim.ts +150 -0
- package/server/src/config-file.ts +17 -0
- package/server/src/config.ts +260 -0
- package/server/src/dev-server-status.ts +103 -0
- package/server/src/dev-watch-ignore.ts +36 -0
- package/server/src/errors.ts +34 -0
- package/server/src/home-paths.ts +95 -0
- package/server/src/index.ts +799 -0
- package/server/src/log-redaction.ts +146 -0
- package/server/src/middleware/auth.ts +178 -0
- package/server/src/middleware/board-mutation-guard.ts +66 -0
- package/server/src/middleware/error-handler.ts +71 -0
- package/server/src/middleware/index.ts +3 -0
- package/server/src/middleware/logger.ts +90 -0
- package/server/src/middleware/private-hostname-guard.ts +92 -0
- package/server/src/middleware/validate.ts +9 -0
- package/server/src/onboarding-assets/ceo/AGENTS.md +54 -0
- package/server/src/onboarding-assets/ceo/HEARTBEAT.md +72 -0
- package/server/src/onboarding-assets/ceo/SOUL.md +33 -0
- package/server/src/onboarding-assets/ceo/TOOLS.md +3 -0
- package/server/src/onboarding-assets/default/AGENTS.md +3 -0
- package/server/src/paths.ts +34 -0
- package/server/src/realtime/live-events-ws.ts +274 -0
- package/server/src/redaction.ts +59 -0
- package/server/src/routes/access.ts +2888 -0
- package/server/src/routes/activity.ts +89 -0
- package/server/src/routes/agents.ts +2313 -0
- package/server/src/routes/approvals.ts +346 -0
- package/server/src/routes/assets.ts +341 -0
- package/server/src/routes/authz.ts +52 -0
- package/server/src/routes/companies.ts +343 -0
- package/server/src/routes/company-skills.ts +300 -0
- package/server/src/routes/costs.ts +335 -0
- package/server/src/routes/dashboard.ts +19 -0
- package/server/src/routes/execution-workspaces.ts +182 -0
- package/server/src/routes/goals.ts +107 -0
- package/server/src/routes/health.ts +94 -0
- package/server/src/routes/index.ts +17 -0
- package/server/src/routes/instance-settings.ts +95 -0
- package/server/src/routes/issues-checkout-wakeup.ts +14 -0
- package/server/src/routes/issues.ts +1680 -0
- package/server/src/routes/llms.ts +86 -0
- package/server/src/routes/org-chart-svg.ts +777 -0
- package/server/src/routes/plugin-ui-static.ts +497 -0
- package/server/src/routes/plugins.ts +2220 -0
- package/server/src/routes/projects.ts +295 -0
- package/server/src/routes/routines.ts +300 -0
- package/server/src/routes/secrets.ts +166 -0
- package/server/src/routes/sidebar-badges.ts +52 -0
- package/server/src/secrets/external-stub-providers.ts +32 -0
- package/server/src/secrets/local-encrypted-provider.ts +135 -0
- package/server/src/secrets/provider-registry.ts +31 -0
- package/server/src/secrets/types.ts +23 -0
- package/server/src/services/access.ts +381 -0
- package/server/src/services/activity-log.ts +95 -0
- package/server/src/services/activity.ts +164 -0
- package/server/src/services/agent-instructions.ts +735 -0
- package/server/src/services/agent-permissions.ts +27 -0
- package/server/src/services/agents.ts +694 -0
- package/server/src/services/approvals.ts +273 -0
- package/server/src/services/assets.ts +23 -0
- package/server/src/services/board-auth.ts +355 -0
- package/server/src/services/budgets.ts +959 -0
- package/server/src/services/companies.ts +313 -0
- package/server/src/services/company-export-readme.ts +173 -0
- package/server/src/services/company-portability.ts +4263 -0
- package/server/src/services/company-skills.ts +2356 -0
- package/server/src/services/costs.ts +365 -0
- package/server/src/services/cron.ts +373 -0
- package/server/src/services/dashboard.ts +110 -0
- package/server/src/services/default-agent-instructions.ts +27 -0
- package/server/src/services/documents.ts +434 -0
- package/server/src/services/execution-workspace-policy.ts +210 -0
- package/server/src/services/execution-workspaces.ts +100 -0
- package/server/src/services/finance.ts +135 -0
- package/server/src/services/goals.ts +81 -0
- package/server/src/services/heartbeat-run-summary.ts +35 -0
- package/server/src/services/heartbeat.ts +3863 -0
- package/server/src/services/hire-hook.ts +114 -0
- package/server/src/services/index.ts +32 -0
- package/server/src/services/instance-settings.ts +138 -0
- package/server/src/services/issue-approvals.ts +175 -0
- package/server/src/services/issue-assignment-wakeup.ts +48 -0
- package/server/src/services/issue-goal-fallback.ts +56 -0
- package/server/src/services/issues.ts +1828 -0
- package/server/src/services/live-events.ts +55 -0
- package/server/src/services/plugin-capability-validator.ts +450 -0
- package/server/src/services/plugin-config-validator.ts +55 -0
- package/server/src/services/plugin-dev-watcher.ts +339 -0
- package/server/src/services/plugin-event-bus.ts +413 -0
- package/server/src/services/plugin-host-service-cleanup.ts +59 -0
- package/server/src/services/plugin-host-services.ts +1132 -0
- package/server/src/services/plugin-job-coordinator.ts +261 -0
- package/server/src/services/plugin-job-scheduler.ts +753 -0
- package/server/src/services/plugin-job-store.ts +466 -0
- package/server/src/services/plugin-lifecycle.ts +822 -0
- package/server/src/services/plugin-loader.ts +1955 -0
- package/server/src/services/plugin-log-retention.ts +87 -0
- package/server/src/services/plugin-manifest-validator.ts +164 -0
- package/server/src/services/plugin-registry.ts +683 -0
- package/server/src/services/plugin-runtime-sandbox.ts +222 -0
- package/server/src/services/plugin-secrets-handler.ts +355 -0
- package/server/src/services/plugin-state-store.ts +238 -0
- package/server/src/services/plugin-stream-bus.ts +81 -0
- package/server/src/services/plugin-tool-dispatcher.ts +449 -0
- package/server/src/services/plugin-tool-registry.ts +450 -0
- package/server/src/services/plugin-worker-manager.ts +1343 -0
- package/server/src/services/projects.ts +860 -0
- package/server/src/services/quota-windows.ts +65 -0
- package/server/src/services/routines.ts +1269 -0
- package/server/src/services/run-log-store.ts +156 -0
- package/server/src/services/secrets.ts +370 -0
- package/server/src/services/sidebar-badges.ts +56 -0
- package/server/src/services/work-products.ts +124 -0
- package/server/src/services/workspace-operation-log-store.ts +156 -0
- package/server/src/services/workspace-operations.ts +262 -0
- package/server/src/services/workspace-runtime.ts +1565 -0
- package/server/src/startup-banner.ts +176 -0
- package/server/src/storage/index.ts +35 -0
- package/server/src/storage/local-disk-provider.ts +89 -0
- package/server/src/storage/provider-registry.ts +18 -0
- package/server/src/storage/s3-provider.ts +153 -0
- package/server/src/storage/service.ts +131 -0
- package/server/src/storage/types.ts +63 -0
- package/server/src/ui-branding.ts +217 -0
- package/server/src/version.ts +10 -0
- package/server/src/worktree-config.ts +468 -0
- package/server/tsconfig.json +9 -0
- package/server/vitest.config.ts +7 -0
- package/skills/paperclip/SKILL.md +365 -0
- package/skills/paperclip/references/api-reference.md +647 -0
- package/skills/paperclip/references/company-skills.md +193 -0
- package/skills/paperclip-create-agent/SKILL.md +142 -0
- package/skills/paperclip-create-agent/references/api-reference.md +105 -0
- package/skills/paperclip-create-plugin/SKILL.md +102 -0
- package/skills/para-memory-files/SKILL.md +104 -0
- package/skills/para-memory-files/references/schemas.md +35 -0
- package/tests/e2e/onboarding.spec.ts +142 -0
- package/tests/e2e/playwright.config.ts +35 -0
- package/tests/release-smoke/docker-auth-onboarding.spec.ts +141 -0
- package/tests/release-smoke/playwright.config.ts +28 -0
- package/tsconfig.base.json +18 -0
- package/tsconfig.json +18 -0
- package/ui/README.md +12 -0
- package/ui/components.json +21 -0
- package/ui/index.html +47 -0
- package/ui/package.json +73 -0
- package/ui/public/android-chrome-192x192.png +0 -0
- package/ui/public/android-chrome-512x512.png +0 -0
- package/ui/public/apple-touch-icon.png +0 -0
- package/ui/public/brands/opencode-logo-dark-square.svg +18 -0
- package/ui/public/brands/opencode-logo-light-square.svg +18 -0
- package/ui/public/favicon-16x16.png +0 -0
- package/ui/public/favicon-32x32.png +0 -0
- package/ui/public/favicon.ico +0 -0
- package/ui/public/favicon.svg +9 -0
- package/ui/public/site.webmanifest +30 -0
- package/ui/public/sprites/1-D-1.png +0 -0
- package/ui/public/sprites/1-D-2.png +0 -0
- package/ui/public/sprites/1-D-3.png +0 -0
- package/ui/public/sprites/1-L-1.png +0 -0
- package/ui/public/sprites/1-R-1.png +0 -0
- package/ui/public/sprites/10-D-1.png +0 -0
- package/ui/public/sprites/10-D-2.png +0 -0
- package/ui/public/sprites/10-D-3.png +0 -0
- package/ui/public/sprites/10-L-1.png +0 -0
- package/ui/public/sprites/10-R-1.png +0 -0
- package/ui/public/sprites/11-D-1.png +0 -0
- package/ui/public/sprites/11-D-2.png +0 -0
- package/ui/public/sprites/11-D-3.png +0 -0
- package/ui/public/sprites/11-L-1.png +0 -0
- package/ui/public/sprites/11-R-1.png +0 -0
- package/ui/public/sprites/12-D-1.png +0 -0
- package/ui/public/sprites/12-D-2.png +0 -0
- package/ui/public/sprites/12-D-3.png +0 -0
- package/ui/public/sprites/12-L-1.png +0 -0
- package/ui/public/sprites/12-R-1.png +0 -0
- package/ui/public/sprites/13-D-1.png +0 -0
- package/ui/public/sprites/13-D-2.png +0 -0
- package/ui/public/sprites/13-D-3.png +0 -0
- package/ui/public/sprites/13-L-1.png +0 -0
- package/ui/public/sprites/13-R-1.png +0 -0
- package/ui/public/sprites/14-D-1.png +0 -0
- package/ui/public/sprites/14-D-2.png +0 -0
- package/ui/public/sprites/14-D-3.png +0 -0
- package/ui/public/sprites/14-L-1.png +0 -0
- package/ui/public/sprites/14-R-1.png +0 -0
- package/ui/public/sprites/2-D-1.png +0 -0
- package/ui/public/sprites/2-D-2.png +0 -0
- package/ui/public/sprites/2-D-3.png +0 -0
- package/ui/public/sprites/2-L-1.png +0 -0
- package/ui/public/sprites/2-R-1.png +0 -0
- package/ui/public/sprites/3-D-1.png +0 -0
- package/ui/public/sprites/3-D-2.png +0 -0
- package/ui/public/sprites/3-D-3.png +0 -0
- package/ui/public/sprites/3-L-1.png +0 -0
- package/ui/public/sprites/3-R-1.png +0 -0
- package/ui/public/sprites/4-D-1.png +0 -0
- package/ui/public/sprites/4-D-2.png +0 -0
- package/ui/public/sprites/4-D-3.png +0 -0
- package/ui/public/sprites/4-L-1.png +0 -0
- package/ui/public/sprites/4-R-1.png +0 -0
- package/ui/public/sprites/5-D-1.png +0 -0
- package/ui/public/sprites/5-D-2.png +0 -0
- package/ui/public/sprites/5-D-3.png +0 -0
- package/ui/public/sprites/5-L-1.png +0 -0
- package/ui/public/sprites/5-R-1.png +0 -0
- package/ui/public/sprites/6-D-1.png +0 -0
- package/ui/public/sprites/6-D-2.png +0 -0
- package/ui/public/sprites/6-D-3.png +0 -0
- package/ui/public/sprites/6-L-1.png +0 -0
- package/ui/public/sprites/6-R-1.png +0 -0
- package/ui/public/sprites/7-D-1.png +0 -0
- package/ui/public/sprites/7-D-2.png +0 -0
- package/ui/public/sprites/7-D-3.png +0 -0
- package/ui/public/sprites/7-L-1.png +0 -0
- package/ui/public/sprites/7-R-1.png +0 -0
- package/ui/public/sprites/8-D-1.png +0 -0
- package/ui/public/sprites/8-D-2.png +0 -0
- package/ui/public/sprites/8-D-3.png +0 -0
- package/ui/public/sprites/8-L-1.png +0 -0
- package/ui/public/sprites/8-R-1.png +0 -0
- package/ui/public/sprites/9-D-1.png +0 -0
- package/ui/public/sprites/9-D-2.png +0 -0
- package/ui/public/sprites/9-D-3.png +0 -0
- package/ui/public/sprites/9-L-1.png +0 -0
- package/ui/public/sprites/9-R-1.png +0 -0
- package/ui/public/sprites/ceo-lobster.png +0 -0
- package/ui/public/sw.js +42 -0
- package/ui/public/worktree-favicon-16x16.png +0 -0
- package/ui/public/worktree-favicon-32x32.png +0 -0
- package/ui/public/worktree-favicon.ico +0 -0
- package/ui/public/worktree-favicon.svg +9 -0
- package/ui/src/App.tsx +354 -0
- package/ui/src/adapters/claude-local/config-fields.tsx +138 -0
- package/ui/src/adapters/claude-local/index.ts +13 -0
- package/ui/src/adapters/codex-local/config-fields.tsx +104 -0
- package/ui/src/adapters/codex-local/index.ts +13 -0
- package/ui/src/adapters/cursor/config-fields.tsx +49 -0
- package/ui/src/adapters/cursor/index.ts +13 -0
- package/ui/src/adapters/gemini-local/config-fields.tsx +51 -0
- package/ui/src/adapters/gemini-local/index.ts +13 -0
- package/ui/src/adapters/http/build-config.ts +9 -0
- package/ui/src/adapters/http/config-fields.tsx +38 -0
- package/ui/src/adapters/http/index.ts +12 -0
- package/ui/src/adapters/http/parse-stdout.ts +5 -0
- package/ui/src/adapters/index.ts +9 -0
- package/ui/src/adapters/local-workspace-runtime-fields.tsx +5 -0
- package/ui/src/adapters/openclaw-gateway/config-fields.tsx +237 -0
- package/ui/src/adapters/openclaw-gateway/index.ts +13 -0
- package/ui/src/adapters/opencode-local/config-fields.tsx +72 -0
- package/ui/src/adapters/opencode-local/index.ts +13 -0
- package/ui/src/adapters/pi-local/config-fields.tsx +49 -0
- package/ui/src/adapters/pi-local/index.ts +13 -0
- package/ui/src/adapters/process/build-config.ts +18 -0
- package/ui/src/adapters/process/config-fields.tsx +77 -0
- package/ui/src/adapters/process/index.ts +12 -0
- package/ui/src/adapters/process/parse-stdout.ts +5 -0
- package/ui/src/adapters/registry.ts +34 -0
- package/ui/src/adapters/runtime-json-fields.tsx +122 -0
- package/ui/src/adapters/transcript.test.ts +30 -0
- package/ui/src/adapters/transcript.ts +62 -0
- package/ui/src/adapters/types.ts +34 -0
- package/ui/src/api/access.ts +160 -0
- package/ui/src/api/activity.ts +37 -0
- package/ui/src/api/agents.ts +194 -0
- package/ui/src/api/approvals.ts +25 -0
- package/ui/src/api/assets.ts +30 -0
- package/ui/src/api/auth.ts +74 -0
- package/ui/src/api/budgets.ts +21 -0
- package/ui/src/api/client.ts +50 -0
- package/ui/src/api/companies.ts +59 -0
- package/ui/src/api/companySkills.ts +55 -0
- package/ui/src/api/costs.ts +60 -0
- package/ui/src/api/dashboard.ts +7 -0
- package/ui/src/api/execution-workspaces.ts +27 -0
- package/ui/src/api/goals.ts +12 -0
- package/ui/src/api/health.ts +41 -0
- package/ui/src/api/heartbeats.ts +62 -0
- package/ui/src/api/index.ts +18 -0
- package/ui/src/api/instanceSettings.ts +19 -0
- package/ui/src/api/issues.ts +115 -0
- package/ui/src/api/plugins.ts +424 -0
- package/ui/src/api/projects.ts +34 -0
- package/ui/src/api/routines.ts +59 -0
- package/ui/src/api/secrets.ts +26 -0
- package/ui/src/api/sidebarBadges.ts +7 -0
- package/ui/src/components/AccountingModelCard.tsx +69 -0
- package/ui/src/components/ActiveAgentsPanel.tsx +157 -0
- package/ui/src/components/ActivityCharts.tsx +264 -0
- package/ui/src/components/ActivityRow.tsx +147 -0
- package/ui/src/components/AgentActionButtons.tsx +51 -0
- package/ui/src/components/AgentConfigForm.tsx +1468 -0
- package/ui/src/components/AgentIconPicker.tsx +81 -0
- package/ui/src/components/AgentProperties.tsx +107 -0
- package/ui/src/components/ApprovalCard.tsx +107 -0
- package/ui/src/components/ApprovalPayload.tsx +134 -0
- package/ui/src/components/AsciiArtAnimation.tsx +355 -0
- package/ui/src/components/BillerSpendCard.tsx +146 -0
- package/ui/src/components/BreadcrumbBar.tsx +113 -0
- package/ui/src/components/BudgetIncidentCard.tsx +101 -0
- package/ui/src/components/BudgetPolicyCard.tsx +220 -0
- package/ui/src/components/BudgetSidebarMarker.tsx +13 -0
- package/ui/src/components/ClaudeSubscriptionPanel.tsx +141 -0
- package/ui/src/components/CodexSubscriptionPanel.tsx +158 -0
- package/ui/src/components/CommandPalette.tsx +239 -0
- package/ui/src/components/CommentThread.tsx +503 -0
- package/ui/src/components/CompanyPatternIcon.tsx +212 -0
- package/ui/src/components/CompanyRail.tsx +329 -0
- package/ui/src/components/CompanySwitcher.tsx +81 -0
- package/ui/src/components/CopyText.tsx +56 -0
- package/ui/src/components/DevRestartBanner.tsx +89 -0
- package/ui/src/components/EmptyState.tsx +27 -0
- package/ui/src/components/EntityRow.tsx +69 -0
- package/ui/src/components/FilterBar.tsx +39 -0
- package/ui/src/components/FinanceBillerCard.tsx +45 -0
- package/ui/src/components/FinanceKindCard.tsx +44 -0
- package/ui/src/components/FinanceTimelineCard.tsx +72 -0
- package/ui/src/components/GoalProperties.tsx +165 -0
- package/ui/src/components/GoalTree.tsx +118 -0
- package/ui/src/components/Identity.tsx +39 -0
- package/ui/src/components/InlineEditor.tsx +248 -0
- package/ui/src/components/InlineEntitySelector.tsx +206 -0
- package/ui/src/components/InstanceSidebar.tsx +53 -0
- package/ui/src/components/IssueDocumentsSection.tsx +892 -0
- package/ui/src/components/IssueProperties.tsx +621 -0
- package/ui/src/components/IssueRow.tsx +149 -0
- package/ui/src/components/IssueWorkspaceCard.tsx +404 -0
- package/ui/src/components/IssuesList.tsx +889 -0
- package/ui/src/components/JsonSchemaForm.tsx +1048 -0
- package/ui/src/components/KanbanBoard.tsx +275 -0
- package/ui/src/components/Layout.tsx +441 -0
- package/ui/src/components/LiveRunWidget.tsx +160 -0
- package/ui/src/components/MarkdownBody.test.tsx +50 -0
- package/ui/src/components/MarkdownBody.tsx +152 -0
- package/ui/src/components/MarkdownEditor.tsx +622 -0
- package/ui/src/components/MetricCard.tsx +53 -0
- package/ui/src/components/MobileBottomNav.tsx +123 -0
- package/ui/src/components/NewAgentDialog.tsx +223 -0
- package/ui/src/components/NewGoalDialog.tsx +283 -0
- package/ui/src/components/NewIssueDialog.tsx +1473 -0
- package/ui/src/components/NewProjectDialog.tsx +451 -0
- package/ui/src/components/OnboardingWizard.tsx +1392 -0
- package/ui/src/components/OpenCodeLogoIcon.tsx +22 -0
- package/ui/src/components/PackageFileTree.tsx +318 -0
- package/ui/src/components/PageSkeleton.tsx +180 -0
- package/ui/src/components/PageTabBar.tsx +45 -0
- package/ui/src/components/PathInstructionsModal.tsx +143 -0
- package/ui/src/components/PriorityIcon.tsx +77 -0
- package/ui/src/components/ProjectProperties.tsx +1127 -0
- package/ui/src/components/PropertiesPanel.tsx +29 -0
- package/ui/src/components/ProviderQuotaCard.tsx +417 -0
- package/ui/src/components/QuotaBar.tsx +65 -0
- package/ui/src/components/ReportsToPicker.tsx +127 -0
- package/ui/src/components/ScheduleEditor.tsx +344 -0
- package/ui/src/components/ScrollToBottom.tsx +79 -0
- package/ui/src/components/Sidebar.tsx +130 -0
- package/ui/src/components/SidebarAgents.tsx +146 -0
- package/ui/src/components/SidebarNavItem.tsx +92 -0
- package/ui/src/components/SidebarProjects.tsx +234 -0
- package/ui/src/components/SidebarSection.tsx +17 -0
- package/ui/src/components/StatusBadge.tsx +15 -0
- package/ui/src/components/StatusIcon.tsx +71 -0
- package/ui/src/components/SwipeToArchive.tsx +152 -0
- package/ui/src/components/ToastViewport.tsx +99 -0
- package/ui/src/components/WorktreeBanner.tsx +25 -0
- package/ui/src/components/agent-config-defaults.ts +31 -0
- package/ui/src/components/agent-config-primitives.tsx +476 -0
- package/ui/src/components/transcript/RunTranscriptView.test.tsx +84 -0
- package/ui/src/components/transcript/RunTranscriptView.tsx +1015 -0
- package/ui/src/components/transcript/useLiveRunTranscripts.ts +297 -0
- package/ui/src/components/ui/avatar.tsx +107 -0
- package/ui/src/components/ui/badge.tsx +48 -0
- package/ui/src/components/ui/breadcrumb.tsx +109 -0
- package/ui/src/components/ui/button.tsx +64 -0
- package/ui/src/components/ui/card.tsx +92 -0
- package/ui/src/components/ui/checkbox.tsx +32 -0
- package/ui/src/components/ui/collapsible.tsx +33 -0
- package/ui/src/components/ui/command.tsx +194 -0
- package/ui/src/components/ui/dialog.tsx +156 -0
- package/ui/src/components/ui/dropdown-menu.tsx +257 -0
- package/ui/src/components/ui/input.tsx +21 -0
- package/ui/src/components/ui/label.tsx +22 -0
- package/ui/src/components/ui/popover.tsx +88 -0
- package/ui/src/components/ui/scroll-area.tsx +56 -0
- package/ui/src/components/ui/select.tsx +188 -0
- package/ui/src/components/ui/separator.tsx +28 -0
- package/ui/src/components/ui/sheet.tsx +143 -0
- package/ui/src/components/ui/skeleton.tsx +13 -0
- package/ui/src/components/ui/tabs.tsx +89 -0
- package/ui/src/components/ui/textarea.tsx +18 -0
- package/ui/src/components/ui/tooltip.tsx +57 -0
- package/ui/src/components/visual-office/AgentAvatar.tsx +99 -0
- package/ui/src/components/visual-office/OfficeViewExact.tsx +417 -0
- package/ui/src/components/visual-office/i18n.ts +52 -0
- package/ui/src/components/visual-office/office-view/CliUsagePanel.tsx +240 -0
- package/ui/src/components/visual-office/office-view/VirtualPadOverlay.tsx +104 -0
- package/ui/src/components/visual-office/office-view/buildScene-break-room.ts +248 -0
- package/ui/src/components/visual-office/office-view/buildScene-ceo-hallway.ts +345 -0
- package/ui/src/components/visual-office/office-view/buildScene-department-agent.ts +242 -0
- package/ui/src/components/visual-office/office-view/buildScene-departments.ts +360 -0
- package/ui/src/components/visual-office/office-view/buildScene-final-layers.ts +113 -0
- package/ui/src/components/visual-office/office-view/buildScene-types.ts +91 -0
- package/ui/src/components/visual-office/office-view/buildScene.ts +232 -0
- package/ui/src/components/visual-office/office-view/drawing-core.ts +374 -0
- package/ui/src/components/visual-office/office-view/drawing-furniture-a.ts +338 -0
- package/ui/src/components/visual-office/office-view/drawing-furniture-b.ts +241 -0
- package/ui/src/components/visual-office/office-view/model.ts +301 -0
- package/ui/src/components/visual-office/office-view/officeTicker.ts +455 -0
- package/ui/src/components/visual-office/office-view/officeTickerRoomAndDelivery.ts +133 -0
- package/ui/src/components/visual-office/office-view/themes-locale.ts +460 -0
- package/ui/src/components/visual-office/office-view/useCliUsage.ts +37 -0
- package/ui/src/components/visual-office/office-view/useOfficeDeliveryEffects.ts +465 -0
- package/ui/src/components/visual-office/office-view/useOfficePixiRuntime.ts +282 -0
- package/ui/src/components/visual-office/types.ts +123 -0
- package/ui/src/context/BreadcrumbContext.tsx +44 -0
- package/ui/src/context/CompanyContext.tsx +151 -0
- package/ui/src/context/DialogContext.tsx +135 -0
- package/ui/src/context/LiveUpdatesProvider.test.ts +119 -0
- package/ui/src/context/LiveUpdatesProvider.tsx +760 -0
- package/ui/src/context/PanelContext.tsx +73 -0
- package/ui/src/context/SidebarContext.tsx +43 -0
- package/ui/src/context/ThemeContext.tsx +83 -0
- package/ui/src/context/ToastContext.tsx +172 -0
- package/ui/src/fixtures/runTranscriptFixtures.ts +226 -0
- package/ui/src/hooks/useAgentOrder.ts +105 -0
- package/ui/src/hooks/useAutosaveIndicator.ts +72 -0
- package/ui/src/hooks/useCompanyPageMemory.test.ts +90 -0
- package/ui/src/hooks/useCompanyPageMemory.ts +79 -0
- package/ui/src/hooks/useDateRange.ts +120 -0
- package/ui/src/hooks/useInboxBadge.ts +132 -0
- package/ui/src/hooks/useKeyboardShortcuts.ts +40 -0
- package/ui/src/hooks/useProjectOrder.ts +106 -0
- package/ui/src/index.css +770 -0
- package/ui/src/lib/agent-icons.ts +99 -0
- package/ui/src/lib/agent-order.ts +107 -0
- package/ui/src/lib/agent-skills-state.test.ts +90 -0
- package/ui/src/lib/agent-skills-state.ts +41 -0
- package/ui/src/lib/assignees.test.ts +92 -0
- package/ui/src/lib/assignees.ts +82 -0
- package/ui/src/lib/color-contrast.ts +107 -0
- package/ui/src/lib/company-export-selection.test.ts +41 -0
- package/ui/src/lib/company-export-selection.ts +57 -0
- package/ui/src/lib/company-page-memory.ts +65 -0
- package/ui/src/lib/company-portability-sidebar.test.ts +101 -0
- package/ui/src/lib/company-portability-sidebar.ts +62 -0
- package/ui/src/lib/company-routes.ts +88 -0
- package/ui/src/lib/company-selection.test.ts +34 -0
- package/ui/src/lib/company-selection.ts +18 -0
- package/ui/src/lib/groupBy.ts +11 -0
- package/ui/src/lib/inbox.test.ts +404 -0
- package/ui/src/lib/inbox.ts +292 -0
- package/ui/src/lib/instance-settings.test.ts +26 -0
- package/ui/src/lib/instance-settings.ts +25 -0
- package/ui/src/lib/issueDetailBreadcrumb.ts +24 -0
- package/ui/src/lib/legacy-agent-config.test.ts +40 -0
- package/ui/src/lib/legacy-agent-config.ts +17 -0
- package/ui/src/lib/mention-aware-link-node.test.ts +50 -0
- package/ui/src/lib/mention-aware-link-node.ts +67 -0
- package/ui/src/lib/mention-chips.ts +168 -0
- package/ui/src/lib/mention-deletion.test.ts +87 -0
- package/ui/src/lib/mention-deletion.ts +143 -0
- package/ui/src/lib/model-utils.ts +16 -0
- package/ui/src/lib/onboarding-goal.test.ts +22 -0
- package/ui/src/lib/onboarding-goal.ts +18 -0
- package/ui/src/lib/onboarding-launch.test.ts +131 -0
- package/ui/src/lib/onboarding-launch.ts +54 -0
- package/ui/src/lib/onboarding-route.test.ts +80 -0
- package/ui/src/lib/onboarding-route.ts +51 -0
- package/ui/src/lib/portable-files.ts +42 -0
- package/ui/src/lib/project-order.ts +71 -0
- package/ui/src/lib/queryKeys.ts +140 -0
- package/ui/src/lib/recent-assignees.ts +36 -0
- package/ui/src/lib/router.tsx +76 -0
- package/ui/src/lib/routine-trigger-patch.test.ts +72 -0
- package/ui/src/lib/routine-trigger-patch.ts +31 -0
- package/ui/src/lib/status-colors.ts +108 -0
- package/ui/src/lib/timeAgo.ts +31 -0
- package/ui/src/lib/utils.ts +168 -0
- package/ui/src/lib/worktree-branding.ts +65 -0
- package/ui/src/lib/zip.test.ts +289 -0
- package/ui/src/lib/zip.ts +284 -0
- package/ui/src/main.tsx +67 -0
- package/ui/src/pages/Activity.tsx +141 -0
- package/ui/src/pages/AgentDetail.tsx +4053 -0
- package/ui/src/pages/Agents.tsx +415 -0
- package/ui/src/pages/ApprovalDetail.tsx +369 -0
- package/ui/src/pages/Approvals.tsx +132 -0
- package/ui/src/pages/Auth.tsx +180 -0
- package/ui/src/pages/BoardClaim.tsx +125 -0
- package/ui/src/pages/CliAuth.tsx +184 -0
- package/ui/src/pages/Companies.tsx +297 -0
- package/ui/src/pages/CompanyExport.tsx +1019 -0
- package/ui/src/pages/CompanyImport.tsx +1355 -0
- package/ui/src/pages/CompanySettings.tsx +661 -0
- package/ui/src/pages/CompanySkills.tsx +1171 -0
- package/ui/src/pages/Costs.tsx +1103 -0
- package/ui/src/pages/Dashboard.tsx +388 -0
- package/ui/src/pages/DesignGuide.tsx +1330 -0
- package/ui/src/pages/ExecutionWorkspaceDetail.tsx +82 -0
- package/ui/src/pages/GoalDetail.tsx +197 -0
- package/ui/src/pages/Goals.tsx +63 -0
- package/ui/src/pages/Inbox.tsx +1291 -0
- package/ui/src/pages/InstanceExperimentalSettings.tsx +139 -0
- package/ui/src/pages/InstanceGeneralSettings.tsx +104 -0
- package/ui/src/pages/InstanceSettings.tsx +284 -0
- package/ui/src/pages/InviteLanding.tsx +320 -0
- package/ui/src/pages/IssueDetail.tsx +1201 -0
- package/ui/src/pages/Issues.tsx +116 -0
- package/ui/src/pages/MyIssues.tsx +72 -0
- package/ui/src/pages/NewAgent.tsx +353 -0
- package/ui/src/pages/NotFound.tsx +66 -0
- package/ui/src/pages/Org.tsx +132 -0
- package/ui/src/pages/OrgChart.tsx +447 -0
- package/ui/src/pages/PluginManager.tsx +510 -0
- package/ui/src/pages/PluginPage.tsx +156 -0
- package/ui/src/pages/PluginSettings.tsx +836 -0
- package/ui/src/pages/ProjectDetail.tsx +633 -0
- package/ui/src/pages/Projects.tsx +87 -0
- package/ui/src/pages/RoutineDetail.tsx +1022 -0
- package/ui/src/pages/Routines.tsx +661 -0
- package/ui/src/pages/RunTranscriptUxLab.tsx +334 -0
- package/ui/src/pages/VisualOffice.tsx +243 -0
- package/ui/src/plugins/bridge-init.ts +69 -0
- package/ui/src/plugins/bridge.ts +476 -0
- package/ui/src/plugins/launchers.tsx +834 -0
- package/ui/src/plugins/slots.tsx +855 -0
- package/ui/tsconfig.json +21 -0
- package/ui/vite.config.ts +23 -0
- package/ui/vitest.config.ts +14 -0
- package/vitest.config.ts +11 -0
|
@@ -0,0 +1,959 @@
|
|
|
1
|
+
import { and, desc, eq, gte, inArray, lt, ne, sql } from "drizzle-orm";
|
|
2
|
+
import type { Db } from "@corporateai/db";
|
|
3
|
+
import {
|
|
4
|
+
agents,
|
|
5
|
+
approvals,
|
|
6
|
+
budgetIncidents,
|
|
7
|
+
budgetPolicies,
|
|
8
|
+
companies,
|
|
9
|
+
costEvents,
|
|
10
|
+
projects,
|
|
11
|
+
} from "@corporateai/db";
|
|
12
|
+
import type {
|
|
13
|
+
BudgetIncident,
|
|
14
|
+
BudgetIncidentResolutionInput,
|
|
15
|
+
BudgetMetric,
|
|
16
|
+
BudgetOverview,
|
|
17
|
+
BudgetPolicy,
|
|
18
|
+
BudgetPolicySummary,
|
|
19
|
+
BudgetPolicyUpsertInput,
|
|
20
|
+
BudgetScopeType,
|
|
21
|
+
BudgetThresholdType,
|
|
22
|
+
BudgetWindowKind,
|
|
23
|
+
} from "@corporateai/shared";
|
|
24
|
+
import { notFound, unprocessable } from "../errors.js";
|
|
25
|
+
import { logActivity } from "./activity-log.js";
|
|
26
|
+
|
|
27
|
+
type ScopeRecord = {
|
|
28
|
+
companyId: string;
|
|
29
|
+
name: string;
|
|
30
|
+
paused: boolean;
|
|
31
|
+
pauseReason: "manual" | "budget" | "system" | null;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
type PolicyRow = typeof budgetPolicies.$inferSelect;
|
|
35
|
+
type IncidentRow = typeof budgetIncidents.$inferSelect;
|
|
36
|
+
|
|
37
|
+
export type BudgetEnforcementScope = {
|
|
38
|
+
companyId: string;
|
|
39
|
+
scopeType: BudgetScopeType;
|
|
40
|
+
scopeId: string;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export type BudgetServiceHooks = {
|
|
44
|
+
cancelWorkForScope?: (scope: BudgetEnforcementScope) => Promise<void>;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
function currentUtcMonthWindow(now = new Date()) {
|
|
48
|
+
const year = now.getUTCFullYear();
|
|
49
|
+
const month = now.getUTCMonth();
|
|
50
|
+
const start = new Date(Date.UTC(year, month, 1, 0, 0, 0, 0));
|
|
51
|
+
const end = new Date(Date.UTC(year, month + 1, 1, 0, 0, 0, 0));
|
|
52
|
+
return { start, end };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function resolveWindow(windowKind: BudgetWindowKind, now = new Date()) {
|
|
56
|
+
if (windowKind === "lifetime") {
|
|
57
|
+
return {
|
|
58
|
+
start: new Date(Date.UTC(1970, 0, 1, 0, 0, 0, 0)),
|
|
59
|
+
end: new Date(Date.UTC(9999, 0, 1, 0, 0, 0, 0)),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return currentUtcMonthWindow(now);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function budgetStatusFromObserved(
|
|
66
|
+
observedAmount: number,
|
|
67
|
+
amount: number,
|
|
68
|
+
warnPercent: number,
|
|
69
|
+
): BudgetPolicySummary["status"] {
|
|
70
|
+
if (amount <= 0) return "ok";
|
|
71
|
+
if (observedAmount >= amount) return "hard_stop";
|
|
72
|
+
if (observedAmount >= Math.ceil((amount * warnPercent) / 100)) return "warning";
|
|
73
|
+
return "ok";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function normalizeScopeName(scopeType: BudgetScopeType, name: string) {
|
|
77
|
+
if (scopeType === "company") return name;
|
|
78
|
+
return name.trim().length > 0 ? name : scopeType;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function resolveScopeRecord(db: Db, scopeType: BudgetScopeType, scopeId: string): Promise<ScopeRecord> {
|
|
82
|
+
if (scopeType === "company") {
|
|
83
|
+
const row = await db
|
|
84
|
+
.select({
|
|
85
|
+
companyId: companies.id,
|
|
86
|
+
name: companies.name,
|
|
87
|
+
status: companies.status,
|
|
88
|
+
pauseReason: companies.pauseReason,
|
|
89
|
+
pausedAt: companies.pausedAt,
|
|
90
|
+
})
|
|
91
|
+
.from(companies)
|
|
92
|
+
.where(eq(companies.id, scopeId))
|
|
93
|
+
.then((rows) => rows[0] ?? null);
|
|
94
|
+
if (!row) throw notFound("Company not found");
|
|
95
|
+
return {
|
|
96
|
+
companyId: row.companyId,
|
|
97
|
+
name: row.name,
|
|
98
|
+
paused: row.status === "paused" || Boolean(row.pausedAt),
|
|
99
|
+
pauseReason: (row.pauseReason as ScopeRecord["pauseReason"]) ?? null,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (scopeType === "agent") {
|
|
104
|
+
const row = await db
|
|
105
|
+
.select({
|
|
106
|
+
companyId: agents.companyId,
|
|
107
|
+
name: agents.name,
|
|
108
|
+
status: agents.status,
|
|
109
|
+
pauseReason: agents.pauseReason,
|
|
110
|
+
})
|
|
111
|
+
.from(agents)
|
|
112
|
+
.where(eq(agents.id, scopeId))
|
|
113
|
+
.then((rows) => rows[0] ?? null);
|
|
114
|
+
if (!row) throw notFound("Agent not found");
|
|
115
|
+
return {
|
|
116
|
+
companyId: row.companyId,
|
|
117
|
+
name: row.name,
|
|
118
|
+
paused: row.status === "paused",
|
|
119
|
+
pauseReason: (row.pauseReason as ScopeRecord["pauseReason"]) ?? null,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const row = await db
|
|
124
|
+
.select({
|
|
125
|
+
companyId: projects.companyId,
|
|
126
|
+
name: projects.name,
|
|
127
|
+
pauseReason: projects.pauseReason,
|
|
128
|
+
pausedAt: projects.pausedAt,
|
|
129
|
+
})
|
|
130
|
+
.from(projects)
|
|
131
|
+
.where(eq(projects.id, scopeId))
|
|
132
|
+
.then((rows) => rows[0] ?? null);
|
|
133
|
+
if (!row) throw notFound("Project not found");
|
|
134
|
+
return {
|
|
135
|
+
companyId: row.companyId,
|
|
136
|
+
name: row.name,
|
|
137
|
+
paused: Boolean(row.pausedAt),
|
|
138
|
+
pauseReason: (row.pauseReason as ScopeRecord["pauseReason"]) ?? null,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function computeObservedAmount(
|
|
143
|
+
db: Db,
|
|
144
|
+
policy: Pick<PolicyRow, "companyId" | "scopeType" | "scopeId" | "windowKind" | "metric">,
|
|
145
|
+
) {
|
|
146
|
+
if (policy.metric !== "billed_cents") return 0;
|
|
147
|
+
|
|
148
|
+
const conditions = [eq(costEvents.companyId, policy.companyId)];
|
|
149
|
+
if (policy.scopeType === "agent") conditions.push(eq(costEvents.agentId, policy.scopeId));
|
|
150
|
+
if (policy.scopeType === "project") conditions.push(eq(costEvents.projectId, policy.scopeId));
|
|
151
|
+
const { start, end } = resolveWindow(policy.windowKind as BudgetWindowKind);
|
|
152
|
+
if (policy.windowKind === "calendar_month_utc") {
|
|
153
|
+
conditions.push(gte(costEvents.occurredAt, start));
|
|
154
|
+
conditions.push(lt(costEvents.occurredAt, end));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const [row] = await db
|
|
158
|
+
.select({
|
|
159
|
+
total: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::int`,
|
|
160
|
+
})
|
|
161
|
+
.from(costEvents)
|
|
162
|
+
.where(and(...conditions));
|
|
163
|
+
|
|
164
|
+
return Number(row?.total ?? 0);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function buildApprovalPayload(input: {
|
|
168
|
+
policy: PolicyRow;
|
|
169
|
+
scopeName: string;
|
|
170
|
+
thresholdType: BudgetThresholdType;
|
|
171
|
+
amountObserved: number;
|
|
172
|
+
windowStart: Date;
|
|
173
|
+
windowEnd: Date;
|
|
174
|
+
}) {
|
|
175
|
+
return {
|
|
176
|
+
scopeType: input.policy.scopeType,
|
|
177
|
+
scopeId: input.policy.scopeId,
|
|
178
|
+
scopeName: input.scopeName,
|
|
179
|
+
metric: input.policy.metric,
|
|
180
|
+
windowKind: input.policy.windowKind,
|
|
181
|
+
thresholdType: input.thresholdType,
|
|
182
|
+
budgetAmount: input.policy.amount,
|
|
183
|
+
observedAmount: input.amountObserved,
|
|
184
|
+
warnPercent: input.policy.warnPercent,
|
|
185
|
+
windowStart: input.windowStart.toISOString(),
|
|
186
|
+
windowEnd: input.windowEnd.toISOString(),
|
|
187
|
+
policyId: input.policy.id,
|
|
188
|
+
guidance: "Raise the budget and resume the scope, or keep the scope paused.",
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function markApprovalStatus(
|
|
193
|
+
db: Db,
|
|
194
|
+
approvalId: string | null,
|
|
195
|
+
status: "approved" | "rejected",
|
|
196
|
+
decisionNote: string | null | undefined,
|
|
197
|
+
decidedByUserId: string,
|
|
198
|
+
) {
|
|
199
|
+
if (!approvalId) return;
|
|
200
|
+
await db
|
|
201
|
+
.update(approvals)
|
|
202
|
+
.set({
|
|
203
|
+
status,
|
|
204
|
+
decisionNote: decisionNote ?? null,
|
|
205
|
+
decidedByUserId,
|
|
206
|
+
decidedAt: new Date(),
|
|
207
|
+
updatedAt: new Date(),
|
|
208
|
+
})
|
|
209
|
+
.where(eq(approvals.id, approvalId));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {
|
|
213
|
+
async function pauseScopeForBudget(policy: PolicyRow) {
|
|
214
|
+
const now = new Date();
|
|
215
|
+
if (policy.scopeType === "agent") {
|
|
216
|
+
await db
|
|
217
|
+
.update(agents)
|
|
218
|
+
.set({
|
|
219
|
+
status: "paused",
|
|
220
|
+
pauseReason: "budget",
|
|
221
|
+
pausedAt: now,
|
|
222
|
+
updatedAt: now,
|
|
223
|
+
})
|
|
224
|
+
.where(and(eq(agents.id, policy.scopeId), inArray(agents.status, ["active", "idle", "running", "error"])));
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (policy.scopeType === "project") {
|
|
229
|
+
await db
|
|
230
|
+
.update(projects)
|
|
231
|
+
.set({
|
|
232
|
+
pauseReason: "budget",
|
|
233
|
+
pausedAt: now,
|
|
234
|
+
updatedAt: now,
|
|
235
|
+
})
|
|
236
|
+
.where(eq(projects.id, policy.scopeId));
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
await db
|
|
241
|
+
.update(companies)
|
|
242
|
+
.set({
|
|
243
|
+
status: "paused",
|
|
244
|
+
pauseReason: "budget",
|
|
245
|
+
pausedAt: now,
|
|
246
|
+
updatedAt: now,
|
|
247
|
+
})
|
|
248
|
+
.where(eq(companies.id, policy.scopeId));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function pauseAndCancelScopeForBudget(policy: PolicyRow) {
|
|
252
|
+
await pauseScopeForBudget(policy);
|
|
253
|
+
await hooks.cancelWorkForScope?.({
|
|
254
|
+
companyId: policy.companyId,
|
|
255
|
+
scopeType: policy.scopeType as BudgetScopeType,
|
|
256
|
+
scopeId: policy.scopeId,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function resumeScopeFromBudget(policy: PolicyRow) {
|
|
261
|
+
const now = new Date();
|
|
262
|
+
if (policy.scopeType === "agent") {
|
|
263
|
+
await db
|
|
264
|
+
.update(agents)
|
|
265
|
+
.set({
|
|
266
|
+
status: "idle",
|
|
267
|
+
pauseReason: null,
|
|
268
|
+
pausedAt: null,
|
|
269
|
+
updatedAt: now,
|
|
270
|
+
})
|
|
271
|
+
.where(and(eq(agents.id, policy.scopeId), eq(agents.pauseReason, "budget")));
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (policy.scopeType === "project") {
|
|
276
|
+
await db
|
|
277
|
+
.update(projects)
|
|
278
|
+
.set({
|
|
279
|
+
pauseReason: null,
|
|
280
|
+
pausedAt: null,
|
|
281
|
+
updatedAt: now,
|
|
282
|
+
})
|
|
283
|
+
.where(and(eq(projects.id, policy.scopeId), eq(projects.pauseReason, "budget")));
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
await db
|
|
288
|
+
.update(companies)
|
|
289
|
+
.set({
|
|
290
|
+
status: "active",
|
|
291
|
+
pauseReason: null,
|
|
292
|
+
pausedAt: null,
|
|
293
|
+
updatedAt: now,
|
|
294
|
+
})
|
|
295
|
+
.where(and(eq(companies.id, policy.scopeId), eq(companies.pauseReason, "budget")));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function getPolicyRow(policyId: string) {
|
|
299
|
+
const policy = await db
|
|
300
|
+
.select()
|
|
301
|
+
.from(budgetPolicies)
|
|
302
|
+
.where(eq(budgetPolicies.id, policyId))
|
|
303
|
+
.then((rows) => rows[0] ?? null);
|
|
304
|
+
if (!policy) throw notFound("Budget policy not found");
|
|
305
|
+
return policy;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function listPolicyRows(companyId: string) {
|
|
309
|
+
return db
|
|
310
|
+
.select()
|
|
311
|
+
.from(budgetPolicies)
|
|
312
|
+
.where(eq(budgetPolicies.companyId, companyId))
|
|
313
|
+
.orderBy(desc(budgetPolicies.updatedAt));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function buildPolicySummary(policy: PolicyRow): Promise<BudgetPolicySummary> {
|
|
317
|
+
const scope = await resolveScopeRecord(db, policy.scopeType as BudgetScopeType, policy.scopeId);
|
|
318
|
+
const observedAmount = await computeObservedAmount(db, policy);
|
|
319
|
+
const { start, end } = resolveWindow(policy.windowKind as BudgetWindowKind);
|
|
320
|
+
const amount = policy.isActive ? policy.amount : 0;
|
|
321
|
+
const utilizationPercent =
|
|
322
|
+
amount > 0 ? Number(((observedAmount / amount) * 100).toFixed(2)) : 0;
|
|
323
|
+
return {
|
|
324
|
+
policyId: policy.id,
|
|
325
|
+
companyId: policy.companyId,
|
|
326
|
+
scopeType: policy.scopeType as BudgetScopeType,
|
|
327
|
+
scopeId: policy.scopeId,
|
|
328
|
+
scopeName: normalizeScopeName(policy.scopeType as BudgetScopeType, scope.name),
|
|
329
|
+
metric: policy.metric as BudgetMetric,
|
|
330
|
+
windowKind: policy.windowKind as BudgetWindowKind,
|
|
331
|
+
amount,
|
|
332
|
+
observedAmount,
|
|
333
|
+
remainingAmount: amount > 0 ? Math.max(0, amount - observedAmount) : 0,
|
|
334
|
+
utilizationPercent,
|
|
335
|
+
warnPercent: policy.warnPercent,
|
|
336
|
+
hardStopEnabled: policy.hardStopEnabled,
|
|
337
|
+
notifyEnabled: policy.notifyEnabled,
|
|
338
|
+
isActive: policy.isActive,
|
|
339
|
+
status: policy.isActive
|
|
340
|
+
? budgetStatusFromObserved(observedAmount, amount, policy.warnPercent)
|
|
341
|
+
: "ok",
|
|
342
|
+
paused: scope.paused,
|
|
343
|
+
pauseReason: scope.pauseReason,
|
|
344
|
+
windowStart: start,
|
|
345
|
+
windowEnd: end,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function createIncidentIfNeeded(
|
|
350
|
+
policy: PolicyRow,
|
|
351
|
+
thresholdType: BudgetThresholdType,
|
|
352
|
+
amountObserved: number,
|
|
353
|
+
) {
|
|
354
|
+
const { start, end } = resolveWindow(policy.windowKind as BudgetWindowKind);
|
|
355
|
+
const existing = await db
|
|
356
|
+
.select()
|
|
357
|
+
.from(budgetIncidents)
|
|
358
|
+
.where(
|
|
359
|
+
and(
|
|
360
|
+
eq(budgetIncidents.policyId, policy.id),
|
|
361
|
+
eq(budgetIncidents.windowStart, start),
|
|
362
|
+
eq(budgetIncidents.thresholdType, thresholdType),
|
|
363
|
+
ne(budgetIncidents.status, "dismissed"),
|
|
364
|
+
),
|
|
365
|
+
)
|
|
366
|
+
.then((rows) => rows[0] ?? null);
|
|
367
|
+
if (existing) return existing;
|
|
368
|
+
|
|
369
|
+
const scope = await resolveScopeRecord(db, policy.scopeType as BudgetScopeType, policy.scopeId);
|
|
370
|
+
const payload = buildApprovalPayload({
|
|
371
|
+
policy,
|
|
372
|
+
scopeName: normalizeScopeName(policy.scopeType as BudgetScopeType, scope.name),
|
|
373
|
+
thresholdType,
|
|
374
|
+
amountObserved,
|
|
375
|
+
windowStart: start,
|
|
376
|
+
windowEnd: end,
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
const approval = thresholdType === "hard"
|
|
380
|
+
? await db
|
|
381
|
+
.insert(approvals)
|
|
382
|
+
.values({
|
|
383
|
+
companyId: policy.companyId,
|
|
384
|
+
type: "budget_override_required",
|
|
385
|
+
requestedByUserId: null,
|
|
386
|
+
requestedByAgentId: null,
|
|
387
|
+
status: "pending",
|
|
388
|
+
payload,
|
|
389
|
+
})
|
|
390
|
+
.returning()
|
|
391
|
+
.then((rows) => rows[0] ?? null)
|
|
392
|
+
: null;
|
|
393
|
+
|
|
394
|
+
return db
|
|
395
|
+
.insert(budgetIncidents)
|
|
396
|
+
.values({
|
|
397
|
+
companyId: policy.companyId,
|
|
398
|
+
policyId: policy.id,
|
|
399
|
+
scopeType: policy.scopeType,
|
|
400
|
+
scopeId: policy.scopeId,
|
|
401
|
+
metric: policy.metric,
|
|
402
|
+
windowKind: policy.windowKind,
|
|
403
|
+
windowStart: start,
|
|
404
|
+
windowEnd: end,
|
|
405
|
+
thresholdType,
|
|
406
|
+
amountLimit: policy.amount,
|
|
407
|
+
amountObserved,
|
|
408
|
+
status: "open",
|
|
409
|
+
approvalId: approval?.id ?? null,
|
|
410
|
+
})
|
|
411
|
+
.returning()
|
|
412
|
+
.then((rows) => rows[0] ?? null);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function resolveOpenSoftIncidents(policyId: string) {
|
|
416
|
+
await db
|
|
417
|
+
.update(budgetIncidents)
|
|
418
|
+
.set({
|
|
419
|
+
status: "resolved",
|
|
420
|
+
resolvedAt: new Date(),
|
|
421
|
+
updatedAt: new Date(),
|
|
422
|
+
})
|
|
423
|
+
.where(
|
|
424
|
+
and(
|
|
425
|
+
eq(budgetIncidents.policyId, policyId),
|
|
426
|
+
eq(budgetIncidents.thresholdType, "soft"),
|
|
427
|
+
eq(budgetIncidents.status, "open"),
|
|
428
|
+
),
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function resolveOpenIncidentsForPolicy(
|
|
433
|
+
policyId: string,
|
|
434
|
+
approvalStatus: "approved" | "rejected" | null,
|
|
435
|
+
decidedByUserId: string | null,
|
|
436
|
+
) {
|
|
437
|
+
const openRows = await db
|
|
438
|
+
.select()
|
|
439
|
+
.from(budgetIncidents)
|
|
440
|
+
.where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open")));
|
|
441
|
+
|
|
442
|
+
await db
|
|
443
|
+
.update(budgetIncidents)
|
|
444
|
+
.set({
|
|
445
|
+
status: "resolved",
|
|
446
|
+
resolvedAt: new Date(),
|
|
447
|
+
updatedAt: new Date(),
|
|
448
|
+
})
|
|
449
|
+
.where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open")));
|
|
450
|
+
|
|
451
|
+
if (!approvalStatus || !decidedByUserId) return;
|
|
452
|
+
for (const row of openRows) {
|
|
453
|
+
await markApprovalStatus(db, row.approvalId ?? null, approvalStatus, "Resolved via budget update", decidedByUserId);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async function hydrateIncidentRows(rows: IncidentRow[]): Promise<BudgetIncident[]> {
|
|
458
|
+
const approvalIds = rows.map((row) => row.approvalId).filter((value): value is string => Boolean(value));
|
|
459
|
+
const approvalRows = approvalIds.length > 0
|
|
460
|
+
? await db
|
|
461
|
+
.select({ id: approvals.id, status: approvals.status })
|
|
462
|
+
.from(approvals)
|
|
463
|
+
.where(inArray(approvals.id, approvalIds))
|
|
464
|
+
: [];
|
|
465
|
+
const approvalStatusById = new Map(approvalRows.map((row) => [row.id, row.status]));
|
|
466
|
+
|
|
467
|
+
return Promise.all(
|
|
468
|
+
rows.map(async (row) => {
|
|
469
|
+
const scope = await resolveScopeRecord(db, row.scopeType as BudgetScopeType, row.scopeId);
|
|
470
|
+
return {
|
|
471
|
+
id: row.id,
|
|
472
|
+
companyId: row.companyId,
|
|
473
|
+
policyId: row.policyId,
|
|
474
|
+
scopeType: row.scopeType as BudgetScopeType,
|
|
475
|
+
scopeId: row.scopeId,
|
|
476
|
+
scopeName: normalizeScopeName(row.scopeType as BudgetScopeType, scope.name),
|
|
477
|
+
metric: row.metric as BudgetMetric,
|
|
478
|
+
windowKind: row.windowKind as BudgetWindowKind,
|
|
479
|
+
windowStart: row.windowStart,
|
|
480
|
+
windowEnd: row.windowEnd,
|
|
481
|
+
thresholdType: row.thresholdType as BudgetThresholdType,
|
|
482
|
+
amountLimit: row.amountLimit,
|
|
483
|
+
amountObserved: row.amountObserved,
|
|
484
|
+
status: row.status as BudgetIncident["status"],
|
|
485
|
+
approvalId: row.approvalId ?? null,
|
|
486
|
+
approvalStatus: row.approvalId ? approvalStatusById.get(row.approvalId) ?? null : null,
|
|
487
|
+
resolvedAt: row.resolvedAt ?? null,
|
|
488
|
+
createdAt: row.createdAt,
|
|
489
|
+
updatedAt: row.updatedAt,
|
|
490
|
+
};
|
|
491
|
+
}),
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
return {
|
|
496
|
+
listPolicies: async (companyId: string): Promise<BudgetPolicy[]> => {
|
|
497
|
+
const rows = await listPolicyRows(companyId);
|
|
498
|
+
return rows.map((row) => ({
|
|
499
|
+
...row,
|
|
500
|
+
scopeType: row.scopeType as BudgetScopeType,
|
|
501
|
+
metric: row.metric as BudgetMetric,
|
|
502
|
+
windowKind: row.windowKind as BudgetWindowKind,
|
|
503
|
+
}));
|
|
504
|
+
},
|
|
505
|
+
|
|
506
|
+
upsertPolicy: async (
|
|
507
|
+
companyId: string,
|
|
508
|
+
input: BudgetPolicyUpsertInput,
|
|
509
|
+
actorUserId: string | null,
|
|
510
|
+
): Promise<BudgetPolicySummary> => {
|
|
511
|
+
const scope = await resolveScopeRecord(db, input.scopeType, input.scopeId);
|
|
512
|
+
if (scope.companyId !== companyId) {
|
|
513
|
+
throw unprocessable("Budget scope does not belong to company");
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const metric = input.metric ?? "billed_cents";
|
|
517
|
+
const windowKind = input.windowKind ?? (input.scopeType === "project" ? "lifetime" : "calendar_month_utc");
|
|
518
|
+
const amount = Math.max(0, Math.floor(input.amount));
|
|
519
|
+
const nextIsActive = amount > 0 && (input.isActive ?? true);
|
|
520
|
+
const existing = await db
|
|
521
|
+
.select()
|
|
522
|
+
.from(budgetPolicies)
|
|
523
|
+
.where(
|
|
524
|
+
and(
|
|
525
|
+
eq(budgetPolicies.companyId, companyId),
|
|
526
|
+
eq(budgetPolicies.scopeType, input.scopeType),
|
|
527
|
+
eq(budgetPolicies.scopeId, input.scopeId),
|
|
528
|
+
eq(budgetPolicies.metric, metric),
|
|
529
|
+
eq(budgetPolicies.windowKind, windowKind),
|
|
530
|
+
),
|
|
531
|
+
)
|
|
532
|
+
.then((rows) => rows[0] ?? null);
|
|
533
|
+
|
|
534
|
+
const now = new Date();
|
|
535
|
+
const row = existing
|
|
536
|
+
? await db
|
|
537
|
+
.update(budgetPolicies)
|
|
538
|
+
.set({
|
|
539
|
+
amount,
|
|
540
|
+
warnPercent: input.warnPercent ?? existing.warnPercent,
|
|
541
|
+
hardStopEnabled: input.hardStopEnabled ?? existing.hardStopEnabled,
|
|
542
|
+
notifyEnabled: input.notifyEnabled ?? existing.notifyEnabled,
|
|
543
|
+
isActive: nextIsActive,
|
|
544
|
+
updatedByUserId: actorUserId,
|
|
545
|
+
updatedAt: now,
|
|
546
|
+
})
|
|
547
|
+
.where(eq(budgetPolicies.id, existing.id))
|
|
548
|
+
.returning()
|
|
549
|
+
.then((rows) => rows[0])
|
|
550
|
+
: await db
|
|
551
|
+
.insert(budgetPolicies)
|
|
552
|
+
.values({
|
|
553
|
+
companyId,
|
|
554
|
+
scopeType: input.scopeType,
|
|
555
|
+
scopeId: input.scopeId,
|
|
556
|
+
metric,
|
|
557
|
+
windowKind,
|
|
558
|
+
amount,
|
|
559
|
+
warnPercent: input.warnPercent ?? 80,
|
|
560
|
+
hardStopEnabled: input.hardStopEnabled ?? true,
|
|
561
|
+
notifyEnabled: input.notifyEnabled ?? true,
|
|
562
|
+
isActive: nextIsActive,
|
|
563
|
+
createdByUserId: actorUserId,
|
|
564
|
+
updatedByUserId: actorUserId,
|
|
565
|
+
})
|
|
566
|
+
.returning()
|
|
567
|
+
.then((rows) => rows[0]);
|
|
568
|
+
|
|
569
|
+
if (input.scopeType === "company" && windowKind === "calendar_month_utc") {
|
|
570
|
+
await db
|
|
571
|
+
.update(companies)
|
|
572
|
+
.set({
|
|
573
|
+
budgetMonthlyCents: amount,
|
|
574
|
+
updatedAt: now,
|
|
575
|
+
})
|
|
576
|
+
.where(eq(companies.id, input.scopeId));
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (input.scopeType === "agent" && windowKind === "calendar_month_utc") {
|
|
580
|
+
await db
|
|
581
|
+
.update(agents)
|
|
582
|
+
.set({
|
|
583
|
+
budgetMonthlyCents: amount,
|
|
584
|
+
updatedAt: now,
|
|
585
|
+
})
|
|
586
|
+
.where(eq(agents.id, input.scopeId));
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
if (amount > 0) {
|
|
590
|
+
const observedAmount = await computeObservedAmount(db, row);
|
|
591
|
+
if (observedAmount < amount) {
|
|
592
|
+
await resumeScopeFromBudget(row);
|
|
593
|
+
await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId);
|
|
594
|
+
} else {
|
|
595
|
+
const softThreshold = Math.ceil((row.amount * row.warnPercent) / 100);
|
|
596
|
+
if (row.notifyEnabled && observedAmount >= softThreshold) {
|
|
597
|
+
await createIncidentIfNeeded(row, "soft", observedAmount);
|
|
598
|
+
}
|
|
599
|
+
if (row.hardStopEnabled && observedAmount >= row.amount) {
|
|
600
|
+
await resolveOpenSoftIncidents(row.id);
|
|
601
|
+
await createIncidentIfNeeded(row, "hard", observedAmount);
|
|
602
|
+
await pauseAndCancelScopeForBudget(row);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
} else {
|
|
606
|
+
await resumeScopeFromBudget(row);
|
|
607
|
+
await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
await logActivity(db, {
|
|
611
|
+
companyId,
|
|
612
|
+
actorType: "user",
|
|
613
|
+
actorId: actorUserId ?? "board",
|
|
614
|
+
action: "budget.policy_upserted",
|
|
615
|
+
entityType: "budget_policy",
|
|
616
|
+
entityId: row.id,
|
|
617
|
+
details: {
|
|
618
|
+
scopeType: row.scopeType,
|
|
619
|
+
scopeId: row.scopeId,
|
|
620
|
+
amount: row.amount,
|
|
621
|
+
windowKind: row.windowKind,
|
|
622
|
+
},
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
return buildPolicySummary(row);
|
|
626
|
+
},
|
|
627
|
+
|
|
628
|
+
overview: async (companyId: string): Promise<BudgetOverview> => {
|
|
629
|
+
const rows = await listPolicyRows(companyId);
|
|
630
|
+
const policies = await Promise.all(rows.map((row) => buildPolicySummary(row)));
|
|
631
|
+
const activeIncidentRows = await db
|
|
632
|
+
.select()
|
|
633
|
+
.from(budgetIncidents)
|
|
634
|
+
.where(and(eq(budgetIncidents.companyId, companyId), eq(budgetIncidents.status, "open")))
|
|
635
|
+
.orderBy(desc(budgetIncidents.createdAt));
|
|
636
|
+
const activeIncidents = await hydrateIncidentRows(activeIncidentRows);
|
|
637
|
+
return {
|
|
638
|
+
companyId,
|
|
639
|
+
policies,
|
|
640
|
+
activeIncidents,
|
|
641
|
+
pausedAgentCount: policies.filter((policy) => policy.scopeType === "agent" && policy.paused).length,
|
|
642
|
+
pausedProjectCount: policies.filter((policy) => policy.scopeType === "project" && policy.paused).length,
|
|
643
|
+
pendingApprovalCount: activeIncidents.filter((incident) => incident.approvalStatus === "pending").length,
|
|
644
|
+
};
|
|
645
|
+
},
|
|
646
|
+
|
|
647
|
+
evaluateCostEvent: async (event: typeof costEvents.$inferSelect) => {
|
|
648
|
+
const candidatePolicies = await db
|
|
649
|
+
.select()
|
|
650
|
+
.from(budgetPolicies)
|
|
651
|
+
.where(
|
|
652
|
+
and(
|
|
653
|
+
eq(budgetPolicies.companyId, event.companyId),
|
|
654
|
+
eq(budgetPolicies.isActive, true),
|
|
655
|
+
inArray(budgetPolicies.scopeType, ["company", "agent", "project"]),
|
|
656
|
+
),
|
|
657
|
+
);
|
|
658
|
+
|
|
659
|
+
const relevantPolicies = candidatePolicies.filter((policy) => {
|
|
660
|
+
if (policy.scopeType === "company") return policy.scopeId === event.companyId;
|
|
661
|
+
if (policy.scopeType === "agent") return policy.scopeId === event.agentId;
|
|
662
|
+
if (policy.scopeType === "project") return Boolean(event.projectId) && policy.scopeId === event.projectId;
|
|
663
|
+
return false;
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
for (const policy of relevantPolicies) {
|
|
667
|
+
if (policy.metric !== "billed_cents" || policy.amount <= 0) continue;
|
|
668
|
+
const observedAmount = await computeObservedAmount(db, policy);
|
|
669
|
+
const softThreshold = Math.ceil((policy.amount * policy.warnPercent) / 100);
|
|
670
|
+
|
|
671
|
+
if (policy.notifyEnabled && observedAmount >= softThreshold) {
|
|
672
|
+
const softIncident = await createIncidentIfNeeded(policy, "soft", observedAmount);
|
|
673
|
+
if (softIncident) {
|
|
674
|
+
await logActivity(db, {
|
|
675
|
+
companyId: policy.companyId,
|
|
676
|
+
actorType: "system",
|
|
677
|
+
actorId: "budget_service",
|
|
678
|
+
action: "budget.soft_threshold_crossed",
|
|
679
|
+
entityType: "budget_incident",
|
|
680
|
+
entityId: softIncident.id,
|
|
681
|
+
details: {
|
|
682
|
+
scopeType: policy.scopeType,
|
|
683
|
+
scopeId: policy.scopeId,
|
|
684
|
+
amountObserved: observedAmount,
|
|
685
|
+
amountLimit: policy.amount,
|
|
686
|
+
},
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
if (policy.hardStopEnabled && observedAmount >= policy.amount) {
|
|
692
|
+
await resolveOpenSoftIncidents(policy.id);
|
|
693
|
+
const hardIncident = await createIncidentIfNeeded(policy, "hard", observedAmount);
|
|
694
|
+
await pauseAndCancelScopeForBudget(policy);
|
|
695
|
+
if (hardIncident) {
|
|
696
|
+
await logActivity(db, {
|
|
697
|
+
companyId: policy.companyId,
|
|
698
|
+
actorType: "system",
|
|
699
|
+
actorId: "budget_service",
|
|
700
|
+
action: "budget.hard_threshold_crossed",
|
|
701
|
+
entityType: "budget_incident",
|
|
702
|
+
entityId: hardIncident.id,
|
|
703
|
+
details: {
|
|
704
|
+
scopeType: policy.scopeType,
|
|
705
|
+
scopeId: policy.scopeId,
|
|
706
|
+
amountObserved: observedAmount,
|
|
707
|
+
amountLimit: policy.amount,
|
|
708
|
+
approvalId: hardIncident.approvalId ?? null,
|
|
709
|
+
},
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
},
|
|
715
|
+
|
|
716
|
+
getInvocationBlock: async (
|
|
717
|
+
companyId: string,
|
|
718
|
+
agentId: string,
|
|
719
|
+
context?: { issueId?: string | null; projectId?: string | null },
|
|
720
|
+
) => {
|
|
721
|
+
const agent = await db
|
|
722
|
+
.select({
|
|
723
|
+
status: agents.status,
|
|
724
|
+
pauseReason: agents.pauseReason,
|
|
725
|
+
companyId: agents.companyId,
|
|
726
|
+
name: agents.name,
|
|
727
|
+
})
|
|
728
|
+
.from(agents)
|
|
729
|
+
.where(eq(agents.id, agentId))
|
|
730
|
+
.then((rows) => rows[0] ?? null);
|
|
731
|
+
if (!agent || agent.companyId !== companyId) throw notFound("Agent not found");
|
|
732
|
+
|
|
733
|
+
const company = await db
|
|
734
|
+
.select({
|
|
735
|
+
status: companies.status,
|
|
736
|
+
pauseReason: companies.pauseReason,
|
|
737
|
+
name: companies.name,
|
|
738
|
+
})
|
|
739
|
+
.from(companies)
|
|
740
|
+
.where(eq(companies.id, companyId))
|
|
741
|
+
.then((rows) => rows[0] ?? null);
|
|
742
|
+
if (!company) throw notFound("Company not found");
|
|
743
|
+
if (company.status === "paused") {
|
|
744
|
+
return {
|
|
745
|
+
scopeType: "company" as const,
|
|
746
|
+
scopeId: companyId,
|
|
747
|
+
scopeName: company.name,
|
|
748
|
+
reason:
|
|
749
|
+
company.pauseReason === "budget"
|
|
750
|
+
? "Company is paused because its budget hard-stop was reached."
|
|
751
|
+
: "Company is paused and cannot start new work.",
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const companyPolicy = await db
|
|
756
|
+
.select()
|
|
757
|
+
.from(budgetPolicies)
|
|
758
|
+
.where(
|
|
759
|
+
and(
|
|
760
|
+
eq(budgetPolicies.companyId, companyId),
|
|
761
|
+
eq(budgetPolicies.scopeType, "company"),
|
|
762
|
+
eq(budgetPolicies.scopeId, companyId),
|
|
763
|
+
eq(budgetPolicies.isActive, true),
|
|
764
|
+
eq(budgetPolicies.metric, "billed_cents"),
|
|
765
|
+
),
|
|
766
|
+
)
|
|
767
|
+
.then((rows) => rows[0] ?? null);
|
|
768
|
+
if (companyPolicy && companyPolicy.hardStopEnabled && companyPolicy.amount > 0) {
|
|
769
|
+
const observed = await computeObservedAmount(db, companyPolicy);
|
|
770
|
+
if (observed >= companyPolicy.amount) {
|
|
771
|
+
return {
|
|
772
|
+
scopeType: "company" as const,
|
|
773
|
+
scopeId: companyId,
|
|
774
|
+
scopeName: company.name,
|
|
775
|
+
reason: "Company cannot start new work because its budget hard-stop is exceeded.",
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
if (agent.status === "paused" && agent.pauseReason === "budget") {
|
|
781
|
+
return {
|
|
782
|
+
scopeType: "agent" as const,
|
|
783
|
+
scopeId: agentId,
|
|
784
|
+
scopeName: agent.name,
|
|
785
|
+
reason: "Agent is paused because its budget hard-stop was reached.",
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const agentPolicy = await db
|
|
790
|
+
.select()
|
|
791
|
+
.from(budgetPolicies)
|
|
792
|
+
.where(
|
|
793
|
+
and(
|
|
794
|
+
eq(budgetPolicies.companyId, companyId),
|
|
795
|
+
eq(budgetPolicies.scopeType, "agent"),
|
|
796
|
+
eq(budgetPolicies.scopeId, agentId),
|
|
797
|
+
eq(budgetPolicies.isActive, true),
|
|
798
|
+
eq(budgetPolicies.metric, "billed_cents"),
|
|
799
|
+
),
|
|
800
|
+
)
|
|
801
|
+
.then((rows) => rows[0] ?? null);
|
|
802
|
+
if (agentPolicy && agentPolicy.hardStopEnabled && agentPolicy.amount > 0) {
|
|
803
|
+
const observed = await computeObservedAmount(db, agentPolicy);
|
|
804
|
+
if (observed >= agentPolicy.amount) {
|
|
805
|
+
return {
|
|
806
|
+
scopeType: "agent" as const,
|
|
807
|
+
scopeId: agentId,
|
|
808
|
+
scopeName: agent.name,
|
|
809
|
+
reason: "Agent cannot start because its budget hard-stop is still exceeded.",
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
const candidateProjectId = context?.projectId ?? null;
|
|
815
|
+
if (!candidateProjectId) return null;
|
|
816
|
+
|
|
817
|
+
const project = await db
|
|
818
|
+
.select({
|
|
819
|
+
id: projects.id,
|
|
820
|
+
name: projects.name,
|
|
821
|
+
companyId: projects.companyId,
|
|
822
|
+
pauseReason: projects.pauseReason,
|
|
823
|
+
pausedAt: projects.pausedAt,
|
|
824
|
+
})
|
|
825
|
+
.from(projects)
|
|
826
|
+
.where(eq(projects.id, candidateProjectId))
|
|
827
|
+
.then((rows) => rows[0] ?? null);
|
|
828
|
+
|
|
829
|
+
if (!project || project.companyId !== companyId) return null;
|
|
830
|
+
const projectPolicy = await db
|
|
831
|
+
.select()
|
|
832
|
+
.from(budgetPolicies)
|
|
833
|
+
.where(
|
|
834
|
+
and(
|
|
835
|
+
eq(budgetPolicies.companyId, companyId),
|
|
836
|
+
eq(budgetPolicies.scopeType, "project"),
|
|
837
|
+
eq(budgetPolicies.scopeId, project.id),
|
|
838
|
+
eq(budgetPolicies.isActive, true),
|
|
839
|
+
eq(budgetPolicies.metric, "billed_cents"),
|
|
840
|
+
),
|
|
841
|
+
)
|
|
842
|
+
.then((rows) => rows[0] ?? null);
|
|
843
|
+
if (projectPolicy && projectPolicy.hardStopEnabled && projectPolicy.amount > 0) {
|
|
844
|
+
const observed = await computeObservedAmount(db, projectPolicy);
|
|
845
|
+
if (observed >= projectPolicy.amount) {
|
|
846
|
+
return {
|
|
847
|
+
scopeType: "project" as const,
|
|
848
|
+
scopeId: project.id,
|
|
849
|
+
scopeName: project.name,
|
|
850
|
+
reason: "Project cannot start work because its budget hard-stop is still exceeded.",
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
if (!project.pausedAt || project.pauseReason !== "budget") return null;
|
|
856
|
+
return {
|
|
857
|
+
scopeType: "project" as const,
|
|
858
|
+
scopeId: project.id,
|
|
859
|
+
scopeName: project.name,
|
|
860
|
+
reason: "Project is paused because its budget hard-stop was reached.",
|
|
861
|
+
};
|
|
862
|
+
},
|
|
863
|
+
|
|
864
|
+
resolveIncident: async (
|
|
865
|
+
companyId: string,
|
|
866
|
+
incidentId: string,
|
|
867
|
+
input: BudgetIncidentResolutionInput,
|
|
868
|
+
actorUserId: string,
|
|
869
|
+
): Promise<BudgetIncident> => {
|
|
870
|
+
const incident = await db
|
|
871
|
+
.select()
|
|
872
|
+
.from(budgetIncidents)
|
|
873
|
+
.where(eq(budgetIncidents.id, incidentId))
|
|
874
|
+
.then((rows) => rows[0] ?? null);
|
|
875
|
+
if (!incident) throw notFound("Budget incident not found");
|
|
876
|
+
if (incident.companyId !== companyId) throw notFound("Budget incident not found");
|
|
877
|
+
|
|
878
|
+
const policy = await getPolicyRow(incident.policyId);
|
|
879
|
+
if (input.action === "raise_budget_and_resume") {
|
|
880
|
+
const nextAmount = Math.max(0, Math.floor(input.amount ?? 0));
|
|
881
|
+
const currentObserved = await computeObservedAmount(db, policy);
|
|
882
|
+
if (nextAmount <= currentObserved) {
|
|
883
|
+
throw unprocessable("New budget must exceed current observed spend");
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const now = new Date();
|
|
887
|
+
await db
|
|
888
|
+
.update(budgetPolicies)
|
|
889
|
+
.set({
|
|
890
|
+
amount: nextAmount,
|
|
891
|
+
isActive: true,
|
|
892
|
+
updatedByUserId: actorUserId,
|
|
893
|
+
updatedAt: now,
|
|
894
|
+
})
|
|
895
|
+
.where(eq(budgetPolicies.id, policy.id));
|
|
896
|
+
|
|
897
|
+
if (policy.scopeType === "company" && policy.windowKind === "calendar_month_utc") {
|
|
898
|
+
await db
|
|
899
|
+
.update(companies)
|
|
900
|
+
.set({ budgetMonthlyCents: nextAmount, updatedAt: now })
|
|
901
|
+
.where(eq(companies.id, policy.scopeId));
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
if (policy.scopeType === "agent" && policy.windowKind === "calendar_month_utc") {
|
|
905
|
+
await db
|
|
906
|
+
.update(agents)
|
|
907
|
+
.set({ budgetMonthlyCents: nextAmount, updatedAt: now })
|
|
908
|
+
.where(eq(agents.id, policy.scopeId));
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
await resumeScopeFromBudget(policy);
|
|
912
|
+
await db
|
|
913
|
+
.update(budgetIncidents)
|
|
914
|
+
.set({
|
|
915
|
+
status: "resolved",
|
|
916
|
+
resolvedAt: now,
|
|
917
|
+
updatedAt: now,
|
|
918
|
+
})
|
|
919
|
+
.where(and(eq(budgetIncidents.policyId, policy.id), eq(budgetIncidents.status, "open")));
|
|
920
|
+
|
|
921
|
+
await markApprovalStatus(db, incident.approvalId ?? null, "approved", input.decisionNote, actorUserId);
|
|
922
|
+
} else {
|
|
923
|
+
await db
|
|
924
|
+
.update(budgetIncidents)
|
|
925
|
+
.set({
|
|
926
|
+
status: "dismissed",
|
|
927
|
+
resolvedAt: new Date(),
|
|
928
|
+
updatedAt: new Date(),
|
|
929
|
+
})
|
|
930
|
+
.where(eq(budgetIncidents.id, incident.id));
|
|
931
|
+
await markApprovalStatus(db, incident.approvalId ?? null, "rejected", input.decisionNote, actorUserId);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
await logActivity(db, {
|
|
935
|
+
companyId: incident.companyId,
|
|
936
|
+
actorType: "user",
|
|
937
|
+
actorId: actorUserId,
|
|
938
|
+
action: "budget.incident_resolved",
|
|
939
|
+
entityType: "budget_incident",
|
|
940
|
+
entityId: incident.id,
|
|
941
|
+
details: {
|
|
942
|
+
action: input.action,
|
|
943
|
+
amount: input.amount ?? null,
|
|
944
|
+
scopeType: incident.scopeType,
|
|
945
|
+
scopeId: incident.scopeId,
|
|
946
|
+
},
|
|
947
|
+
});
|
|
948
|
+
|
|
949
|
+
const [updated] = await hydrateIncidentRows([{
|
|
950
|
+
...incident,
|
|
951
|
+
status: input.action === "raise_budget_and_resume" ? "resolved" : "dismissed",
|
|
952
|
+
resolvedAt: new Date(),
|
|
953
|
+
updatedAt: new Date(),
|
|
954
|
+
}]);
|
|
955
|
+
return updated!;
|
|
956
|
+
},
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
|