stagent 0.1.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 +191 -0
- package/README.md +399 -0
- package/components.json +21 -0
- package/dist/cli.js +171 -0
- package/drizzle.config.ts +12 -0
- package/next.config.mjs +15 -0
- package/package.json +114 -0
- package/postcss.config.mjs +8 -0
- package/public/icon-512.png +0 -0
- package/public/icon.svg +13 -0
- package/public/readme/home-workspace.png +0 -0
- package/public/readme/inbox-approvals.png +0 -0
- package/public/readme/workflow-blueprints.png +0 -0
- package/public/stagent-s-128.png +0 -0
- package/public/stagent-s-64.png +0 -0
- package/src/app/api/blueprints/[id]/instantiate/route.ts +27 -0
- package/src/app/api/blueprints/[id]/route.ts +39 -0
- package/src/app/api/blueprints/import/route.ts +68 -0
- package/src/app/api/blueprints/route.ts +29 -0
- package/src/app/api/command-palette/recent/route.ts +31 -0
- package/src/app/api/data/clear/route.ts +22 -0
- package/src/app/api/data/seed/route.ts +22 -0
- package/src/app/api/documents/[id]/file/route.ts +44 -0
- package/src/app/api/documents/[id]/route.ts +123 -0
- package/src/app/api/documents/route.ts +59 -0
- package/src/app/api/logs/stream/route.ts +101 -0
- package/src/app/api/notifications/[id]/route.ts +36 -0
- package/src/app/api/notifications/mark-all-read/route.ts +13 -0
- package/src/app/api/notifications/pending-approvals/route.ts +10 -0
- package/src/app/api/notifications/pending-approvals/stream/route.ts +101 -0
- package/src/app/api/notifications/route.ts +34 -0
- package/src/app/api/permissions/route.ts +46 -0
- package/src/app/api/profiles/[id]/route.ts +79 -0
- package/src/app/api/profiles/[id]/test/route.ts +42 -0
- package/src/app/api/profiles/import/route.ts +108 -0
- package/src/app/api/profiles/route.ts +50 -0
- package/src/app/api/projects/[id]/route.ts +72 -0
- package/src/app/api/projects/route.ts +53 -0
- package/src/app/api/schedules/[id]/route.ts +185 -0
- package/src/app/api/schedules/route.ts +117 -0
- package/src/app/api/settings/budgets/route.ts +24 -0
- package/src/app/api/settings/openai/route.ts +24 -0
- package/src/app/api/settings/route.ts +21 -0
- package/src/app/api/settings/test/route.ts +26 -0
- package/src/app/api/tasks/[id]/cancel/route.ts +21 -0
- package/src/app/api/tasks/[id]/execute/route.ts +90 -0
- package/src/app/api/tasks/[id]/logs/route.ts +95 -0
- package/src/app/api/tasks/[id]/output/route.ts +47 -0
- package/src/app/api/tasks/[id]/respond/route.ts +64 -0
- package/src/app/api/tasks/[id]/resume/route.ts +76 -0
- package/src/app/api/tasks/[id]/route.ts +77 -0
- package/src/app/api/tasks/assist/route.ts +35 -0
- package/src/app/api/tasks/route.ts +82 -0
- package/src/app/api/uploads/[id]/route.ts +81 -0
- package/src/app/api/uploads/cleanup/route.ts +7 -0
- package/src/app/api/uploads/route.ts +66 -0
- package/src/app/api/workflows/[id]/execute/route.ts +82 -0
- package/src/app/api/workflows/[id]/route.ts +133 -0
- package/src/app/api/workflows/[id]/status/route.ts +54 -0
- package/src/app/api/workflows/[id]/steps/[stepId]/retry/route.ts +22 -0
- package/src/app/api/workflows/route.ts +61 -0
- package/src/app/apple-icon.tsx +31 -0
- package/src/app/costs/page.tsx +256 -0
- package/src/app/dashboard/page.tsx +44 -0
- package/src/app/documents/[id]/page.tsx +46 -0
- package/src/app/documents/page.tsx +45 -0
- package/src/app/error.tsx +26 -0
- package/src/app/global-error.tsx +23 -0
- package/src/app/globals.css +733 -0
- package/src/app/icon.tsx +30 -0
- package/src/app/inbox/loading.tsx +15 -0
- package/src/app/inbox/page.tsx +35 -0
- package/src/app/layout.tsx +78 -0
- package/src/app/manifest.ts +32 -0
- package/src/app/monitor/page.tsx +37 -0
- package/src/app/page.tsx +162 -0
- package/src/app/profiles/[id]/edit/page.tsx +39 -0
- package/src/app/profiles/[id]/page.tsx +33 -0
- package/src/app/profiles/new/page.tsx +22 -0
- package/src/app/profiles/page.tsx +19 -0
- package/src/app/projects/[id]/page.tsx +134 -0
- package/src/app/projects/loading.tsx +17 -0
- package/src/app/projects/page.tsx +32 -0
- package/src/app/schedules/[id]/page.tsx +47 -0
- package/src/app/schedules/page.tsx +18 -0
- package/src/app/settings/loading.tsx +24 -0
- package/src/app/settings/page.tsx +27 -0
- package/src/app/tasks/[id]/page.tsx +45 -0
- package/src/app/tasks/new/page.tsx +27 -0
- package/src/app/workflows/[id]/edit/page.tsx +66 -0
- package/src/app/workflows/[id]/page.tsx +37 -0
- package/src/app/workflows/blueprints/[id]/page.tsx +40 -0
- package/src/app/workflows/blueprints/new/page.tsx +20 -0
- package/src/app/workflows/blueprints/page.tsx +11 -0
- package/src/app/workflows/new/page.tsx +36 -0
- package/src/app/workflows/page.tsx +18 -0
- package/src/components/charts/donut-ring.tsx +64 -0
- package/src/components/charts/mini-bar.tsx +75 -0
- package/src/components/charts/sparkline.tsx +107 -0
- package/src/components/costs/cost-dashboard.tsx +877 -0
- package/src/components/costs/cost-filters.tsx +179 -0
- package/src/components/dashboard/activity-feed.tsx +95 -0
- package/src/components/dashboard/greeting.tsx +30 -0
- package/src/components/dashboard/priority-queue.tsx +79 -0
- package/src/components/dashboard/quick-actions.tsx +62 -0
- package/src/components/dashboard/recent-projects.tsx +79 -0
- package/src/components/dashboard/stats-cards.tsx +114 -0
- package/src/components/documents/document-browser.tsx +235 -0
- package/src/components/documents/document-detail-view.tsx +367 -0
- package/src/components/documents/document-grid.tsx +78 -0
- package/src/components/documents/document-preview.tsx +68 -0
- package/src/components/documents/document-table.tsx +119 -0
- package/src/components/documents/document-upload-dialog.tsx +153 -0
- package/src/components/documents/types.ts +6 -0
- package/src/components/documents/utils.ts +57 -0
- package/src/components/monitoring/connection-indicator.tsx +14 -0
- package/src/components/monitoring/log-entry.tsx +79 -0
- package/src/components/monitoring/log-filters.tsx +57 -0
- package/src/components/monitoring/log-stream.tsx +144 -0
- package/src/components/monitoring/monitor-overview-wrapper.tsx +64 -0
- package/src/components/monitoring/monitor-overview.tsx +119 -0
- package/src/components/notifications/failure-action.tsx +38 -0
- package/src/components/notifications/inbox-list.tsx +165 -0
- package/src/components/notifications/message-response.tsx +196 -0
- package/src/components/notifications/notification-item.tsx +250 -0
- package/src/components/notifications/pending-approval-host.tsx +478 -0
- package/src/components/notifications/permission-action.tsx +37 -0
- package/src/components/notifications/permission-response-actions.tsx +126 -0
- package/src/components/notifications/unread-badge.tsx +35 -0
- package/src/components/profiles/profile-browser.tsx +117 -0
- package/src/components/profiles/profile-card.tsx +78 -0
- package/src/components/profiles/profile-detail-view.tsx +564 -0
- package/src/components/profiles/profile-form-view.tsx +480 -0
- package/src/components/profiles/profile-import-dialog.tsx +113 -0
- package/src/components/projects/project-card.tsx +58 -0
- package/src/components/projects/project-create-dialog.tsx +140 -0
- package/src/components/projects/project-detail.tsx +68 -0
- package/src/components/projects/project-edit-dialog.tsx +219 -0
- package/src/components/projects/project-list.tsx +108 -0
- package/src/components/schedules/schedule-create-dialog.tsx +403 -0
- package/src/components/schedules/schedule-detail-view.tsx +274 -0
- package/src/components/schedules/schedule-list.tsx +242 -0
- package/src/components/schedules/schedule-status-badge.tsx +16 -0
- package/src/components/settings/api-key-form.tsx +141 -0
- package/src/components/settings/auth-config-section.tsx +141 -0
- package/src/components/settings/auth-method-selector.tsx +67 -0
- package/src/components/settings/auth-status-badge.tsx +40 -0
- package/src/components/settings/auth-status-dot.tsx +59 -0
- package/src/components/settings/budget-guardrails-section.tsx +842 -0
- package/src/components/settings/data-management-section.tsx +141 -0
- package/src/components/settings/openai-runtime-section.tsx +104 -0
- package/src/components/settings/permissions-section.tsx +91 -0
- package/src/components/shared/app-sidebar.tsx +123 -0
- package/src/components/shared/card-skeleton.tsx +42 -0
- package/src/components/shared/command-palette.tsx +250 -0
- package/src/components/shared/confirm-dialog.tsx +52 -0
- package/src/components/shared/empty-state.tsx +24 -0
- package/src/components/shared/error-state.tsx +32 -0
- package/src/components/shared/form-section-card.tsx +33 -0
- package/src/components/shared/section-heading.tsx +14 -0
- package/src/components/shared/stagent-logo.tsx +21 -0
- package/src/components/shared/theme-toggle.tsx +46 -0
- package/src/components/tasks/ai-assist-panel.tsx +210 -0
- package/src/components/tasks/content-preview.tsx +89 -0
- package/src/components/tasks/empty-board.tsx +12 -0
- package/src/components/tasks/file-upload.tsx +120 -0
- package/src/components/tasks/kanban-board.tsx +275 -0
- package/src/components/tasks/kanban-column.tsx +75 -0
- package/src/components/tasks/skeleton-board.tsx +21 -0
- package/src/components/tasks/task-attachments.tsx +114 -0
- package/src/components/tasks/task-card.tsx +101 -0
- package/src/components/tasks/task-create-panel.tsx +360 -0
- package/src/components/tasks/task-detail-view.tsx +356 -0
- package/src/components/ui/alert-dialog.tsx +196 -0
- package/src/components/ui/badge.tsx +50 -0
- package/src/components/ui/button.tsx +71 -0
- package/src/components/ui/card.tsx +92 -0
- package/src/components/ui/checkbox.tsx +32 -0
- package/src/components/ui/command.tsx +184 -0
- package/src/components/ui/dialog.tsx +158 -0
- package/src/components/ui/dropdown-menu.tsx +257 -0
- package/src/components/ui/form.tsx +167 -0
- package/src/components/ui/input.tsx +21 -0
- package/src/components/ui/label.tsx +24 -0
- package/src/components/ui/popover.tsx +89 -0
- package/src/components/ui/progress.tsx +31 -0
- package/src/components/ui/radio-group.tsx +45 -0
- package/src/components/ui/scroll-area.tsx +58 -0
- package/src/components/ui/select.tsx +190 -0
- package/src/components/ui/separator.tsx +28 -0
- package/src/components/ui/sheet.tsx +143 -0
- package/src/components/ui/sidebar.tsx +726 -0
- package/src/components/ui/skeleton.tsx +13 -0
- package/src/components/ui/slider.tsx +63 -0
- package/src/components/ui/sonner.tsx +36 -0
- package/src/components/ui/switch.tsx +35 -0
- package/src/components/ui/table.tsx +116 -0
- package/src/components/ui/tabs.tsx +91 -0
- package/src/components/ui/textarea.tsx +18 -0
- package/src/components/ui/tooltip.tsx +57 -0
- package/src/components/workflows/blueprint-editor.tsx +109 -0
- package/src/components/workflows/blueprint-gallery.tsx +155 -0
- package/src/components/workflows/blueprint-preview.tsx +240 -0
- package/src/components/workflows/loop-status-view.tsx +272 -0
- package/src/components/workflows/swarm-dashboard.tsx +185 -0
- package/src/components/workflows/workflow-form-view.tsx +1376 -0
- package/src/components/workflows/workflow-list.tsx +230 -0
- package/src/components/workflows/workflow-status-view.tsx +477 -0
- package/src/hooks/use-mobile.ts +19 -0
- package/src/instrumentation.ts +7 -0
- package/src/lib/agents/claude-agent.ts +737 -0
- package/src/lib/agents/execution-manager.ts +27 -0
- package/src/lib/agents/profiles/assignment-validation.ts +75 -0
- package/src/lib/agents/profiles/builtins/code-reviewer/SKILL.md +21 -0
- package/src/lib/agents/profiles/builtins/code-reviewer/profile.yaml +28 -0
- package/src/lib/agents/profiles/builtins/data-analyst/SKILL.md +25 -0
- package/src/lib/agents/profiles/builtins/data-analyst/profile.yaml +27 -0
- package/src/lib/agents/profiles/builtins/devops-engineer/SKILL.md +34 -0
- package/src/lib/agents/profiles/builtins/devops-engineer/profile.yaml +27 -0
- package/src/lib/agents/profiles/builtins/document-writer/SKILL.md +16 -0
- package/src/lib/agents/profiles/builtins/document-writer/profile.yaml +27 -0
- package/src/lib/agents/profiles/builtins/general/SKILL.md +13 -0
- package/src/lib/agents/profiles/builtins/general/profile.yaml +18 -0
- package/src/lib/agents/profiles/builtins/health-fitness-coach/SKILL.md +34 -0
- package/src/lib/agents/profiles/builtins/health-fitness-coach/profile.yaml +26 -0
- package/src/lib/agents/profiles/builtins/learning-coach/SKILL.md +35 -0
- package/src/lib/agents/profiles/builtins/learning-coach/profile.yaml +26 -0
- package/src/lib/agents/profiles/builtins/project-manager/SKILL.md +26 -0
- package/src/lib/agents/profiles/builtins/project-manager/profile.yaml +26 -0
- package/src/lib/agents/profiles/builtins/researcher/SKILL.md +15 -0
- package/src/lib/agents/profiles/builtins/researcher/profile.yaml +27 -0
- package/src/lib/agents/profiles/builtins/shopping-assistant/SKILL.md +34 -0
- package/src/lib/agents/profiles/builtins/shopping-assistant/profile.yaml +26 -0
- package/src/lib/agents/profiles/builtins/technical-writer/SKILL.md +31 -0
- package/src/lib/agents/profiles/builtins/technical-writer/profile.yaml +29 -0
- package/src/lib/agents/profiles/builtins/travel-planner/SKILL.md +23 -0
- package/src/lib/agents/profiles/builtins/travel-planner/profile.yaml +26 -0
- package/src/lib/agents/profiles/builtins/wealth-manager/SKILL.md +24 -0
- package/src/lib/agents/profiles/builtins/wealth-manager/profile.yaml +26 -0
- package/src/lib/agents/profiles/compatibility.ts +109 -0
- package/src/lib/agents/profiles/registry.ts +293 -0
- package/src/lib/agents/profiles/test-runner.ts +18 -0
- package/src/lib/agents/profiles/test-types.ts +20 -0
- package/src/lib/agents/profiles/types.ts +43 -0
- package/src/lib/agents/router.ts +56 -0
- package/src/lib/agents/runtime/catalog.ts +85 -0
- package/src/lib/agents/runtime/claude-sdk.ts +12 -0
- package/src/lib/agents/runtime/claude.ts +370 -0
- package/src/lib/agents/runtime/codex-app-server-client.ts +289 -0
- package/src/lib/agents/runtime/index.ts +167 -0
- package/src/lib/agents/runtime/openai-codex.ts +1089 -0
- package/src/lib/agents/runtime/task-assist-types.ts +8 -0
- package/src/lib/agents/runtime/types.ts +30 -0
- package/src/lib/constants/settings.ts +13 -0
- package/src/lib/constants/status-colors.ts +44 -0
- package/src/lib/constants/task-status.ts +49 -0
- package/src/lib/data/clear.ts +63 -0
- package/src/lib/data/seed-data/documents.ts +715 -0
- package/src/lib/data/seed-data/logs.ts +195 -0
- package/src/lib/data/seed-data/notifications.ts +141 -0
- package/src/lib/data/seed-data/profiles.ts +175 -0
- package/src/lib/data/seed-data/projects.ts +61 -0
- package/src/lib/data/seed-data/schedules.ts +108 -0
- package/src/lib/data/seed-data/tasks.ts +341 -0
- package/src/lib/data/seed-data/usage-ledger.ts +130 -0
- package/src/lib/data/seed-data/workflows.ts +213 -0
- package/src/lib/data/seed.ts +129 -0
- package/src/lib/db/index.ts +221 -0
- package/src/lib/db/migrations/0000_aromatic_gargoyle.sql +59 -0
- package/src/lib/db/migrations/0001_first_iron_patriot.sql +6 -0
- package/src/lib/db/migrations/0002_add_resume_count.sql +1 -0
- package/src/lib/db/migrations/0003_add_settings.sql +5 -0
- package/src/lib/db/migrations/0004_add_documents.sql +20 -0
- package/src/lib/db/migrations/0005_add_document_preprocessing.sql +4 -0
- package/src/lib/db/migrations/0006_add_agent_profile.sql +2 -0
- package/src/lib/db/migrations/0007_add_usage_metering_ledger.sql +30 -0
- package/src/lib/db/migrations/0008_add_document_version.sql +1 -0
- package/src/lib/db/migrations/meta/0000_snapshot.json +416 -0
- package/src/lib/db/migrations/meta/0001_snapshot.json +461 -0
- package/src/lib/db/migrations/meta/0002_snapshot.json +469 -0
- package/src/lib/db/migrations/meta/_journal.json +27 -0
- package/src/lib/db/schema.ts +227 -0
- package/src/lib/documents/cleanup.ts +50 -0
- package/src/lib/documents/context-builder.ts +75 -0
- package/src/lib/documents/output-scanner.ts +166 -0
- package/src/lib/documents/processor.ts +120 -0
- package/src/lib/documents/processors/image.ts +21 -0
- package/src/lib/documents/processors/office.ts +36 -0
- package/src/lib/documents/processors/pdf.ts +12 -0
- package/src/lib/documents/processors/spreadsheet.ts +18 -0
- package/src/lib/documents/processors/text.ts +8 -0
- package/src/lib/documents/registry.ts +25 -0
- package/src/lib/notifications/actionable.ts +108 -0
- package/src/lib/notifications/permissions.ts +169 -0
- package/src/lib/queries/chart-data.ts +184 -0
- package/src/lib/schedules/interval-parser.ts +110 -0
- package/src/lib/schedules/scheduler.ts +220 -0
- package/src/lib/settings/auth.ts +98 -0
- package/src/lib/settings/budget-guardrails.ts +590 -0
- package/src/lib/settings/helpers.ts +23 -0
- package/src/lib/settings/openai-auth.ts +80 -0
- package/src/lib/settings/permissions.ts +102 -0
- package/src/lib/usage/ledger.ts +489 -0
- package/src/lib/usage/pricing.ts +68 -0
- package/src/lib/utils/crypto.ts +90 -0
- package/src/lib/utils/format-timestamp.ts +46 -0
- package/src/lib/utils/session-cleanup.ts +26 -0
- package/src/lib/utils/stagent-paths.ts +18 -0
- package/src/lib/utils.ts +6 -0
- package/src/lib/validators/blueprint.ts +43 -0
- package/src/lib/validators/profile.ts +64 -0
- package/src/lib/validators/project.ts +17 -0
- package/src/lib/validators/settings.ts +57 -0
- package/src/lib/validators/task.ts +30 -0
- package/src/lib/workflows/blueprints/builtins/code-review-pipeline.yaml +72 -0
- package/src/lib/workflows/blueprints/builtins/documentation-generation.yaml +62 -0
- package/src/lib/workflows/blueprints/builtins/investment-research.yaml +81 -0
- package/src/lib/workflows/blueprints/builtins/meal-planning.yaml +73 -0
- package/src/lib/workflows/blueprints/builtins/product-research.yaml +72 -0
- package/src/lib/workflows/blueprints/builtins/research-report.yaml +77 -0
- package/src/lib/workflows/blueprints/builtins/sprint-planning.yaml +77 -0
- package/src/lib/workflows/blueprints/builtins/travel-planning.yaml +80 -0
- package/src/lib/workflows/blueprints/instantiator.ts +131 -0
- package/src/lib/workflows/blueprints/registry.ts +128 -0
- package/src/lib/workflows/blueprints/template.ts +58 -0
- package/src/lib/workflows/blueprints/types.ts +38 -0
- package/src/lib/workflows/definition-validation.ts +121 -0
- package/src/lib/workflows/engine.ts +1113 -0
- package/src/lib/workflows/loop-executor.ts +270 -0
- package/src/lib/workflows/parallel.ts +55 -0
- package/src/lib/workflows/swarm.ts +97 -0
- package/src/lib/workflows/types.ts +112 -0
- package/tsconfig.json +41 -0
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
import { and, eq, gte, lt } from "drizzle-orm";
|
|
2
|
+
import { db } from "@/lib/db";
|
|
3
|
+
import { notifications, tasks, usageLedger } from "@/lib/db/schema";
|
|
4
|
+
import { SETTINGS_KEYS } from "@/lib/constants/settings";
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_AGENT_RUNTIME,
|
|
7
|
+
getRuntimeCatalogEntry,
|
|
8
|
+
resolveAgentRuntime,
|
|
9
|
+
SUPPORTED_AGENT_RUNTIMES,
|
|
10
|
+
type AgentRuntimeId,
|
|
11
|
+
} from "@/lib/agents/runtime/catalog";
|
|
12
|
+
import { getSetting, setSetting } from "./helpers";
|
|
13
|
+
import {
|
|
14
|
+
budgetPolicySchema,
|
|
15
|
+
type BudgetPolicy,
|
|
16
|
+
type RuntimeBudgetPolicy,
|
|
17
|
+
type UpdateBudgetPolicyInput,
|
|
18
|
+
} from "@/lib/validators/settings";
|
|
19
|
+
import {
|
|
20
|
+
recordUsageLedgerEntry,
|
|
21
|
+
resolveUsageActivityType,
|
|
22
|
+
type UsageActivityType,
|
|
23
|
+
} from "@/lib/usage/ledger";
|
|
24
|
+
|
|
25
|
+
const WARNING_THRESHOLD = 0.8;
|
|
26
|
+
|
|
27
|
+
type BudgetWindow = "daily" | "monthly";
|
|
28
|
+
type BudgetMetric = "spend" | "tokens";
|
|
29
|
+
type BudgetHealth = "unlimited" | "ok" | "warning" | "blocked";
|
|
30
|
+
type BudgetScopeId = "overall" | AgentRuntimeId;
|
|
31
|
+
|
|
32
|
+
interface UsageAggregate {
|
|
33
|
+
costMicros: number;
|
|
34
|
+
totalTokens: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface BudgetWindowStatus {
|
|
38
|
+
id: string;
|
|
39
|
+
scopeId: BudgetScopeId;
|
|
40
|
+
scopeLabel: string;
|
|
41
|
+
runtimeId: AgentRuntimeId | null;
|
|
42
|
+
metric: BudgetMetric;
|
|
43
|
+
window: BudgetWindow;
|
|
44
|
+
currentValue: number;
|
|
45
|
+
limitValue: number | null;
|
|
46
|
+
ratio: number | null;
|
|
47
|
+
health: BudgetHealth;
|
|
48
|
+
resetAt: Date;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface BudgetWarningState {
|
|
52
|
+
[statusId: string]: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface BudgetSnapshot {
|
|
56
|
+
policy: BudgetPolicy;
|
|
57
|
+
statuses: Array<BudgetWindowStatus & { resetAtIso: string }>;
|
|
58
|
+
dailyResetAtIso: string;
|
|
59
|
+
monthlyResetAtIso: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface BudgetGuardInput {
|
|
63
|
+
runtimeId?: string | null;
|
|
64
|
+
taskId?: string | null;
|
|
65
|
+
projectId?: string | null;
|
|
66
|
+
workflowId?: string | null;
|
|
67
|
+
scheduleId?: string | null;
|
|
68
|
+
activityType: UsageActivityType;
|
|
69
|
+
failTaskOnBlock?: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function createEmptyRuntimeBudgetPolicy(): RuntimeBudgetPolicy {
|
|
73
|
+
return {
|
|
74
|
+
dailySpendCapUsd: null,
|
|
75
|
+
monthlySpendCapUsd: null,
|
|
76
|
+
dailyTokenCap: null,
|
|
77
|
+
monthlyTokenCap: null,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createEmptyBudgetPolicy(): BudgetPolicy {
|
|
82
|
+
return {
|
|
83
|
+
overall: {
|
|
84
|
+
dailySpendCapUsd: null,
|
|
85
|
+
monthlySpendCapUsd: null,
|
|
86
|
+
},
|
|
87
|
+
runtimes: Object.fromEntries(
|
|
88
|
+
SUPPORTED_AGENT_RUNTIMES.map((runtimeId) => [
|
|
89
|
+
runtimeId,
|
|
90
|
+
createEmptyRuntimeBudgetPolicy(),
|
|
91
|
+
])
|
|
92
|
+
) as BudgetPolicy["runtimes"],
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function formatWindowKey(window: BudgetWindow, date: Date) {
|
|
97
|
+
if (window === "daily") {
|
|
98
|
+
return new Intl.DateTimeFormat("en-CA", {
|
|
99
|
+
year: "numeric",
|
|
100
|
+
month: "2-digit",
|
|
101
|
+
day: "2-digit",
|
|
102
|
+
}).format(date);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const year = date.getFullYear();
|
|
106
|
+
const month = `${date.getMonth() + 1}`.padStart(2, "0");
|
|
107
|
+
return `${year}-${month}`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function formatMicrosAsUsd(micros: number) {
|
|
111
|
+
return new Intl.NumberFormat("en-US", {
|
|
112
|
+
style: "currency",
|
|
113
|
+
currency: "USD",
|
|
114
|
+
minimumFractionDigits: 2,
|
|
115
|
+
maximumFractionDigits: 4,
|
|
116
|
+
}).format(micros / 1_000_000);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function formatTokenCount(tokens: number) {
|
|
120
|
+
return new Intl.NumberFormat("en-US").format(tokens);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function formatResetAt(date: Date) {
|
|
124
|
+
return new Intl.DateTimeFormat("en-US", {
|
|
125
|
+
dateStyle: "medium",
|
|
126
|
+
timeStyle: "short",
|
|
127
|
+
}).format(date);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function usdToMicros(value: number | null) {
|
|
131
|
+
return value == null ? null : Math.round(value * 1_000_000);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function getBudgetWindowBounds(now = new Date()) {
|
|
135
|
+
const dailyStart = new Date(now);
|
|
136
|
+
dailyStart.setHours(0, 0, 0, 0);
|
|
137
|
+
|
|
138
|
+
const dailyEnd = new Date(dailyStart);
|
|
139
|
+
dailyEnd.setDate(dailyEnd.getDate() + 1);
|
|
140
|
+
|
|
141
|
+
const monthlyStart = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
142
|
+
monthlyStart.setHours(0, 0, 0, 0);
|
|
143
|
+
|
|
144
|
+
const monthlyEnd = new Date(now.getFullYear(), now.getMonth() + 1, 1);
|
|
145
|
+
monthlyEnd.setHours(0, 0, 0, 0);
|
|
146
|
+
|
|
147
|
+
return { dailyStart, dailyEnd, monthlyStart, monthlyEnd };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function getWarningState(): Promise<BudgetWarningState> {
|
|
151
|
+
const raw = await getSetting(SETTINGS_KEYS.BUDGET_WARNING_STATE);
|
|
152
|
+
if (!raw) {
|
|
153
|
+
return {};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
try {
|
|
157
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
158
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
159
|
+
? (parsed as BudgetWarningState)
|
|
160
|
+
: {};
|
|
161
|
+
} catch {
|
|
162
|
+
return {};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function setWarningState(state: BudgetWarningState) {
|
|
167
|
+
await setSetting(SETTINGS_KEYS.BUDGET_WARNING_STATE, JSON.stringify(state));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function getBudgetPolicy(): Promise<BudgetPolicy> {
|
|
171
|
+
const raw = await getSetting(SETTINGS_KEYS.BUDGET_POLICY);
|
|
172
|
+
if (!raw) {
|
|
173
|
+
return createEmptyBudgetPolicy();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
const parsed = budgetPolicySchema.safeParse(JSON.parse(raw));
|
|
178
|
+
return parsed.success ? parsed.data : createEmptyBudgetPolicy();
|
|
179
|
+
} catch {
|
|
180
|
+
return createEmptyBudgetPolicy();
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function setBudgetPolicy(
|
|
185
|
+
input: UpdateBudgetPolicyInput
|
|
186
|
+
): Promise<BudgetPolicy> {
|
|
187
|
+
const parsed = budgetPolicySchema.parse(input);
|
|
188
|
+
await setSetting(SETTINGS_KEYS.BUDGET_POLICY, JSON.stringify(parsed));
|
|
189
|
+
await setWarningState({});
|
|
190
|
+
return parsed;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function getUsageAggregates(now = new Date()) {
|
|
194
|
+
const { dailyStart, dailyEnd, monthlyStart, monthlyEnd } =
|
|
195
|
+
getBudgetWindowBounds(now);
|
|
196
|
+
|
|
197
|
+
const rows = await db
|
|
198
|
+
.select({
|
|
199
|
+
runtimeId: usageLedger.runtimeId,
|
|
200
|
+
costMicros: usageLedger.costMicros,
|
|
201
|
+
totalTokens: usageLedger.totalTokens,
|
|
202
|
+
finishedAt: usageLedger.finishedAt,
|
|
203
|
+
})
|
|
204
|
+
.from(usageLedger)
|
|
205
|
+
.where(
|
|
206
|
+
and(
|
|
207
|
+
gte(usageLedger.finishedAt, monthlyStart),
|
|
208
|
+
lt(usageLedger.finishedAt, monthlyEnd)
|
|
209
|
+
)
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
const overall = {
|
|
213
|
+
daily: { costMicros: 0, totalTokens: 0 },
|
|
214
|
+
monthly: { costMicros: 0, totalTokens: 0 },
|
|
215
|
+
};
|
|
216
|
+
const runtimes = Object.fromEntries(
|
|
217
|
+
SUPPORTED_AGENT_RUNTIMES.map((runtimeId) => [
|
|
218
|
+
runtimeId,
|
|
219
|
+
{
|
|
220
|
+
daily: { costMicros: 0, totalTokens: 0 },
|
|
221
|
+
monthly: { costMicros: 0, totalTokens: 0 },
|
|
222
|
+
},
|
|
223
|
+
])
|
|
224
|
+
) as Record<AgentRuntimeId, { daily: UsageAggregate; monthly: UsageAggregate }>;
|
|
225
|
+
|
|
226
|
+
rows.forEach((row) => {
|
|
227
|
+
const runtimeId = SUPPORTED_AGENT_RUNTIMES.find(
|
|
228
|
+
(candidate) => candidate === row.runtimeId
|
|
229
|
+
);
|
|
230
|
+
if (!runtimeId) {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const costMicros = row.costMicros ?? 0;
|
|
235
|
+
const totalTokens = row.totalTokens ?? 0;
|
|
236
|
+
|
|
237
|
+
overall.monthly.costMicros += costMicros;
|
|
238
|
+
overall.monthly.totalTokens += totalTokens;
|
|
239
|
+
runtimes[runtimeId].monthly.costMicros += costMicros;
|
|
240
|
+
runtimes[runtimeId].monthly.totalTokens += totalTokens;
|
|
241
|
+
|
|
242
|
+
if (row.finishedAt >= dailyStart && row.finishedAt < dailyEnd) {
|
|
243
|
+
overall.daily.costMicros += costMicros;
|
|
244
|
+
overall.daily.totalTokens += totalTokens;
|
|
245
|
+
runtimes[runtimeId].daily.costMicros += costMicros;
|
|
246
|
+
runtimes[runtimeId].daily.totalTokens += totalTokens;
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
overall,
|
|
252
|
+
runtimes,
|
|
253
|
+
...getBudgetWindowBounds(now),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function buildStatus(input: {
|
|
258
|
+
scopeId: BudgetScopeId;
|
|
259
|
+
scopeLabel: string;
|
|
260
|
+
runtimeId: AgentRuntimeId | null;
|
|
261
|
+
metric: BudgetMetric;
|
|
262
|
+
window: BudgetWindow;
|
|
263
|
+
currentValue: number;
|
|
264
|
+
limitValue: number | null;
|
|
265
|
+
resetAt: Date;
|
|
266
|
+
}): BudgetWindowStatus {
|
|
267
|
+
const ratio =
|
|
268
|
+
input.limitValue && input.limitValue > 0
|
|
269
|
+
? input.currentValue / input.limitValue
|
|
270
|
+
: null;
|
|
271
|
+
|
|
272
|
+
let health: BudgetHealth = "unlimited";
|
|
273
|
+
if (input.limitValue != null) {
|
|
274
|
+
if (ratio != null && ratio >= 1) {
|
|
275
|
+
health = "blocked";
|
|
276
|
+
} else if (ratio != null && ratio >= WARNING_THRESHOLD) {
|
|
277
|
+
health = "warning";
|
|
278
|
+
} else {
|
|
279
|
+
health = "ok";
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
id: `${input.scopeId}:${input.window}:${input.metric}`,
|
|
285
|
+
scopeId: input.scopeId,
|
|
286
|
+
scopeLabel: input.scopeLabel,
|
|
287
|
+
runtimeId: input.runtimeId,
|
|
288
|
+
metric: input.metric,
|
|
289
|
+
window: input.window,
|
|
290
|
+
currentValue: input.currentValue,
|
|
291
|
+
limitValue: input.limitValue,
|
|
292
|
+
ratio,
|
|
293
|
+
health,
|
|
294
|
+
resetAt: input.resetAt,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function buildBudgetStatuses(
|
|
299
|
+
policy: BudgetPolicy,
|
|
300
|
+
aggregates: Awaited<ReturnType<typeof getUsageAggregates>>
|
|
301
|
+
) {
|
|
302
|
+
const statuses: BudgetWindowStatus[] = [];
|
|
303
|
+
|
|
304
|
+
statuses.push(
|
|
305
|
+
buildStatus({
|
|
306
|
+
scopeId: "overall",
|
|
307
|
+
scopeLabel: "Overall",
|
|
308
|
+
runtimeId: null,
|
|
309
|
+
metric: "spend",
|
|
310
|
+
window: "daily",
|
|
311
|
+
currentValue: aggregates.overall.daily.costMicros,
|
|
312
|
+
limitValue: usdToMicros(policy.overall.dailySpendCapUsd),
|
|
313
|
+
resetAt: aggregates.dailyEnd,
|
|
314
|
+
}),
|
|
315
|
+
buildStatus({
|
|
316
|
+
scopeId: "overall",
|
|
317
|
+
scopeLabel: "Overall",
|
|
318
|
+
runtimeId: null,
|
|
319
|
+
metric: "spend",
|
|
320
|
+
window: "monthly",
|
|
321
|
+
currentValue: aggregates.overall.monthly.costMicros,
|
|
322
|
+
limitValue: usdToMicros(policy.overall.monthlySpendCapUsd),
|
|
323
|
+
resetAt: aggregates.monthlyEnd,
|
|
324
|
+
})
|
|
325
|
+
);
|
|
326
|
+
|
|
327
|
+
SUPPORTED_AGENT_RUNTIMES.forEach((runtimeId) => {
|
|
328
|
+
const runtime = getRuntimeCatalogEntry(runtimeId);
|
|
329
|
+
const runtimePolicy = policy.runtimes[runtimeId];
|
|
330
|
+
const usage = aggregates.runtimes[runtimeId];
|
|
331
|
+
|
|
332
|
+
statuses.push(
|
|
333
|
+
buildStatus({
|
|
334
|
+
scopeId: runtimeId,
|
|
335
|
+
scopeLabel: runtime.label,
|
|
336
|
+
runtimeId,
|
|
337
|
+
metric: "spend",
|
|
338
|
+
window: "daily",
|
|
339
|
+
currentValue: usage.daily.costMicros,
|
|
340
|
+
limitValue: usdToMicros(runtimePolicy.dailySpendCapUsd),
|
|
341
|
+
resetAt: aggregates.dailyEnd,
|
|
342
|
+
}),
|
|
343
|
+
buildStatus({
|
|
344
|
+
scopeId: runtimeId,
|
|
345
|
+
scopeLabel: runtime.label,
|
|
346
|
+
runtimeId,
|
|
347
|
+
metric: "spend",
|
|
348
|
+
window: "monthly",
|
|
349
|
+
currentValue: usage.monthly.costMicros,
|
|
350
|
+
limitValue: usdToMicros(runtimePolicy.monthlySpendCapUsd),
|
|
351
|
+
resetAt: aggregates.monthlyEnd,
|
|
352
|
+
}),
|
|
353
|
+
buildStatus({
|
|
354
|
+
scopeId: runtimeId,
|
|
355
|
+
scopeLabel: runtime.label,
|
|
356
|
+
runtimeId,
|
|
357
|
+
metric: "tokens",
|
|
358
|
+
window: "daily",
|
|
359
|
+
currentValue: usage.daily.totalTokens,
|
|
360
|
+
limitValue: runtimePolicy.dailyTokenCap,
|
|
361
|
+
resetAt: aggregates.dailyEnd,
|
|
362
|
+
}),
|
|
363
|
+
buildStatus({
|
|
364
|
+
scopeId: runtimeId,
|
|
365
|
+
scopeLabel: runtime.label,
|
|
366
|
+
runtimeId,
|
|
367
|
+
metric: "tokens",
|
|
368
|
+
window: "monthly",
|
|
369
|
+
currentValue: usage.monthly.totalTokens,
|
|
370
|
+
limitValue: runtimePolicy.monthlyTokenCap,
|
|
371
|
+
resetAt: aggregates.monthlyEnd,
|
|
372
|
+
})
|
|
373
|
+
);
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
return statuses;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function describeBudgetStatus(status: BudgetWindowStatus) {
|
|
380
|
+
const metricLabel = status.metric === "spend" ? "spend" : "token usage";
|
|
381
|
+
const currentLabel =
|
|
382
|
+
status.metric === "spend"
|
|
383
|
+
? formatMicrosAsUsd(status.currentValue)
|
|
384
|
+
: formatTokenCount(status.currentValue);
|
|
385
|
+
const limitLabel =
|
|
386
|
+
status.limitValue == null
|
|
387
|
+
? "Unlimited"
|
|
388
|
+
: status.metric === "spend"
|
|
389
|
+
? formatMicrosAsUsd(status.limitValue)
|
|
390
|
+
: formatTokenCount(status.limitValue);
|
|
391
|
+
|
|
392
|
+
return `${status.scopeLabel} ${status.window} ${metricLabel} is ${currentLabel} of ${limitLabel}. Resets ${formatResetAt(status.resetAt)}.`;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function createBudgetNotification(input: {
|
|
396
|
+
title: string;
|
|
397
|
+
body: string;
|
|
398
|
+
taskId?: string | null;
|
|
399
|
+
}) {
|
|
400
|
+
await db.insert(notifications).values({
|
|
401
|
+
id: crypto.randomUUID(),
|
|
402
|
+
taskId: input.taskId ?? null,
|
|
403
|
+
type: "budget_alert",
|
|
404
|
+
title: input.title,
|
|
405
|
+
body: input.body,
|
|
406
|
+
read: false,
|
|
407
|
+
toolName: null,
|
|
408
|
+
toolInput: null,
|
|
409
|
+
response: null,
|
|
410
|
+
respondedAt: null,
|
|
411
|
+
createdAt: new Date(),
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function emitWarningNotifications(
|
|
416
|
+
statuses: BudgetWindowStatus[],
|
|
417
|
+
warningState: BudgetWarningState,
|
|
418
|
+
taskId?: string | null
|
|
419
|
+
) {
|
|
420
|
+
let changed = false;
|
|
421
|
+
|
|
422
|
+
for (const status of statuses) {
|
|
423
|
+
const windowKey = formatWindowKey(status.window, status.resetAt);
|
|
424
|
+
if (warningState[status.id] === windowKey) {
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const percent = status.ratio == null ? 0 : Math.round(status.ratio * 100);
|
|
429
|
+
await createBudgetNotification({
|
|
430
|
+
taskId,
|
|
431
|
+
title: `${status.scopeLabel} ${status.window} ${status.metric} at ${percent}%`,
|
|
432
|
+
body: describeBudgetStatus(status),
|
|
433
|
+
});
|
|
434
|
+
warningState[status.id] = windowKey;
|
|
435
|
+
changed = true;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (changed) {
|
|
439
|
+
await setWarningState(warningState);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function recordBlockedAttempt(input: {
|
|
444
|
+
runtimeId: AgentRuntimeId;
|
|
445
|
+
activityType: UsageActivityType;
|
|
446
|
+
taskId?: string | null;
|
|
447
|
+
projectId?: string | null;
|
|
448
|
+
workflowId?: string | null;
|
|
449
|
+
scheduleId?: string | null;
|
|
450
|
+
}) {
|
|
451
|
+
const runtime = getRuntimeCatalogEntry(input.runtimeId);
|
|
452
|
+
await recordUsageLedgerEntry({
|
|
453
|
+
taskId: input.taskId ?? null,
|
|
454
|
+
projectId: input.projectId ?? null,
|
|
455
|
+
workflowId: input.workflowId ?? null,
|
|
456
|
+
scheduleId: input.scheduleId ?? null,
|
|
457
|
+
activityType: input.activityType,
|
|
458
|
+
runtimeId: input.runtimeId,
|
|
459
|
+
providerId: runtime.providerId,
|
|
460
|
+
status: "blocked",
|
|
461
|
+
startedAt: new Date(),
|
|
462
|
+
finishedAt: new Date(),
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async function markTaskBlocked(taskId: string, message: string) {
|
|
467
|
+
await db
|
|
468
|
+
.update(tasks)
|
|
469
|
+
.set({
|
|
470
|
+
status: "failed",
|
|
471
|
+
result: message,
|
|
472
|
+
updatedAt: new Date(),
|
|
473
|
+
})
|
|
474
|
+
.where(eq(tasks.id, taskId));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async function getTaskBudgetContext(taskId: string, isResume = false) {
|
|
478
|
+
const [task] = await db
|
|
479
|
+
.select({
|
|
480
|
+
id: tasks.id,
|
|
481
|
+
projectId: tasks.projectId,
|
|
482
|
+
workflowId: tasks.workflowId,
|
|
483
|
+
scheduleId: tasks.scheduleId,
|
|
484
|
+
assignedAgent: tasks.assignedAgent,
|
|
485
|
+
})
|
|
486
|
+
.from(tasks)
|
|
487
|
+
.where(eq(tasks.id, taskId));
|
|
488
|
+
|
|
489
|
+
if (!task) {
|
|
490
|
+
throw new Error(`Task ${taskId} not found`);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return {
|
|
494
|
+
runtimeId: resolveAgentRuntime(task.assignedAgent ?? DEFAULT_AGENT_RUNTIME),
|
|
495
|
+
taskId: task.id,
|
|
496
|
+
projectId: task.projectId ?? null,
|
|
497
|
+
workflowId: task.workflowId ?? null,
|
|
498
|
+
scheduleId: task.scheduleId ?? null,
|
|
499
|
+
activityType: resolveUsageActivityType({
|
|
500
|
+
workflowId: task.workflowId,
|
|
501
|
+
scheduleId: task.scheduleId,
|
|
502
|
+
isResume,
|
|
503
|
+
}),
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
export class BudgetLimitExceededError extends Error {
|
|
508
|
+
readonly status: BudgetWindowStatus;
|
|
509
|
+
|
|
510
|
+
constructor(status: BudgetWindowStatus) {
|
|
511
|
+
super(describeBudgetStatus(status));
|
|
512
|
+
this.name = "BudgetLimitExceededError";
|
|
513
|
+
this.status = status;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export async function enforceBudgetGuardrails(input: BudgetGuardInput) {
|
|
518
|
+
const runtimeId = resolveAgentRuntime(input.runtimeId ?? DEFAULT_AGENT_RUNTIME);
|
|
519
|
+
const policy = await getBudgetPolicy();
|
|
520
|
+
const warningState = await getWarningState();
|
|
521
|
+
const aggregates = await getUsageAggregates();
|
|
522
|
+
const statuses = buildBudgetStatuses(policy, aggregates).filter(
|
|
523
|
+
(status) => status.scopeId === "overall" || status.runtimeId === runtimeId
|
|
524
|
+
);
|
|
525
|
+
|
|
526
|
+
const blocked = statuses.find((status) => status.health === "blocked");
|
|
527
|
+
const warnings = statuses.filter((status) => status.health === "warning");
|
|
528
|
+
|
|
529
|
+
if (!blocked && warnings.length > 0) {
|
|
530
|
+
await emitWarningNotifications(warnings, warningState, input.taskId ?? null);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
if (!blocked) {
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const runtime = getRuntimeCatalogEntry(runtimeId);
|
|
538
|
+
const title = `${runtime.label} blocked by ${blocked.window} ${blocked.metric} cap`;
|
|
539
|
+
const body = describeBudgetStatus(blocked);
|
|
540
|
+
|
|
541
|
+
await createBudgetNotification({
|
|
542
|
+
taskId: input.taskId ?? null,
|
|
543
|
+
title,
|
|
544
|
+
body,
|
|
545
|
+
});
|
|
546
|
+
await recordBlockedAttempt({
|
|
547
|
+
runtimeId,
|
|
548
|
+
activityType: input.activityType,
|
|
549
|
+
taskId: input.taskId ?? null,
|
|
550
|
+
projectId: input.projectId ?? null,
|
|
551
|
+
workflowId: input.workflowId ?? null,
|
|
552
|
+
scheduleId: input.scheduleId ?? null,
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
if (input.failTaskOnBlock && input.taskId) {
|
|
556
|
+
await markTaskBlocked(input.taskId, body);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
throw new BudgetLimitExceededError(blocked);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export async function enforceTaskBudgetGuardrails(
|
|
563
|
+
taskId: string,
|
|
564
|
+
options?: {
|
|
565
|
+
isResume?: boolean;
|
|
566
|
+
failTaskOnBlock?: boolean;
|
|
567
|
+
}
|
|
568
|
+
) {
|
|
569
|
+
const context = await getTaskBudgetContext(taskId, options?.isResume);
|
|
570
|
+
return enforceBudgetGuardrails({
|
|
571
|
+
...context,
|
|
572
|
+
failTaskOnBlock: options?.failTaskOnBlock,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export async function getBudgetGuardrailSnapshot(): Promise<BudgetSnapshot> {
|
|
577
|
+
const policy = await getBudgetPolicy();
|
|
578
|
+
const aggregates = await getUsageAggregates();
|
|
579
|
+
const statuses = buildBudgetStatuses(policy, aggregates).map((status) => ({
|
|
580
|
+
...status,
|
|
581
|
+
resetAtIso: status.resetAt.toISOString(),
|
|
582
|
+
}));
|
|
583
|
+
|
|
584
|
+
return {
|
|
585
|
+
policy,
|
|
586
|
+
statuses,
|
|
587
|
+
dailyResetAtIso: aggregates.dailyEnd.toISOString(),
|
|
588
|
+
monthlyResetAtIso: aggregates.monthlyEnd.toISOString(),
|
|
589
|
+
};
|
|
590
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { db } from "@/lib/db";
|
|
2
|
+
import { settings } from "@/lib/db/schema";
|
|
3
|
+
import { eq } from "drizzle-orm";
|
|
4
|
+
|
|
5
|
+
/** Read a single setting from DB */
|
|
6
|
+
export async function getSetting(key: string): Promise<string | null> {
|
|
7
|
+
const rows = await db.select().from(settings).where(eq(settings.key, key));
|
|
8
|
+
return rows[0]?.value ?? null;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Upsert a setting in DB */
|
|
12
|
+
export async function setSetting(key: string, value: string): Promise<void> {
|
|
13
|
+
const now = new Date();
|
|
14
|
+
const existing = await getSetting(key);
|
|
15
|
+
if (existing !== null) {
|
|
16
|
+
await db.update(settings)
|
|
17
|
+
.set({ value, updatedAt: now })
|
|
18
|
+
.where(eq(settings.key, key));
|
|
19
|
+
} else {
|
|
20
|
+
await db.insert(settings)
|
|
21
|
+
.values({ key, value, updatedAt: now });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { SETTINGS_KEYS, type ApiKeySource } from "@/lib/constants/settings";
|
|
2
|
+
import { decrypt, encrypt } from "@/lib/utils/crypto";
|
|
3
|
+
import { getSetting, setSetting } from "./helpers";
|
|
4
|
+
|
|
5
|
+
export interface OpenAIAuthSettings {
|
|
6
|
+
hasKey: boolean;
|
|
7
|
+
apiKeySource: ApiKeySource;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface OpenAIAuthConfigInput {
|
|
11
|
+
apiKey: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function getOpenAIAuthSettings(): Promise<OpenAIAuthSettings> {
|
|
15
|
+
const encryptedKey = await getSetting(SETTINGS_KEYS.OPENAI_AUTH_API_KEY);
|
|
16
|
+
const storedSource = (await getSetting(
|
|
17
|
+
SETTINGS_KEYS.OPENAI_AUTH_API_KEY_SOURCE
|
|
18
|
+
)) as ApiKeySource | null;
|
|
19
|
+
|
|
20
|
+
const hasDbKey = encryptedKey !== null;
|
|
21
|
+
const hasEnvKey = !!process.env.OPENAI_API_KEY;
|
|
22
|
+
|
|
23
|
+
let apiKeySource: ApiKeySource;
|
|
24
|
+
if (storedSource) {
|
|
25
|
+
apiKeySource = storedSource;
|
|
26
|
+
} else if (hasDbKey) {
|
|
27
|
+
apiKeySource = "db";
|
|
28
|
+
} else if (hasEnvKey) {
|
|
29
|
+
apiKeySource = "env";
|
|
30
|
+
} else {
|
|
31
|
+
apiKeySource = "unknown";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
hasKey: hasDbKey || hasEnvKey,
|
|
36
|
+
apiKeySource,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function setOpenAIAuthSettings(
|
|
41
|
+
input: OpenAIAuthConfigInput
|
|
42
|
+
): Promise<void> {
|
|
43
|
+
await setSetting(
|
|
44
|
+
SETTINGS_KEYS.OPENAI_AUTH_API_KEY,
|
|
45
|
+
encrypt(input.apiKey)
|
|
46
|
+
);
|
|
47
|
+
await setSetting(SETTINGS_KEYS.OPENAI_AUTH_API_KEY_SOURCE, "db");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function getOpenAIApiKey(): Promise<{
|
|
51
|
+
apiKey: string | null;
|
|
52
|
+
source: Extract<ApiKeySource, "db" | "env" | "unknown">;
|
|
53
|
+
}> {
|
|
54
|
+
const encryptedKey = await getSetting(SETTINGS_KEYS.OPENAI_AUTH_API_KEY);
|
|
55
|
+
if (encryptedKey) {
|
|
56
|
+
try {
|
|
57
|
+
return { apiKey: decrypt(encryptedKey), source: "db" };
|
|
58
|
+
} catch {
|
|
59
|
+
// Fall through to env lookup.
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (process.env.OPENAI_API_KEY) {
|
|
64
|
+
return { apiKey: process.env.OPENAI_API_KEY, source: "env" };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return { apiKey: null, source: "unknown" };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function getOpenAIAuthEnv(): Promise<Record<string, string> | undefined> {
|
|
71
|
+
const { apiKey } = await getOpenAIApiKey();
|
|
72
|
+
if (!apiKey) return undefined;
|
|
73
|
+
return { OPENAI_API_KEY: apiKey };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function updateOpenAIAuthStatus(
|
|
77
|
+
source: Extract<ApiKeySource, "db" | "env" | "unknown">
|
|
78
|
+
): Promise<void> {
|
|
79
|
+
await setSetting(SETTINGS_KEYS.OPENAI_AUTH_API_KEY_SOURCE, source);
|
|
80
|
+
}
|