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,102 @@
|
|
|
1
|
+
import { getSetting, setSetting } from "./helpers";
|
|
2
|
+
import { SETTINGS_KEYS } from "@/lib/constants/settings";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Get all saved permission patterns.
|
|
6
|
+
*/
|
|
7
|
+
export async function getAllowedPermissions(): Promise<string[]> {
|
|
8
|
+
const raw = await getSetting(SETTINGS_KEYS.PERMISSIONS_ALLOW);
|
|
9
|
+
if (!raw) return [];
|
|
10
|
+
try {
|
|
11
|
+
const parsed = JSON.parse(raw);
|
|
12
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
13
|
+
} catch {
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Add a permission pattern (no-op if duplicate).
|
|
20
|
+
*/
|
|
21
|
+
export async function addAllowedPermission(pattern: string): Promise<void> {
|
|
22
|
+
const current = await getAllowedPermissions();
|
|
23
|
+
if (current.includes(pattern)) return;
|
|
24
|
+
current.push(pattern);
|
|
25
|
+
await setSetting(SETTINGS_KEYS.PERMISSIONS_ALLOW, JSON.stringify(current));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Remove a permission pattern.
|
|
30
|
+
*/
|
|
31
|
+
export async function removeAllowedPermission(pattern: string): Promise<void> {
|
|
32
|
+
const current = await getAllowedPermissions();
|
|
33
|
+
const filtered = current.filter((p) => p !== pattern);
|
|
34
|
+
await setSetting(SETTINGS_KEYS.PERMISSIONS_ALLOW, JSON.stringify(filtered));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Check whether a tool invocation is pre-approved by any saved pattern.
|
|
39
|
+
*/
|
|
40
|
+
export async function isToolAllowed(
|
|
41
|
+
toolName: string,
|
|
42
|
+
input: Record<string, unknown>
|
|
43
|
+
): Promise<boolean> {
|
|
44
|
+
const patterns = await getAllowedPermissions();
|
|
45
|
+
return patterns.some((pattern) => matchesPermission(toolName, input, pattern));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Pure matching function — checks if a tool+input matches a permission pattern.
|
|
50
|
+
*
|
|
51
|
+
* Pattern formats:
|
|
52
|
+
* - "Read" — blanket allow for any Read invocation
|
|
53
|
+
* - "Bash(command:git *)" — allow Bash when command starts with "git "
|
|
54
|
+
* - "mcp__server__tool" — exact tool name match
|
|
55
|
+
*/
|
|
56
|
+
export function matchesPermission(
|
|
57
|
+
toolName: string,
|
|
58
|
+
input: Record<string, unknown>,
|
|
59
|
+
pattern: string
|
|
60
|
+
): boolean {
|
|
61
|
+
const parenIdx = pattern.indexOf("(");
|
|
62
|
+
|
|
63
|
+
// No constraint — bare tool name match
|
|
64
|
+
if (parenIdx === -1) {
|
|
65
|
+
return pattern === toolName;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const patternTool = pattern.slice(0, parenIdx);
|
|
69
|
+
if (patternTool !== toolName) return false;
|
|
70
|
+
|
|
71
|
+
// Parse constraint: "key:glob)"
|
|
72
|
+
const constraint = pattern.slice(parenIdx + 1, -1); // strip parens
|
|
73
|
+
const colonIdx = constraint.indexOf(":");
|
|
74
|
+
if (colonIdx === -1) return false;
|
|
75
|
+
|
|
76
|
+
const key = constraint.slice(0, colonIdx);
|
|
77
|
+
const glob = constraint.slice(colonIdx + 1);
|
|
78
|
+
const inputValue = String(input[key] ?? "");
|
|
79
|
+
|
|
80
|
+
if (glob.endsWith("*")) {
|
|
81
|
+
return inputValue.startsWith(glob.slice(0, -1));
|
|
82
|
+
}
|
|
83
|
+
return inputValue === glob;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Generate a suggested permission pattern from a tool invocation.
|
|
88
|
+
* Uses smart defaults — Bash gets granular patterns, others get blanket.
|
|
89
|
+
*/
|
|
90
|
+
export function buildPermissionPattern(
|
|
91
|
+
toolName: string,
|
|
92
|
+
input: Record<string, unknown>
|
|
93
|
+
): string {
|
|
94
|
+
if (toolName === "Bash" && typeof input.command === "string") {
|
|
95
|
+
const command = input.command;
|
|
96
|
+
const firstWord = command.split(/\s+/)[0];
|
|
97
|
+
return `Bash(command:${firstWord} *)`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Most tools are safe to blanket-allow
|
|
101
|
+
return toolName;
|
|
102
|
+
}
|
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
import { and, desc, eq, gte, inArray, lte } from "drizzle-orm";
|
|
2
|
+
import { db } from "@/lib/db";
|
|
3
|
+
import {
|
|
4
|
+
projects,
|
|
5
|
+
schedules,
|
|
6
|
+
tasks,
|
|
7
|
+
usageLedger,
|
|
8
|
+
workflows,
|
|
9
|
+
} from "@/lib/db/schema";
|
|
10
|
+
import { deriveUsageCostMicros } from "./pricing";
|
|
11
|
+
|
|
12
|
+
export type UsageActivityType =
|
|
13
|
+
| "task_run"
|
|
14
|
+
| "task_resume"
|
|
15
|
+
| "workflow_step"
|
|
16
|
+
| "scheduled_firing"
|
|
17
|
+
| "task_assist"
|
|
18
|
+
| "profile_test";
|
|
19
|
+
|
|
20
|
+
export type UsageLedgerStatus =
|
|
21
|
+
| "completed"
|
|
22
|
+
| "failed"
|
|
23
|
+
| "cancelled"
|
|
24
|
+
| "blocked"
|
|
25
|
+
| "unknown_pricing";
|
|
26
|
+
|
|
27
|
+
export interface UsageSnapshot {
|
|
28
|
+
modelId?: string | null;
|
|
29
|
+
inputTokens?: number | null;
|
|
30
|
+
outputTokens?: number | null;
|
|
31
|
+
totalTokens?: number | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface UsageLedgerWriteInput extends UsageSnapshot {
|
|
35
|
+
taskId?: string | null;
|
|
36
|
+
workflowId?: string | null;
|
|
37
|
+
scheduleId?: string | null;
|
|
38
|
+
projectId?: string | null;
|
|
39
|
+
activityType: UsageActivityType;
|
|
40
|
+
runtimeId: string;
|
|
41
|
+
providerId: string;
|
|
42
|
+
status: Exclude<UsageLedgerStatus, "unknown_pricing">;
|
|
43
|
+
startedAt: Date;
|
|
44
|
+
finishedAt: Date;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface UsageAuditEntry {
|
|
48
|
+
id: string;
|
|
49
|
+
activityType: UsageActivityType;
|
|
50
|
+
runtimeId: string;
|
|
51
|
+
providerId: string;
|
|
52
|
+
modelId: string | null;
|
|
53
|
+
status: UsageLedgerStatus;
|
|
54
|
+
inputTokens: number | null;
|
|
55
|
+
outputTokens: number | null;
|
|
56
|
+
totalTokens: number | null;
|
|
57
|
+
costMicros: number | null;
|
|
58
|
+
pricingVersion: string | null;
|
|
59
|
+
startedAt: Date;
|
|
60
|
+
finishedAt: Date;
|
|
61
|
+
taskId: string | null;
|
|
62
|
+
taskTitle: string | null;
|
|
63
|
+
workflowId: string | null;
|
|
64
|
+
workflowName: string | null;
|
|
65
|
+
scheduleId: string | null;
|
|
66
|
+
scheduleName: string | null;
|
|
67
|
+
projectId: string | null;
|
|
68
|
+
projectName: string | null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface ProviderModelBreakdownEntry {
|
|
72
|
+
providerId: string;
|
|
73
|
+
modelId: string | null;
|
|
74
|
+
runtimeId: string;
|
|
75
|
+
costMicros: number;
|
|
76
|
+
inputTokens: number;
|
|
77
|
+
outputTokens: number;
|
|
78
|
+
totalTokens: number;
|
|
79
|
+
runs: number;
|
|
80
|
+
unknownPricingRuns: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
84
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function parseInteger(value: unknown): number | null {
|
|
88
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
89
|
+
return Math.round(value);
|
|
90
|
+
}
|
|
91
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
92
|
+
const parsed = Number(value);
|
|
93
|
+
if (Number.isFinite(parsed)) {
|
|
94
|
+
return Math.round(parsed);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function mergeValue(
|
|
101
|
+
current: number | string | null | undefined,
|
|
102
|
+
next: number | string | null | undefined
|
|
103
|
+
) {
|
|
104
|
+
return current ?? next ?? null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function mergeUsageSnapshot(
|
|
108
|
+
current: UsageSnapshot,
|
|
109
|
+
next: UsageSnapshot
|
|
110
|
+
): UsageSnapshot {
|
|
111
|
+
return {
|
|
112
|
+
modelId: mergeValue(current.modelId, next.modelId) as string | null,
|
|
113
|
+
inputTokens: mergeValue(current.inputTokens, next.inputTokens) as number | null,
|
|
114
|
+
outputTokens: mergeValue(current.outputTokens, next.outputTokens) as number | null,
|
|
115
|
+
totalTokens: mergeValue(current.totalTokens, next.totalTokens) as number | null,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function extractUsageSnapshot(value: unknown): UsageSnapshot {
|
|
120
|
+
const snapshot: UsageSnapshot = {};
|
|
121
|
+
const visited = new Set<unknown>();
|
|
122
|
+
|
|
123
|
+
function visit(node: unknown, depth: number) {
|
|
124
|
+
if (depth > 6 || node == null || visited.has(node)) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
visited.add(node);
|
|
128
|
+
|
|
129
|
+
if (Array.isArray(node)) {
|
|
130
|
+
node.forEach((entry) => visit(entry, depth + 1));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!isRecord(node)) {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const modelId =
|
|
139
|
+
(typeof node.model === "string" ? node.model : null) ??
|
|
140
|
+
(typeof node.modelId === "string" ? node.modelId : null) ??
|
|
141
|
+
(typeof node.model_id === "string" ? node.model_id : null);
|
|
142
|
+
if (modelId && !snapshot.modelId) {
|
|
143
|
+
snapshot.modelId = modelId;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const inputTokens =
|
|
147
|
+
parseInteger(node.input_tokens) ??
|
|
148
|
+
parseInteger(node.inputTokens) ??
|
|
149
|
+
parseInteger(node.prompt_tokens) ??
|
|
150
|
+
parseInteger(node.promptTokens);
|
|
151
|
+
if (inputTokens !== null && snapshot.inputTokens == null) {
|
|
152
|
+
snapshot.inputTokens = inputTokens;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const outputTokens =
|
|
156
|
+
parseInteger(node.output_tokens) ??
|
|
157
|
+
parseInteger(node.outputTokens) ??
|
|
158
|
+
parseInteger(node.completion_tokens) ??
|
|
159
|
+
parseInteger(node.completionTokens);
|
|
160
|
+
if (outputTokens !== null && snapshot.outputTokens == null) {
|
|
161
|
+
snapshot.outputTokens = outputTokens;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const totalTokens =
|
|
165
|
+
parseInteger(node.total_tokens) ?? parseInteger(node.totalTokens);
|
|
166
|
+
if (totalTokens !== null && snapshot.totalTokens == null) {
|
|
167
|
+
snapshot.totalTokens = totalTokens;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
Object.values(node).forEach((child) => visit(child, depth + 1));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
visit(value, 0);
|
|
174
|
+
|
|
175
|
+
if (
|
|
176
|
+
snapshot.totalTokens == null &&
|
|
177
|
+
snapshot.inputTokens != null &&
|
|
178
|
+
snapshot.outputTokens != null
|
|
179
|
+
) {
|
|
180
|
+
snapshot.totalTokens = snapshot.inputTokens + snapshot.outputTokens;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return snapshot;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function resolveUsageActivityType(input: {
|
|
187
|
+
workflowId?: string | null;
|
|
188
|
+
scheduleId?: string | null;
|
|
189
|
+
isResume?: boolean;
|
|
190
|
+
}): UsageActivityType {
|
|
191
|
+
if (input.workflowId) {
|
|
192
|
+
return "workflow_step";
|
|
193
|
+
}
|
|
194
|
+
if (input.scheduleId) {
|
|
195
|
+
return "scheduled_firing";
|
|
196
|
+
}
|
|
197
|
+
return input.isResume ? "task_resume" : "task_run";
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export async function recordUsageLedgerEntry(input: UsageLedgerWriteInput) {
|
|
201
|
+
const normalizedInputTokens = input.inputTokens ?? null;
|
|
202
|
+
const normalizedOutputTokens = input.outputTokens ?? null;
|
|
203
|
+
const normalizedTotalTokens =
|
|
204
|
+
input.totalTokens ??
|
|
205
|
+
(normalizedInputTokens != null && normalizedOutputTokens != null
|
|
206
|
+
? normalizedInputTokens + normalizedOutputTokens
|
|
207
|
+
: null);
|
|
208
|
+
const { costMicros, pricingVersion } = deriveUsageCostMicros({
|
|
209
|
+
providerId: input.providerId,
|
|
210
|
+
modelId: input.modelId,
|
|
211
|
+
inputTokens: normalizedInputTokens,
|
|
212
|
+
outputTokens: normalizedOutputTokens,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
const resolvedCostMicros = input.status === "blocked" ? 0 : costMicros;
|
|
216
|
+
const resolvedPricingVersion =
|
|
217
|
+
input.status === "blocked" ? "budget-guardrail" : pricingVersion;
|
|
218
|
+
|
|
219
|
+
const status: UsageLedgerStatus =
|
|
220
|
+
input.status === "completed" &&
|
|
221
|
+
normalizedTotalTokens != null &&
|
|
222
|
+
resolvedCostMicros === null
|
|
223
|
+
? "unknown_pricing"
|
|
224
|
+
: input.status;
|
|
225
|
+
|
|
226
|
+
const row = {
|
|
227
|
+
id: crypto.randomUUID(),
|
|
228
|
+
taskId: input.taskId ?? null,
|
|
229
|
+
workflowId: input.workflowId ?? null,
|
|
230
|
+
scheduleId: input.scheduleId ?? null,
|
|
231
|
+
projectId: input.projectId ?? null,
|
|
232
|
+
activityType: input.activityType,
|
|
233
|
+
runtimeId: input.runtimeId,
|
|
234
|
+
providerId: input.providerId,
|
|
235
|
+
modelId: input.modelId ?? null,
|
|
236
|
+
status,
|
|
237
|
+
inputTokens: normalizedInputTokens,
|
|
238
|
+
outputTokens: normalizedOutputTokens,
|
|
239
|
+
totalTokens: normalizedTotalTokens,
|
|
240
|
+
costMicros: resolvedCostMicros,
|
|
241
|
+
pricingVersion: resolvedPricingVersion,
|
|
242
|
+
startedAt: input.startedAt,
|
|
243
|
+
finishedAt: input.finishedAt,
|
|
244
|
+
} as const;
|
|
245
|
+
|
|
246
|
+
await db.insert(usageLedger).values(row);
|
|
247
|
+
return row;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function startOfWindow(days: number) {
|
|
251
|
+
const now = new Date();
|
|
252
|
+
const start = new Date(now);
|
|
253
|
+
start.setHours(0, 0, 0, 0);
|
|
254
|
+
start.setDate(start.getDate() - (days - 1));
|
|
255
|
+
return start;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function formatLocalDay(date: Date) {
|
|
259
|
+
return new Intl.DateTimeFormat("en-CA", {
|
|
260
|
+
year: "numeric",
|
|
261
|
+
month: "2-digit",
|
|
262
|
+
day: "2-digit",
|
|
263
|
+
}).format(date);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export async function getDailySpendTotals(days = 7) {
|
|
267
|
+
const rows = await db
|
|
268
|
+
.select()
|
|
269
|
+
.from(usageLedger)
|
|
270
|
+
.where(gte(usageLedger.finishedAt, startOfWindow(days)))
|
|
271
|
+
.orderBy(usageLedger.finishedAt);
|
|
272
|
+
|
|
273
|
+
const totals = new Map<string, number>();
|
|
274
|
+
rows.forEach((row) => {
|
|
275
|
+
const day = formatLocalDay(row.finishedAt);
|
|
276
|
+
totals.set(day, (totals.get(day) ?? 0) + (row.costMicros ?? 0));
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
return Array.from(totals.entries()).map(([day, costMicros]) => ({
|
|
280
|
+
day,
|
|
281
|
+
costMicros,
|
|
282
|
+
}));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export async function getDailyTokenTotals(days = 7) {
|
|
286
|
+
const rows = await db
|
|
287
|
+
.select()
|
|
288
|
+
.from(usageLedger)
|
|
289
|
+
.where(gte(usageLedger.finishedAt, startOfWindow(days)))
|
|
290
|
+
.orderBy(usageLedger.finishedAt);
|
|
291
|
+
|
|
292
|
+
const totals = new Map<
|
|
293
|
+
string,
|
|
294
|
+
{ inputTokens: number; outputTokens: number; totalTokens: number }
|
|
295
|
+
>();
|
|
296
|
+
|
|
297
|
+
rows.forEach((row) => {
|
|
298
|
+
const day = formatLocalDay(row.finishedAt);
|
|
299
|
+
const bucket = totals.get(day) ?? {
|
|
300
|
+
inputTokens: 0,
|
|
301
|
+
outputTokens: 0,
|
|
302
|
+
totalTokens: 0,
|
|
303
|
+
};
|
|
304
|
+
bucket.inputTokens += row.inputTokens ?? 0;
|
|
305
|
+
bucket.outputTokens += row.outputTokens ?? 0;
|
|
306
|
+
bucket.totalTokens += row.totalTokens ?? 0;
|
|
307
|
+
totals.set(day, bucket);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
return Array.from(totals.entries()).map(([day, values]) => ({
|
|
311
|
+
day,
|
|
312
|
+
...values,
|
|
313
|
+
}));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export async function getProviderModelBreakdown(options?: {
|
|
317
|
+
startedAt?: Date;
|
|
318
|
+
finishedAt?: Date;
|
|
319
|
+
}): Promise<ProviderModelBreakdownEntry[]> {
|
|
320
|
+
const conditions = [];
|
|
321
|
+
if (options?.startedAt) {
|
|
322
|
+
conditions.push(gte(usageLedger.finishedAt, options.startedAt));
|
|
323
|
+
}
|
|
324
|
+
if (options?.finishedAt) {
|
|
325
|
+
conditions.push(lte(usageLedger.finishedAt, options.finishedAt));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const rows = await db
|
|
329
|
+
.select()
|
|
330
|
+
.from(usageLedger)
|
|
331
|
+
.where(conditions.length ? and(...conditions) : undefined);
|
|
332
|
+
|
|
333
|
+
const totals = new Map<
|
|
334
|
+
string,
|
|
335
|
+
{
|
|
336
|
+
providerId: string;
|
|
337
|
+
modelId: string | null;
|
|
338
|
+
runtimeId: string;
|
|
339
|
+
costMicros: number;
|
|
340
|
+
inputTokens: number;
|
|
341
|
+
outputTokens: number;
|
|
342
|
+
totalTokens: number;
|
|
343
|
+
runs: number;
|
|
344
|
+
unknownPricingRuns: number;
|
|
345
|
+
}
|
|
346
|
+
>();
|
|
347
|
+
|
|
348
|
+
rows.forEach((row) => {
|
|
349
|
+
const key = `${row.providerId}::${row.modelId ?? "unknown"}::${row.runtimeId}`;
|
|
350
|
+
const bucket = totals.get(key) ?? {
|
|
351
|
+
providerId: row.providerId,
|
|
352
|
+
modelId: row.modelId ?? null,
|
|
353
|
+
runtimeId: row.runtimeId,
|
|
354
|
+
costMicros: 0,
|
|
355
|
+
inputTokens: 0,
|
|
356
|
+
outputTokens: 0,
|
|
357
|
+
totalTokens: 0,
|
|
358
|
+
runs: 0,
|
|
359
|
+
unknownPricingRuns: 0,
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
bucket.costMicros += row.costMicros ?? 0;
|
|
363
|
+
bucket.inputTokens += row.inputTokens ?? 0;
|
|
364
|
+
bucket.outputTokens += row.outputTokens ?? 0;
|
|
365
|
+
bucket.totalTokens += row.totalTokens ?? 0;
|
|
366
|
+
bucket.runs += 1;
|
|
367
|
+
if (row.status === "unknown_pricing") {
|
|
368
|
+
bucket.unknownPricingRuns += 1;
|
|
369
|
+
}
|
|
370
|
+
totals.set(key, bucket);
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
return Array.from(totals.values()).sort(
|
|
374
|
+
(left, right) => right.costMicros - left.costMicros
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export async function listUsageAuditEntries(options?: {
|
|
379
|
+
limit?: number;
|
|
380
|
+
offset?: number;
|
|
381
|
+
statuses?: UsageLedgerStatus[];
|
|
382
|
+
activityTypes?: UsageActivityType[];
|
|
383
|
+
runtimeIds?: string[];
|
|
384
|
+
startedAt?: Date;
|
|
385
|
+
finishedAt?: Date;
|
|
386
|
+
}) {
|
|
387
|
+
const conditions = [];
|
|
388
|
+
if (options?.statuses?.length) {
|
|
389
|
+
conditions.push(inArray(usageLedger.status, options.statuses));
|
|
390
|
+
}
|
|
391
|
+
if (options?.activityTypes?.length) {
|
|
392
|
+
conditions.push(inArray(usageLedger.activityType, options.activityTypes));
|
|
393
|
+
}
|
|
394
|
+
if (options?.runtimeIds?.length) {
|
|
395
|
+
conditions.push(inArray(usageLedger.runtimeId, options.runtimeIds));
|
|
396
|
+
}
|
|
397
|
+
if (options?.startedAt) {
|
|
398
|
+
conditions.push(gte(usageLedger.finishedAt, options.startedAt));
|
|
399
|
+
}
|
|
400
|
+
if (options?.finishedAt) {
|
|
401
|
+
conditions.push(lte(usageLedger.finishedAt, options.finishedAt));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const rows = await db
|
|
405
|
+
.select()
|
|
406
|
+
.from(usageLedger)
|
|
407
|
+
.where(conditions.length ? and(...conditions) : undefined)
|
|
408
|
+
.orderBy(desc(usageLedger.finishedAt));
|
|
409
|
+
|
|
410
|
+
const pagedRows = rows.slice(
|
|
411
|
+
options?.offset ?? 0,
|
|
412
|
+
(options?.offset ?? 0) + (options?.limit ?? 50)
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
const taskIds = Array.from(
|
|
416
|
+
new Set(pagedRows.map((row) => row.taskId).filter(Boolean))
|
|
417
|
+
) as string[];
|
|
418
|
+
const workflowIds = Array.from(
|
|
419
|
+
new Set(pagedRows.map((row) => row.workflowId).filter(Boolean))
|
|
420
|
+
) as string[];
|
|
421
|
+
const scheduleIds = Array.from(
|
|
422
|
+
new Set(pagedRows.map((row) => row.scheduleId).filter(Boolean))
|
|
423
|
+
) as string[];
|
|
424
|
+
const projectIds = Array.from(
|
|
425
|
+
new Set(pagedRows.map((row) => row.projectId).filter(Boolean))
|
|
426
|
+
) as string[];
|
|
427
|
+
|
|
428
|
+
const [taskRows, workflowRows, scheduleRows, projectRows] = await Promise.all([
|
|
429
|
+
taskIds.length
|
|
430
|
+
? db
|
|
431
|
+
.select({ id: tasks.id, title: tasks.title })
|
|
432
|
+
.from(tasks)
|
|
433
|
+
.where(inArray(tasks.id, taskIds))
|
|
434
|
+
: Promise.resolve([]),
|
|
435
|
+
workflowIds.length
|
|
436
|
+
? db
|
|
437
|
+
.select({ id: workflows.id, name: workflows.name })
|
|
438
|
+
.from(workflows)
|
|
439
|
+
.where(inArray(workflows.id, workflowIds))
|
|
440
|
+
: Promise.resolve([]),
|
|
441
|
+
scheduleIds.length
|
|
442
|
+
? db
|
|
443
|
+
.select({ id: schedules.id, name: schedules.name })
|
|
444
|
+
.from(schedules)
|
|
445
|
+
.where(inArray(schedules.id, scheduleIds))
|
|
446
|
+
: Promise.resolve([]),
|
|
447
|
+
projectIds.length
|
|
448
|
+
? db
|
|
449
|
+
.select({ id: projects.id, name: projects.name })
|
|
450
|
+
.from(projects)
|
|
451
|
+
.where(inArray(projects.id, projectIds))
|
|
452
|
+
: Promise.resolve([]),
|
|
453
|
+
]);
|
|
454
|
+
|
|
455
|
+
const taskMap = new Map(taskRows.map((row) => [row.id, row.title]));
|
|
456
|
+
const workflowMap = new Map(workflowRows.map((row) => [row.id, row.name]));
|
|
457
|
+
const scheduleMap = new Map(scheduleRows.map((row) => [row.id, row.name]));
|
|
458
|
+
const projectMap = new Map(projectRows.map((row) => [row.id, row.name]));
|
|
459
|
+
|
|
460
|
+
return pagedRows.map(
|
|
461
|
+
(row): UsageAuditEntry => ({
|
|
462
|
+
id: row.id,
|
|
463
|
+
activityType: row.activityType,
|
|
464
|
+
runtimeId: row.runtimeId,
|
|
465
|
+
providerId: row.providerId,
|
|
466
|
+
modelId: row.modelId ?? null,
|
|
467
|
+
status: row.status,
|
|
468
|
+
inputTokens: row.inputTokens ?? null,
|
|
469
|
+
outputTokens: row.outputTokens ?? null,
|
|
470
|
+
totalTokens: row.totalTokens ?? null,
|
|
471
|
+
costMicros: row.costMicros ?? null,
|
|
472
|
+
pricingVersion: row.pricingVersion ?? null,
|
|
473
|
+
startedAt: row.startedAt,
|
|
474
|
+
finishedAt: row.finishedAt,
|
|
475
|
+
taskId: row.taskId ?? null,
|
|
476
|
+
taskTitle: row.taskId ? taskMap.get(row.taskId) ?? null : null,
|
|
477
|
+
workflowId: row.workflowId ?? null,
|
|
478
|
+
workflowName: row.workflowId
|
|
479
|
+
? workflowMap.get(row.workflowId) ?? null
|
|
480
|
+
: null,
|
|
481
|
+
scheduleId: row.scheduleId ?? null,
|
|
482
|
+
scheduleName: row.scheduleId
|
|
483
|
+
? scheduleMap.get(row.scheduleId) ?? null
|
|
484
|
+
: null,
|
|
485
|
+
projectId: row.projectId ?? null,
|
|
486
|
+
projectName: row.projectId ? projectMap.get(row.projectId) ?? null : null,
|
|
487
|
+
})
|
|
488
|
+
);
|
|
489
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export interface PricingRule {
|
|
2
|
+
providerId: "anthropic" | "openai";
|
|
3
|
+
pricingVersion: string;
|
|
4
|
+
inputCostPerMillionMicros: number;
|
|
5
|
+
outputCostPerMillionMicros: number;
|
|
6
|
+
matchesModel(modelId: string): boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const PRICING_RULES: PricingRule[] = [
|
|
10
|
+
{
|
|
11
|
+
providerId: "anthropic",
|
|
12
|
+
pricingVersion: "registry-2026-03-12",
|
|
13
|
+
inputCostPerMillionMicros: 3_000_000,
|
|
14
|
+
outputCostPerMillionMicros: 15_000_000,
|
|
15
|
+
matchesModel(modelId) {
|
|
16
|
+
return (
|
|
17
|
+
modelId === "claude-sonnet-4-20250514" ||
|
|
18
|
+
modelId.startsWith("claude-sonnet-4")
|
|
19
|
+
);
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
providerId: "openai",
|
|
24
|
+
pricingVersion: "registry-2026-03-12",
|
|
25
|
+
inputCostPerMillionMicros: 1_500_000,
|
|
26
|
+
outputCostPerMillionMicros: 6_000_000,
|
|
27
|
+
matchesModel(modelId) {
|
|
28
|
+
return modelId === "codex-mini-latest" || modelId.startsWith("codex-mini");
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
export interface DerivedCost {
|
|
34
|
+
costMicros: number | null;
|
|
35
|
+
pricingVersion: string | null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function deriveUsageCostMicros(input: {
|
|
39
|
+
providerId: string;
|
|
40
|
+
modelId?: string | null;
|
|
41
|
+
inputTokens?: number | null;
|
|
42
|
+
outputTokens?: number | null;
|
|
43
|
+
}): DerivedCost {
|
|
44
|
+
if (!input.modelId) {
|
|
45
|
+
return { costMicros: null, pricingVersion: null };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const rule = PRICING_RULES.find(
|
|
49
|
+
(entry) =>
|
|
50
|
+
entry.providerId === input.providerId && entry.matchesModel(input.modelId!)
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
if (!rule) {
|
|
54
|
+
return { costMicros: null, pricingVersion: null };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const inputTokens = input.inputTokens ?? 0;
|
|
58
|
+
const outputTokens = input.outputTokens ?? 0;
|
|
59
|
+
const inputCost =
|
|
60
|
+
(inputTokens * rule.inputCostPerMillionMicros) / 1_000_000;
|
|
61
|
+
const outputCost =
|
|
62
|
+
(outputTokens * rule.outputCostPerMillionMicros) / 1_000_000;
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
costMicros: Math.round(inputCost + outputCost),
|
|
66
|
+
pricingVersion: rule.pricingVersion,
|
|
67
|
+
};
|
|
68
|
+
}
|