Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

eric.hayes/macro-1882-ai-usage (#4143)

Eric Hayesb37532636194
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index f60c8f1e46..c2ab39e5cf 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -4,11 +4,14 @@
"agent": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"macro_user_id",
+ "macro_uuid",
"model-entity",
"model_file_type",
+ "model_user",
"non_empty",
"workspace-hack"
],
@@ -16,6 +19,7 @@
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anthropic",
"attachment",
"authentication_service_client",
@@ -113,6 +117,14 @@
"macro_user_id",
"workspace-hack"
],
+ "ai_usage": [
+ "ai_usage",
+ "cowlike",
+ "macro_user_id",
+ "macro_uuid",
+ "model_user",
+ "workspace-hack"
+ ],
"analytics_client": [
"analytics_client",
"workspace-hack"
@@ -136,6 +148,7 @@
"authentication_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"analytics_client",
"attachment",
"authentication_service",
@@ -234,6 +247,7 @@
"authentication_service_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -242,6 +256,7 @@
"frecency",
"item_filters",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -269,6 +284,7 @@
"bots": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"bot_id",
@@ -338,6 +354,7 @@
"call": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"call",
"comms",
@@ -389,6 +406,7 @@
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anthropic",
"attachment",
"authentication_service_client",
@@ -484,6 +502,7 @@
"channels": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"bot_id",
@@ -546,6 +565,7 @@
"chat": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"chat",
"cowlike",
@@ -575,6 +595,7 @@
"comms": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"comms",
"cowlike",
@@ -584,6 +605,7 @@
"frecency",
"item_filters",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -600,6 +622,7 @@
"comms_db_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"comms_db_client",
"cowlike",
@@ -624,6 +647,7 @@
"connection": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"connection",
"connection_gateway_client",
@@ -635,6 +659,7 @@
"frecency",
"item_filters",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -650,6 +675,7 @@
"connection_gateway": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"connection_gateway",
"connection_gateway_client",
@@ -711,6 +737,7 @@
"contacts": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"contacts",
"cowlike",
@@ -753,6 +780,7 @@
"contacts_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"contacts",
"contacts_service",
@@ -804,6 +832,7 @@
"convert_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"convert_service",
@@ -867,6 +896,7 @@
"crm": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"crm",
@@ -928,6 +958,7 @@
"deleted_item_poller": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -975,6 +1006,7 @@
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anthropic",
"attachment",
"authentication_service_client",
@@ -1080,6 +1112,7 @@
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"analytics_client",
"anthropic",
"attachment",
@@ -1193,6 +1226,7 @@
"document_storage_service_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_storage_service_client",
@@ -1201,6 +1235,7 @@
"frecency",
"item_filters",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -1220,6 +1255,7 @@
"document_text_extractor": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -1232,6 +1268,7 @@
"macro_env",
"macro_env_var",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -1248,6 +1285,7 @@
"document_upload_finalizer_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -1321,6 +1359,7 @@
"documents": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -1393,6 +1432,7 @@
"docx_unzip_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -1450,6 +1490,7 @@
"email": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -1521,6 +1562,7 @@
"email_refresh_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -1558,6 +1600,7 @@
"email_scheduled_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -1595,6 +1638,7 @@
"email_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"connection_gateway_client",
@@ -1665,6 +1709,7 @@
"email_service_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -1696,6 +1741,7 @@
"email_sfs_delete_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -1733,6 +1779,7 @@
"email_suppression_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -1785,6 +1832,7 @@
"entity_access": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -1793,6 +1841,7 @@
"frecency",
"item_filters",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -1835,6 +1884,7 @@
"foreign_entity": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -1878,6 +1928,7 @@
"github": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -1973,6 +2024,7 @@
"image_proxy_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"decode_jwt",
@@ -2062,6 +2114,7 @@
"lexical_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -2175,6 +2228,7 @@
"macro_db_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -2226,6 +2280,7 @@
"macro_middleware": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"decode_jwt",
@@ -2279,6 +2334,7 @@
"macro_sha_count_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -2287,6 +2343,7 @@
"item_filters",
"macro_sha_count_client",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -2326,10 +2383,12 @@
"mcp_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"macro_env_var",
"macro_user_id",
+ "macro_uuid",
"mcp_client",
"model-entity",
"model-error-response",
@@ -2342,6 +2401,7 @@
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anthropic",
"attachment",
"authentication_service_client",
@@ -2440,6 +2500,7 @@
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anthropic",
"attachment",
"authentication_service_client",
@@ -2545,6 +2606,7 @@
"model": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -2552,6 +2614,7 @@
"frecency",
"item_filters",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -2672,6 +2735,7 @@
"models_search": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -2734,6 +2798,7 @@
"models_soup": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -2892,6 +2957,7 @@
"notification_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"decode_jwt",
@@ -2961,6 +3027,7 @@
"organization_retention_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -2998,6 +3065,7 @@
"organization_retention_trigger": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -3039,6 +3107,7 @@
"properties": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"decode_jwt",
@@ -3094,6 +3163,7 @@
"properties_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"decode_jwt",
@@ -3205,6 +3275,7 @@
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anthropic",
"attachment",
"authentication_service_client",
@@ -3302,6 +3373,7 @@
"search_processing_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -3377,6 +3449,7 @@
"search_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -3445,6 +3518,7 @@
"search_service_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -3500,6 +3574,7 @@
"search_upload_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -3546,6 +3621,7 @@
"seed_cli": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"comms_db_client",
"cowlike",
@@ -3620,6 +3696,7 @@
"soup": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -3674,6 +3751,7 @@
"sqs_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -3720,6 +3798,7 @@
"static_file_service": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"decode_jwt",
@@ -3782,6 +3861,7 @@
"sync_service_client": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
@@ -3789,6 +3869,7 @@
"frecency",
"item_filters",
"macro_user_id",
+ "macro_uuid",
"model",
"model-entity",
"model-error-response",
@@ -3814,6 +3895,7 @@
"task_dedup": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"call",
@@ -3880,6 +3962,7 @@
"teams": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -3939,6 +4022,7 @@
"upload_extractor_lambda_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"connection_gateway_client",
@@ -3981,6 +4065,7 @@
"upload_extractor_lambda_trigger": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"authentication_service_client",
"cowlike",
@@ -4019,6 +4104,7 @@
"user_link_cleanup_handler": [
"agent",
"ai_toolset",
+ "ai_usage",
"attachment",
"cowlike",
"document_sub_type",
diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.ts
index 07cec76b58..605bc161cf 100644
--- a/js/app/packages/service-clients/service-cognition/generated/client.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts
@@ -14,6 +14,7 @@ import type {
CreateChatRequest,
DeleteMcpServerParams,
DocumentTextPart,
+ ErrorBody,
ErrorResponse,
GetBatchPreviewRequest,
GetBatchPreviewResponse,
@@ -29,6 +30,7 @@ import type {
RejectToolCallRequest,
SendChatMessageResponse,
ServerResponse,
+ SetPricingRequest,
StartAuthRequest,
StartAuthResponse,
StopChatStreamError,
@@ -41,8 +43,130 @@ import type {
UpdateServerRequest,
UpdateToolCallRequest,
UpdateToolResponseRequest,
+ UsageRequest,
+ UsageSummary,
} from './schemas';
+/**
+ * @summary Set the pricing for a model and recompute its recorded rows. Admin only.
+ */
+export type setPricingHandlerResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type setPricingHandlerResponse403 = {
+ data: ErrorBody;
+ status: 403;
+};
+
+export type setPricingHandlerResponse500 = {
+ data: ErrorBody;
+ status: 500;
+};
+
+export type setPricingHandlerResponseSuccess = setPricingHandlerResponse200 & {
+ headers: Headers;
+};
+export type setPricingHandlerResponseError = (
+ | setPricingHandlerResponse403
+ | setPricingHandlerResponse500
+) & {
+ headers: Headers;
+};
+
+export type setPricingHandlerResponse =
+ | setPricingHandlerResponseSuccess
+ | setPricingHandlerResponseError;
+
+export const getSetPricingHandlerUrl = () => {
+ return `/ai-cost/pricing`;
+};
+
+export const setPricingHandler = async (
+ setPricingRequest: SetPricingRequest,
+ options?: RequestInit
+): Promise<setPricingHandlerResponse> => {
+ const res = await fetch(getSetPricingHandlerUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(setPricingRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: setPricingHandlerResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as setPricingHandlerResponse;
+};
+
+/**
+ * @summary Query recorded AI usage. Admin only.
+ */
+export type getUsageHandlerResponse200 = {
+ data: UsageSummary;
+ status: 200;
+};
+
+export type getUsageHandlerResponse400 = {
+ data: ErrorBody;
+ status: 400;
+};
+
+export type getUsageHandlerResponse403 = {
+ data: ErrorBody;
+ status: 403;
+};
+
+export type getUsageHandlerResponse500 = {
+ data: ErrorBody;
+ status: 500;
+};
+
+export type getUsageHandlerResponseSuccess = getUsageHandlerResponse200 & {
+ headers: Headers;
+};
+export type getUsageHandlerResponseError = (
+ | getUsageHandlerResponse400
+ | getUsageHandlerResponse403
+ | getUsageHandlerResponse500
+) & {
+ headers: Headers;
+};
+
+export type getUsageHandlerResponse =
+ | getUsageHandlerResponseSuccess
+ | getUsageHandlerResponseError;
+
+export const getGetUsageHandlerUrl = () => {
+ return `/ai-cost/usage`;
+};
+
+export const getUsageHandler = async (
+ usageRequest: UsageRequest,
+ options?: RequestInit
+): Promise<getUsageHandlerResponse> => {
+ const res = await fetch(getGetUsageHandlerUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(usageRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getUsageHandlerResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getUsageHandlerResponse;
+};
+
export type getChatsForAttachmentHandlerResponse200 = {
data: GetChatsForAttachmentResponse;
status: 200;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/aiFeature.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/aiFeature.ts
new file mode 100644
index 0000000000..9ffe6b9cb2
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/aiFeature.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Everything we use AI for. The wire / DB form of each variant is its
+`snake_case` name.
+ */
+export type AiFeature = (typeof AiFeature)[keyof typeof AiFeature];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AiFeature = {
+ chat: 'chat',
+ memory: 'memory',
+ automation: 'automation',
+ dynamic_completions_api: 'dynamic_completions_api',
+ chat_rename: 'chat_rename',
+ call_summary: 'call_summary',
+ channel_bot: 'channel_bot',
+} as const;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/completionUsage.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/completionUsage.ts
new file mode 100644
index 0000000000..dd5ab30403
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/completionUsage.ts
@@ -0,0 +1,26 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+import type { AiFeature } from './aiFeature';
+import type { CompletionUsageEntity } from './completionUsageEntity';
+import type { MacroUserIdStr } from './macroUserIdStr';
+import type { Usage } from './usage';
+
+/**
+ * A recorded completion: who, what feature, optional entity, and the cost.
+ */
+export interface CompletionUsage {
+ /** Token usage and cost. */
+ cost: Usage;
+ /** The entity the completion related to, if any. */
+ entity?: CompletionUsageEntity;
+ /** The feature that performed the completion. */
+ feature: AiFeature;
+ /** The user the completion was performed for (the [system user](SYSTEM_USER_ID)
+for background work). */
+ user: MacroUserIdStr;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/completionUsageEntity.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/completionUsageEntity.ts
new file mode 100644
index 0000000000..d4d73acf11
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/completionUsageEntity.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * The entity the completion related to, if any.
+ */
+export type CompletionUsageEntity = string | null;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/errorBody.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/errorBody.ts
new file mode 100644
index 0000000000..0294c8c00e
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/errorBody.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Error response body.
+ */
+export interface ErrorBody {
+ /** Human-readable error description. */
+ error: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/featureUsage.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/featureUsage.ts
new file mode 100644
index 0000000000..d599cfc1a5
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/featureUsage.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+import type { AiFeature } from './aiFeature';
+import type { CompletionUsage } from './completionUsage';
+
+/**
+ * Usage for a single feature, with its rolled-up dollar total.
+ */
+export interface FeatureUsage {
+ /** The individual completions recorded for this feature. */
+ entries: CompletionUsage[];
+ /** The feature. */
+ feature: AiFeature;
+ /** Total cost across `entries` (USD). */
+ total: number;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
index 460e0ac5d8..821e7d1b94 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
@@ -7,6 +7,7 @@
export * from './accessLevel';
export * from './addServerRequest';
+export * from './aiFeature';
export * from './assistantMessagePart';
export * from './assistantMessagePartOneOf';
export * from './assistantMessagePartOneOfEight';
@@ -82,6 +83,8 @@ export * from './chatStreamOneOfSix';
export * from './chatStreamOneOfSixType';
export * from './chatTokenCount';
export * from './chatUpdatedAt';
+export * from './completionUsage';
+export * from './completionUsageEntity';
export * from './conversationRecord';
export * from './createChatRequest';
export * from './createChatRequestName';
@@ -97,7 +100,9 @@ export * from './dynamicSchema';
export * from './dynamicSchemaDescription';
export * from './entity';
export * from './entityType';
+export * from './errorBody';
export * from './errorResponse';
+export * from './featureUsage';
export * from './fileType';
export * from './genericErrorResponse';
export * from './getBatchPreviewRequest';
@@ -111,6 +116,7 @@ export * from './httpSendChatMessageRequestAdditionalInstructions';
export * from './httpSendChatMessageRequestAttachments';
export * from './httpSendChatMessageRequestChatId';
export * from './jwtPayload';
+export * from './macroUserIdStr';
export * from './mcpAuthCallbackParams';
export * from './memoryErrorBody';
export * from './memoryResponse';
@@ -126,6 +132,7 @@ export * from './patchChatRequest';
export * from './patchChatRequestName';
export * from './patchChatRequestProjectId';
export * from './patchChatRequestSharePermission';
+export * from './price';
export * from './rejectToolCallRequest';
export * from './role';
export * from './sendChatMessagePayload';
@@ -134,6 +141,7 @@ export * from './sendChatMessagePayloadAllOfAdditionalInstructions';
export * from './sendChatMessagePayloadAllOfAttachments';
export * from './sendChatMessageResponse';
export * from './serverResponse';
+export * from './setPricingRequest';
export * from './sharePermissionV2';
export * from './sharePermissionV2ChannelSharePermissions';
export * from './sharePermissionV2PublicAccessLevel';
@@ -171,6 +179,12 @@ export * from './updateSharePermissionRequestV2IsPublic';
export * from './updateSharePermissionRequestV2PublicAccessLevel';
export * from './updateToolCallRequest';
export * from './updateToolResponseRequest';
+export * from './usage';
+export * from './usagePrice';
+export * from './usageRequest';
+export * from './usageRequestFrom';
+export * from './usageRequestUntil';
+export * from './usageSummary';
export * from './userPdfRect';
export * from './userToolResponseValue';
export * from './userToolResponseValueOneOf';
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/macroUserIdStr.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/macroUserIdStr.ts
new file mode 100644
index 0000000000..378ed9207f
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/macroUserIdStr.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+export type MacroUserIdStr = string;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/price.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/price.ts
new file mode 100644
index 0000000000..38ca8cefee
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/price.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Resolved price for one completion.
+ */
+export interface Price {
+ /** Price per million input tokens (USD). */
+ price_per_million_in: number;
+ /** Price per million output tokens (USD). */
+ price_per_million_out: number;
+ /** Total cost of the completion (USD). */
+ total: number;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/setPricingRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/setPricingRequest.ts
new file mode 100644
index 0000000000..ac92a4d7d2
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/setPricingRequest.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Request body for [`set_pricing_handler`].
+ */
+export interface SetPricingRequest {
+ /** The model api id to (re)price. */
+ model: string;
+ /** New price per million input tokens (USD). */
+ price_per_mil_in: number;
+ /** New price per million output tokens (USD). */
+ price_per_mil_out: number;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/usage.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/usage.ts
new file mode 100644
index 0000000000..d229e92d4a
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/usage.ts
@@ -0,0 +1,28 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { UsagePrice } from './usagePrice';
+
+/**
+ * The token usage and resolved cost of a single completion.
+ */
+export interface Usage {
+ /** When the completion was recorded. */
+ created_at: string;
+ /**
+ * Tokens consumed by the input.
+ * @minimum 0
+ */
+ input_tokens: number;
+ /** The model api id (e.g. `claude-opus-4-8`). */
+ model: string;
+ /**
+ * Tokens generated in the output.
+ * @minimum 0
+ */
+ output_tokens: number;
+ price?: UsagePrice;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/usagePrice.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/usagePrice.ts
new file mode 100644
index 0000000000..4ccffd5577
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/usagePrice.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { Price } from './price';
+
+export type UsagePrice = null | Price;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequest.ts
new file mode 100644
index 0000000000..6cce241021
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequest.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { AiFeature } from './aiFeature';
+import type { UsageRequestFrom } from './usageRequestFrom';
+import type { UsageRequestUntil } from './usageRequestUntil';
+
+/**
+ * Request body for [`get_usage_handler`].
+ */
+export interface UsageRequest {
+ /** If empty, include all features. */
+ features?: AiFeature[];
+ /** Inclusive lower bound on `created_at`. */
+ from?: UsageRequestFrom;
+ /** If empty, include all users. */
+ include_users?: string[];
+ /** Exclusive upper bound on `created_at`. */
+ until?: UsageRequestUntil;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequestFrom.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequestFrom.ts
new file mode 100644
index 0000000000..d176f95d78
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequestFrom.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Inclusive lower bound on `created_at`.
+ */
+export type UsageRequestFrom = string | null;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequestUntil.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequestUntil.ts
new file mode 100644
index 0000000000..b9a9dc7e29
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/usageRequestUntil.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Exclusive upper bound on `created_at`.
+ */
+export type UsageRequestUntil = string | null;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/usageSummary.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/usageSummary.ts
new file mode 100644
index 0000000000..6985e37152
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/usageSummary.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { FeatureUsage } from './featureUsage';
+
+/**
+ * The result of a usage query: per-feature breakdown plus a grand total.
+ */
+export interface UsageSummary {
+ /** Per-feature usage. */
+ entries: FeatureUsage[];
+ /** Grand total cost across all features (USD). */
+ total: number;
+}
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index 116b36712c..bbf788930b 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -11,6 +11,107 @@
"version": "1.0.0"
},
"paths": {
+ "/ai-cost/pricing": {
+ "post": {
+ "tags": ["ai_usage"],
+ "summary": "Set the pricing for a model and recompute its recorded rows. Admin only.",
+ "operationId": "set_pricing_handler",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetPricingRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Pricing updated"
+ },
+ "403": {
+ "description": "Admin access required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorBody"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/ai-cost/usage": {
+ "post": {
+ "tags": ["ai_usage"],
+ "summary": "Query recorded AI usage. Admin only.",
+ "operationId": "get_usage_handler",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UsageRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Usage summary",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UsageSummary"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorBody"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Admin access required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorBody"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/attachments/{attachment_id}/chats": {
"get": {
"tags": ["get_chats_for_attachment"],
@@ -1439,6 +1540,19 @@
}
}
},
+ "AiFeature": {
+ "type": "string",
+ "description": "Everything we use AI for. The wire / DB form of each variant is its\n`snake_case` name.",
+ "enum": [
+ "chat",
+ "memory",
+ "automation",
+ "dynamic_completions_api",
+ "chat_rename",
+ "call_summary",
+ "channel_bot"
+ ]
+ },
"AssistantMessagePart": {
"oneOf": [
{
@@ -2098,6 +2212,30 @@
}
]
},
+ "CompletionUsage": {
+ "type": "object",
+ "description": "A recorded completion: who, what feature, optional entity, and the cost.",
+ "required": ["feature", "user", "cost"],
+ "properties": {
+ "cost": {
+ "$ref": "#/components/schemas/Usage",
+ "description": "Token usage and cost."
+ },
+ "entity": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The entity the completion related to, if any."
+ },
+ "feature": {
+ "$ref": "#/components/schemas/AiFeature",
+ "description": "The feature that performed the completion."
+ },
+ "user": {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "The user the completion was performed for (the [system user](SYSTEM_USER_ID)\nfor background work)."
+ }
+ }
+ },
"ConversationRecord": {
"type": "object",
"required": ["chat_id", "title", "messages"],
@@ -2221,6 +2359,17 @@
"crm_contact"
]
},
+ "ErrorBody": {
+ "type": "object",
+ "description": "Error response body.",
+ "required": ["error"],
+ "properties": {
+ "error": {
+ "type": "string",
+ "description": "Human-readable error description."
+ }
+ }
+ },
"ErrorResponse": {
"type": "object",
"description": "A plain old json error response for use with axum.\nyup, thats it.",
@@ -2232,6 +2381,29 @@
}
}
},
+ "FeatureUsage": {
+ "type": "object",
+ "description": "Usage for a single feature, with its rolled-up dollar total.",
+ "required": ["feature", "entries", "total"],
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CompletionUsage"
+ },
+ "description": "The individual completions recorded for this feature."
+ },
+ "feature": {
+ "$ref": "#/components/schemas/AiFeature",
+ "description": "The feature."
+ },
+ "total": {
+ "type": "number",
+ "format": "float",
+ "description": "Total cost across `entries` (USD)."
+ }
+ }
+ },
"FileType": {
"type": "string",
"description": "Generates a FileType enum and associated ContentType enum with their implementations.\n\nThis macro takes a list of tuples in the format:\n(Variant, \"extension\", \"mime_type\", CONTENT_TYPE_VARIANT)\n\nFor each tuple it generates:\n- A variant in the FileType enum\n- A variant in the ContentType enum\n- Implementations for:\n - FileType::to_str() - Converts FileType to extension string\n - FileType::from_str() - Converts extension string to FileType\n - From<FileType> for ContentType - Maps FileType to ContentType\n - ContentType::mime_type() - Gets MIME type for ContentType\n",
@@ -2789,6 +2961,9 @@
}
}
},
+ "MacroUserIdStr": {
+ "type": "string"
+ },
"MemoryErrorBody": {
"type": "object",
"required": ["error"],
@@ -2957,6 +3132,28 @@
}
}
},
+ "Price": {
+ "type": "object",
+ "description": "Resolved price for one completion.",
+ "required": ["price_per_million_in", "price_per_million_out", "total"],
+ "properties": {
+ "price_per_million_in": {
+ "type": "number",
+ "format": "float",
+ "description": "Price per million input tokens (USD)."
+ },
+ "price_per_million_out": {
+ "type": "number",
+ "format": "float",
+ "description": "Price per million output tokens (USD)."
+ },
+ "total": {
+ "type": "number",
+ "format": "float",
+ "description": "Total cost of the completion (USD)."
+ }
+ }
+ },
"RejectToolCallRequest": {
"type": "object",
"description": "Request body for rejecting a pending tool call.",
@@ -3063,6 +3260,27 @@
}
}
},
+ "SetPricingRequest": {
+ "type": "object",
+ "description": "Request body for [`set_pricing_handler`].",
+ "required": ["model", "price_per_mil_in", "price_per_mil_out"],
+ "properties": {
+ "model": {
+ "type": "string",
+ "description": "The model api id to (re)price."
+ },
+ "price_per_mil_in": {
+ "type": "number",
+ "format": "float",
+ "description": "New price per million input tokens (USD)."
+ },
+ "price_per_mil_out": {
+ "type": "number",
+ "format": "float",
+ "description": "New price per million output tokens (USD)."
+ }
+ }
+ },
"SharePermissionV2": {
"type": "object",
"required": ["id", "isPublic", "owner"],
@@ -3390,6 +3608,94 @@
}
}
},
+ "Usage": {
+ "type": "object",
+ "description": "The token usage and resolved cost of a single completion.",
+ "required": ["input_tokens", "output_tokens", "model", "created_at"],
+ "properties": {
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the completion was recorded."
+ },
+ "input_tokens": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Tokens consumed by the input.",
+ "minimum": 0
+ },
+ "model": {
+ "type": "string",
+ "description": "The model api id (e.g. `claude-opus-4-8`)."
+ },
+ "output_tokens": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Tokens generated in the output.",
+ "minimum": 0
+ },
+ "price": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/Price",
+ "description": "Resolved price, or `None` when the model had no pricing at record time."
+ }
+ ]
+ }
+ }
+ },
+ "UsageRequest": {
+ "type": "object",
+ "description": "Request body for [`get_usage_handler`].",
+ "properties": {
+ "features": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AiFeature"
+ },
+ "description": "If empty, include all features."
+ },
+ "from": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "Inclusive lower bound on `created_at`."
+ },
+ "include_users": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "If empty, include all users."
+ },
+ "until": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "Exclusive upper bound on `created_at`."
+ }
+ }
+ },
+ "UsageSummary": {
+ "type": "object",
+ "description": "The result of a usage query: per-feature breakdown plus a grand total.",
+ "required": ["entries", "total"],
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/FeatureUsage"
+ },
+ "description": "Per-feature usage."
+ },
+ "total": {
+ "type": "number",
+ "format": "float",
+ "description": "Grand total cost across all features (USD)."
+ }
+ }
+ },
"UserPdfRect": {
"type": "object",
"description": "UserPdfRect is in UserSpace\n(0,0) top left\npercent page units\n1-based page index",
diff --git a/rust/cloud-storage/.sqlx/query-006d6742d6218213f59326abc8c5e0df14ddf5e7c04a2cf05d8bff6ea4279add.json b/rust/cloud-storage/.sqlx/query-006d6742d6218213f59326abc8c5e0df14ddf5e7c04a2cf05d8bff6ea4279add.json
new file mode 100644
index 0000000000..1f1640067f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-006d6742d6218213f59326abc8c5e0df14ddf5e7c04a2cf05d8bff6ea4279add.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_usage (\n id, feature, user_id, entity, model,\n input_tokens, output_tokens,\n price_per_million_in, price_per_million_out, total\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Uuid",
+ "Text",
+ "Int8",
+ "Int8",
+ "Float4",
+ "Float4",
+ "Float4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "006d6742d6218213f59326abc8c5e0df14ddf5e7c04a2cf05d8bff6ea4279add"
+}
diff --git a/rust/cloud-storage/.sqlx/query-81bed360250642bbb9f8f46d705bfe31be1a467c32bb2c8a16cf61cc668fb6c1.json b/rust/cloud-storage/.sqlx/query-81bed360250642bbb9f8f46d705bfe31be1a467c32bb2c8a16cf61cc668fb6c1.json
new file mode 100644
index 0000000000..bd17d0b32c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-81bed360250642bbb9f8f46d705bfe31be1a467c32bb2c8a16cf61cc668fb6c1.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out)\n VALUES ($1, $2, $3)\n ON CONFLICT (model) DO UPDATE\n SET price_per_million_in = EXCLUDED.price_per_million_in,\n price_per_million_out = EXCLUDED.price_per_million_out,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Float4",
+ "Float4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "81bed360250642bbb9f8f46d705bfe31be1a467c32bb2c8a16cf61cc668fb6c1"
+}
diff --git a/rust/cloud-storage/.sqlx/query-8dc9ec20b47e16110d9ec18da057b14461c616516d03ca31d7e17749938b829a.json b/rust/cloud-storage/.sqlx/query-8dc9ec20b47e16110d9ec18da057b14461c616516d03ca31d7e17749938b829a.json
new file mode 100644
index 0000000000..1082325c79
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-8dc9ec20b47e16110d9ec18da057b14461c616516d03ca31d7e17749938b829a.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT price_per_million_in, price_per_million_out\n FROM ai_pricing\n WHERE model = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "price_per_million_in",
+ "type_info": "Float4"
+ },
+ {
+ "ordinal": 1,
+ "name": "price_per_million_out",
+ "type_info": "Float4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "8dc9ec20b47e16110d9ec18da057b14461c616516d03ca31d7e17749938b829a"
+}
diff --git a/rust/cloud-storage/.sqlx/query-8f6b8f408336fd56bf212f1b17f32f36dc1fdbe6d45e4ccfe3ab938974d828c3.json b/rust/cloud-storage/.sqlx/query-8f6b8f408336fd56bf212f1b17f32f36dc1fdbe6d45e4ccfe3ab938974d828c3.json
new file mode 100644
index 0000000000..5390457b2c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-8f6b8f408336fd56bf212f1b17f32f36dc1fdbe6d45e4ccfe3ab938974d828c3.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE ai_usage\n SET price_per_million_in = $2::real,\n price_per_million_out = $3::real,\n total = (input_tokens::real / 1000000.0::real) * $2::real\n + (output_tokens::real / 1000000.0::real) * $3::real\n WHERE model = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Float4",
+ "Float4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8f6b8f408336fd56bf212f1b17f32f36dc1fdbe6d45e4ccfe3ab938974d828c3"
+}
diff --git a/rust/cloud-storage/.sqlx/query-cc6d835ae3a35891b84f625bc774d487f4907b7f4ac77a6b870113b7ea2581fb.json b/rust/cloud-storage/.sqlx/query-cc6d835ae3a35891b84f625bc774d487f4907b7f4ac77a6b870113b7ea2581fb.json
new file mode 100644
index 0000000000..dce905120c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-cc6d835ae3a35891b84f625bc774d487f4907b7f4ac77a6b870113b7ea2581fb.json
@@ -0,0 +1,79 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n feature,\n user_id,\n entity,\n model,\n input_tokens,\n output_tokens,\n price_per_million_in,\n price_per_million_out,\n total,\n created_at\n FROM ai_usage\n WHERE ($1::timestamptz IS NULL OR created_at >= $1)\n AND ($2::timestamptz IS NULL OR created_at < $2)\n AND (cardinality($3::text[]) = 0 OR user_id = ANY($3))\n AND (cardinality($4::text[]) = 0 OR feature = ANY($4))\n ORDER BY created_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "feature",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "model",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "input_tokens",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "output_tokens",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 6,
+ "name": "price_per_million_in",
+ "type_info": "Float4"
+ },
+ {
+ "ordinal": 7,
+ "name": "price_per_million_out",
+ "type_info": "Float4"
+ },
+ {
+ "ordinal": 8,
+ "name": "total",
+ "type_info": "Float4"
+ },
+ {
+ "ordinal": 9,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Timestamptz",
+ "Timestamptz",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false
+ ]
+ },
+ "hash": "cc6d835ae3a35891b84f625bc774d487f4907b7f4ac77a6b870113b7ea2581fb"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e67f379e8f..181b3a7f9a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -48,6 +48,7 @@ name = "agent"
version = "0.1.0"
dependencies = [
"ai_toolset",
+ "ai_usage",
"anyhow",
"async-openai",
"async-stream",
@@ -98,6 +99,7 @@ version = "0.1.0"
dependencies = [
"agent",
"ai_toolset",
+ "ai_usage",
"anthropic",
"anyhow",
"async-trait",
@@ -185,6 +187,28 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "ai_usage"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "chrono",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "model_user",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "strum",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "utoipa",
+ "workspace-hack",
+]
+
[[package]]
name = "aligned"
version = "0.4.3"
@@ -1930,6 +1954,7 @@ version = "0.1.0"
dependencies = [
"agent",
"ai_toolset",
+ "ai_usage",
"anyhow",
"async-trait",
"aws-sdk-s3",
@@ -2098,6 +2123,7 @@ dependencies = [
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anyhow",
"async-trait",
"bot_id",
@@ -3463,6 +3489,7 @@ dependencies = [
"aho-corasick",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anyhow",
"async-openai",
"async-stream",
@@ -3558,6 +3585,7 @@ name = "document_storage_service"
version = "0.1.0"
dependencies = [
"ai_tools",
+ "ai_usage",
"analytics_client",
"anyhow",
"aws-sdk-dynamodb",
@@ -7190,6 +7218,7 @@ version = "0.1.0"
dependencies = [
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anyhow",
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
@@ -7269,6 +7298,7 @@ dependencies = [
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anyhow",
"axum",
"call",
@@ -10499,6 +10529,7 @@ dependencies = [
"agent",
"ai_tools",
"ai_toolset",
+ "ai_usage",
"anyhow",
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
@@ -12044,6 +12075,7 @@ name = "task_dedup"
version = "0.1.0"
dependencies = [
"agent",
+ "ai_usage",
"anyhow",
"async-trait",
"aws-sdk-secretsmanager",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index cc92468f3b..e2bd647ffc 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -3,6 +3,7 @@ resolver = "2"
members = [
"agent",
+ "ai_usage",
"authentication_service",
"backfill_entity_access",
"bot_id",
diff --git a/rust/cloud-storage/agent/Cargo.toml b/rust/cloud-storage/agent/Cargo.toml
index ed854b83c5..480ed0b069 100644
--- a/rust/cloud-storage/agent/Cargo.toml
+++ b/rust/cloud-storage/agent/Cargo.toml
@@ -25,6 +25,7 @@ thiserror = { workspace = true }
utoipa = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
+ai_usage = { path = "../ai_usage" }
ai_toolset = { path = "../ai_toolset" }
attachment = { path = "../attachment" }
macro_user_id = { path = "../macro_user_id" }
diff --git a/rust/cloud-storage/agent/src/agent_loop.rs b/rust/cloud-storage/agent/src/agent_loop.rs
index 818f6ef86d..26f1f85c16 100644
--- a/rust/cloud-storage/agent/src/agent_loop.rs
+++ b/rust/cloud-storage/agent/src/agent_loop.rs
@@ -7,8 +7,8 @@ use crate::model::types::Model;
use crate::stream::{ChatCompletionStream, StreamPart};
use crate::tool_adapter::DynToolSetAdapter;
use ai_toolset::{RequestContext, ToolSet as AiToolSet};
+use ai_usage::{UsageContext, UsageRecorder};
use futures::StreamExt;
-use macro_user_id::user_id::MacroUserIdStr;
use rig_core::agent::{Agent, MultiTurnStreamItem};
use rig_core::client::ProviderClient;
use rig_core::completion::{CompletionModel, GetTokenUsage};
@@ -35,20 +35,18 @@ pub struct AgentLoop {
model: String,
max_turns: usize,
max_tokens: u64,
-}
-
-impl Default for AgentLoop {
- fn default() -> Self {
- Self::new()
- }
+ recorder: Arc<dyn UsageRecorder>,
}
impl AgentLoop {
/// Create an `AgentLoop` with provider clients from the environment and
/// the default model (Opus 4.7).
///
+ /// `recorder` is the [`UsageRecorder`] every session created from this loop
+ /// logs token usage to — it is required so that no AI call goes unrecorded.
+ ///
/// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.
- pub fn new() -> Self {
+ pub fn new(recorder: Arc<dyn UsageRecorder>) -> Self {
let anthropic =
Arc::new(anthropic::Client::from_env().expect("ANTHROPIC_API_KEY must be set"));
let openai = Arc::new(openai::Client::from_env().expect("OPENAI_API_KEY must be set"));
@@ -58,6 +56,7 @@ impl AgentLoop {
model: AgentModel::default().to_string(),
max_turns: DEFAULT_MAX_TURNS,
max_tokens: DEFAULT_MAX_TOKENS,
+ recorder,
}
}
@@ -105,18 +104,21 @@ impl AgentLoop {
/// `toolset` is the combined tool set (static + MCP) for this request.
/// `context` is the shared service context passed to tool calls.
/// `system_prompt` is the system prompt for this request.
- /// `user_id` identifies the calling user for tool dispatch.
+ /// `usage_ctx` identifies the calling user (used for tool dispatch) and the
+ /// feature/entity that token usage is recorded against.
pub async fn session<Context>(
&self,
toolset: Arc<dyn AiToolSet<Context> + Send + Sync>,
context: Arc<Context>,
system_prompt: &str,
- user_id: MacroUserIdStr<'static>,
+ usage_ctx: UsageContext,
) -> Session
where
Context: Clone + Send + Sync + 'static,
{
- let request_context = Arc::new(RwLock::new(RequestContext { user_id }));
+ let request_context = Arc::new(RwLock::new(RequestContext {
+ user_id: usage_ctx.user.clone(),
+ }));
// Keep a handle to the toolset so the stream bridge can resolve MCP
// routing info (service / display name) for tool calls. This is the
@@ -171,6 +173,9 @@ impl AgentLoop {
history: Vec::new(),
max_turns: self.max_turns,
routing,
+ recorder: self.recorder.clone(),
+ usage_ctx,
+ model: self.model.clone(),
}
}
}
@@ -187,6 +192,9 @@ pub struct Session {
history: Vec<Message>,
max_turns: usize,
routing: ToolRouter,
+ recorder: Arc<dyn UsageRecorder>,
+ usage_ctx: UsageContext,
+ model: String,
}
impl Session {
@@ -215,6 +223,9 @@ impl Session {
history.to_vec(),
self.max_turns,
self.routing.clone(),
+ self.recorder.clone(),
+ self.usage_ctx.clone(),
+ self.model.clone(),
)
.await
}
@@ -225,6 +236,9 @@ impl Session {
history.to_vec(),
self.max_turns,
self.routing.clone(),
+ self.recorder.clone(),
+ self.usage_ctx.clone(),
+ self.model.clone(),
)
.await
}
@@ -241,12 +255,16 @@ impl Session {
/// Run the agentic loop on `agent` and adapt rig's stream into the
/// provider-agnostic [`StreamPart`] stream consumed by DCS.
+#[allow(clippy::too_many_arguments)]
async fn run_stream<M>(
agent: &Agent<M>,
prompt: Message,
history: Vec<Message>,
max_turns: usize,
routing: ToolRouter,
+ recorder: Arc<dyn UsageRecorder>,
+ usage_ctx: UsageContext,
+ model: String,
) -> ChatCompletionStream<'static>
where
M: CompletionModel + 'static,
@@ -281,6 +299,12 @@ where
match other {
Ok(MultiTurnStreamItem::FinalResponse(final_resp)) => {
let usage = final_resp.usage();
+ // Best-effort cost logging; never fails the stream.
+ recorder.record(usage_ctx.clone().into_event(
+ model.clone(),
+ usage.input_tokens,
+ usage.output_tokens,
+ ));
yield Ok(StreamPart::Usage(crate::stream::Usage {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
diff --git a/rust/cloud-storage/agent/src/completion.rs b/rust/cloud-storage/agent/src/completion.rs
index b5f41ef0e0..de46102ecb 100644
--- a/rust/cloud-storage/agent/src/completion.rs
+++ b/rust/cloud-storage/agent/src/completion.rs
@@ -1,6 +1,8 @@
/// One-shot completion — send a prompt and get a string response.
use crate::model::router::{AllModelsRouter, RoutedModel};
use crate::model::types::Model;
+use ai_usage::{UsageContext, UsageRecorder};
+use rig_core::agent::PromptResponse;
use rig_core::client::ProviderClient;
use rig_core::completion::{CompletionModel, Prompt};
use rig_core::message::Message;
@@ -21,55 +23,85 @@ fn env_router() -> anyhow::Result<AllModelsRouter> {
/// This is the simple, non-streaming path for one-shot tasks like
/// summarization. `model` is anything stringifiable to an api id — an
/// [`AgentModel`](crate::AgentModel) or a raw string from the frontend.
-#[tracing::instrument(skip(model, system_prompt, user_message), err)]
+///
+/// Token usage is recorded against `ctx` via `recorder` once the completion
+/// returns. Recording is best-effort and never affects the result.
+#[tracing::instrument(skip(model, system_prompt, user_message, recorder, ctx), err)]
pub async fn complete<M: ToString>(
model: M,
system_prompt: &str,
user_message: &str,
+ recorder: &dyn UsageRecorder,
+ ctx: UsageContext,
) -> anyhow::Result<String> {
- match env_router()?.route_or_default(&model.to_string()) {
- RoutedModel::Anthropic(m) => prompt_once(m.completion(), system_prompt, user_message).await,
- RoutedModel::OpenAi(m) => prompt_once(m.completion(), system_prompt, user_message).await,
- }
+ let model = model.to_string();
+ let response = match env_router()?.route_or_default(&model) {
+ RoutedModel::Anthropic(m) => {
+ prompt_once(m.completion(), system_prompt, user_message).await?
+ }
+ RoutedModel::OpenAi(m) => prompt_once(m.completion(), system_prompt, user_message).await?,
+ };
+ record(recorder, ctx, model, &response);
+ Ok(response.output)
}
/// Send a system prompt + conversation history and return the model's text
/// response.
-#[tracing::instrument(skip(model, system_prompt, messages), err)]
+///
+/// Usage is recorded against `ctx` via `recorder`, as in [`complete`].
+#[tracing::instrument(skip(model, system_prompt, messages, recorder, ctx), err)]
pub async fn complete_with_history<M: ToString>(
model: M,
system_prompt: &str,
messages: Vec<Message>,
+ recorder: &dyn UsageRecorder,
+ ctx: UsageContext,
) -> anyhow::Result<String> {
- match env_router()?.route_or_default(&model.to_string()) {
+ let model = model.to_string();
+ let response = match env_router()?.route_or_default(&model) {
RoutedModel::Anthropic(m) => {
- prompt_with_history(m.completion(), system_prompt, messages).await
+ prompt_with_history(m.completion(), system_prompt, messages).await?
}
RoutedModel::OpenAi(m) => {
- prompt_with_history(m.completion(), system_prompt, messages).await
+ prompt_with_history(m.completion(), system_prompt, messages).await?
}
- }
+ };
+ record(recorder, ctx, model, &response);
+ Ok(response.output)
+}
+
+/// Record the usage of a one-shot completion.
+fn record(
+ recorder: &dyn UsageRecorder,
+ ctx: UsageContext,
+ model: String,
+ response: &PromptResponse,
+) {
+ recorder.record(ctx.into_event(
+ model,
+ response.usage.input_tokens,
+ response.usage.output_tokens,
+ ));
}
async fn prompt_once<M: CompletionModel + 'static>(
completion_model: M,
system_prompt: &str,
user_message: &str,
-) -> anyhow::Result<String> {
+) -> anyhow::Result<PromptResponse> {
let agent = rig_core::agent::AgentBuilder::new(completion_model)
.preamble(system_prompt)
.max_tokens(16_000)
.build();
- let response = agent.prompt(user_message).await?;
- Ok(response)
+ Ok(agent.prompt(user_message).extended_details().await?)
}
async fn prompt_with_history<M: CompletionModel + 'static>(
completion_model: M,
system_prompt: &str,
messages: Vec<Message>,
-) -> anyhow::Result<String> {
+) -> anyhow::Result<PromptResponse> {
let agent = rig_core::agent::AgentBuilder::new(completion_model)
.preamble(system_prompt)
.max_tokens(16_000)
@@ -79,9 +111,9 @@ async fn prompt_with_history<M: CompletionModel + 'static>(
anyhow::bail!("messages must not be empty");
};
- let response = agent
+ Ok(agent
.prompt(prompt.clone())
+ .extended_details()
.with_history(history.to_vec())
- .await?;
- Ok(response)
+ .await?)
}
diff --git a/rust/cloud-storage/agent/src/structured_output.rs b/rust/cloud-storage/agent/src/structured_output.rs
index 31b91229c1..f96d6ad25a 100644
--- a/rust/cloud-storage/agent/src/structured_output.rs
+++ b/rust/cloud-storage/agent/src/structured_output.rs
@@ -18,12 +18,14 @@ pub struct DynamicSchema {
/// Run a completion with conversation history and return a JSON value
/// conforming to `schema`.
-#[tracing::instrument(skip(model, system_prompt, messages, schema), err)]
+#[tracing::instrument(skip(model, system_prompt, messages, schema, recorder, ctx), err)]
pub async fn dynamic_structured_completion<M: ToString>(
model: M,
system_prompt: &str,
messages: Vec<Message>,
schema: DynamicSchema,
+ recorder: &dyn ai_usage::UsageRecorder,
+ ctx: ai_usage::UsageContext,
) -> anyhow::Result<serde_json::Value> {
let structured_prompt = format!(
"{system_prompt}\n\n\
@@ -41,8 +43,14 @@ pub async fn dynamic_structured_completion<M: ToString>(
schema_json = serde_json::to_string_pretty(&schema.schema)?,
);
- let response =
- crate::completion::complete_with_history(model, &structured_prompt, messages).await?;
+ let response = crate::completion::complete_with_history(
+ model,
+ &structured_prompt,
+ messages,
+ recorder,
+ ctx,
+ )
+ .await?;
let trimmed = response.trim();
let json_str = if let Some(rest) = trimmed.strip_prefix("```") {
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index 46847d775d..a494749531 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -9,6 +9,7 @@ test-support = []
[dependencies]
agent = { path = "../agent" }
+ai_usage = { path = "../ai_usage" }
anthropic = { path = "../anthropic", features = ["toolset"] }
attachment = { path = "../attachment" }
non_empty = { path = "../non_empty" }
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index d38e37b5e0..6acc9e2718 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -307,6 +307,8 @@ pub async fn build_tool_service_context_from_env(
team_tool_context: crate::tool_context::build_team_tool_context(pool.clone()),
schedule_tool_context: crate::NoOpScheduleContext,
anthropic_tool_context,
+ recorder: ai_usage::pg_recorder(pool.clone()),
+ usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
})
}
diff --git a/rust/cloud-storage/ai_tools/src/subagent.rs b/rust/cloud-storage/ai_tools/src/subagent.rs
index 5b6a3adc02..75e9fb73f8 100644
--- a/rust/cloud-storage/ai_tools/src/subagent.rs
+++ b/rust/cloud-storage/ai_tools/src/subagent.rs
@@ -34,15 +34,23 @@ impl AsyncTool<ToolServiceContext> for Subagent {
#[tracing::instrument(skip_all, err)]
async fn call(
&self,
- _service_context: ServiceContext<ToolServiceContext>,
+ service_context: ServiceContext<ToolServiceContext>,
_request_context: RequestContext,
) -> ToolResult<Self::Output> {
- let result = agent::complete(SUBAGENT_MODEL, SUBAGENT_PROMPT, &self.task)
- .await
- .map_err(|e| ToolCallError {
- description: "subagent encountered an error".to_string(),
- internal_error: e,
- })?;
+ // Subagents have no feature of their own — their usage rolls up into the
+ // feature that spawned them, carried on the service context.
+ let result = agent::complete(
+ SUBAGENT_MODEL,
+ SUBAGENT_PROMPT,
+ &self.task,
+ service_context.recorder.as_ref(),
+ service_context.usage_context.clone(),
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "subagent encountered an error".to_string(),
+ internal_error: e,
+ })?;
Ok(SubagentResponse { result })
}
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index c76dbc96de..ed0a63bb0f 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -589,6 +589,12 @@ pub struct ToolServiceContext {
pub team_tool_context: ToolTeamToolContext,
pub schedule_tool_context: NoOpScheduleContext,
pub anthropic_tool_context: AnthropicToolContext,
+ /// Records token usage / cost for AI calls made with this context.
+ pub recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,
+ /// The usage context (feature/user/entity) of the request currently using
+ /// this context. Set per-session by the caller so AI calls made by tools
+ /// (e.g. subagents) are attributed to the feature that spawned them.
+ pub usage_context: ai_usage::UsageContext,
}
impl FromRef<ToolServiceContext> for ai_toolset::NoContext {
diff --git a/rust/cloud-storage/ai_usage/Cargo.toml b/rust/cloud-storage/ai_usage/Cargo.toml
new file mode 100644
index 0000000000..bb92e90c12
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+edition = "2024"
+name = "ai_usage"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+anyhow = { workspace = true }
+axum = { workspace = true }
+chrono = { workspace = true }
+macro_user_id = { path = "../macro_user_id", features = ["schema"] }
+macro_uuid = { path = "../macro_uuid" }
+model_user = { path = "../model_user", features = ["axum"] }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+strum = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
+utoipa = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/ai_usage/src/domain/mod.rs b/rust/cloud-storage/ai_usage/src/domain/mod.rs
new file mode 100644
index 0000000000..340df61c37
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/domain/mod.rs
@@ -0,0 +1,10 @@
+//! Domain layer: the cost model, ports, and the service that computes cost.
+
+pub mod ports;
+pub mod service;
+
+pub use ports::{
+ AiFeature, CompletionUsage, FeatureUsage, Price, Result, SYSTEM_USER_ID, Usage, UsageApiParams,
+ UsageContext, UsageError, UsageEvent, UsageRecorder, UsageRepo, UsageService, UsageSummary,
+};
+pub use service::UsageServiceImpl;
diff --git a/rust/cloud-storage/ai_usage/src/domain/ports.rs b/rust/cloud-storage/ai_usage/src/domain/ports.rs
new file mode 100644
index 0000000000..f21b59f224
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/domain/ports.rs
@@ -0,0 +1,292 @@
+//! Cost model types and the ports the crate is built around.
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use std::sync::LazyLock;
+use thiserror::Error;
+use utoipa::ToSchema;
+
+/// The reserved system user recorded for completions with no originating
+/// end-user (background tasks, internal summarization, subagents, …).
+///
+/// Building a [`MacroUserIdStr`] parses the id at runtime (there is no
+/// `const fn` constructor), so this is a `LazyLock` rather than a literal
+/// `const`. Deref yields a `&'static MacroUserIdStr`; clone it when an owned
+/// value is needed.
+pub static SYSTEM_USER_ID: LazyLock<MacroUserIdStr<'static>> = LazyLock::new(|| {
+ MacroUserIdStr::try_from("macro|[email protected]".to_string())
+ .expect("system user id is valid")
+});
+
+/// Everything we use AI for. The wire / DB form of each variant is its
+/// `snake_case` name.
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ PartialEq,
+ Eq,
+ Hash,
+ PartialOrd,
+ Ord,
+ Serialize,
+ Deserialize,
+ ToSchema,
+ strum::Display,
+ strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum AiFeature {
+ /// Interactive chat.
+ Chat,
+ /// User memory generation.
+ Memory,
+ /// Scheduled actions / automations.
+ Automation,
+ /// The dynamic (structured) completions API.
+ DynamicCompletionsApi,
+ /// Automatic chat renaming.
+ ChatRename,
+ /// Call recording summarization.
+ CallSummary,
+ /// Channel bots.
+ ChannelBot,
+}
+
+/// Resolved price for one completion.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, ToSchema)]
+pub struct Price {
+ /// Price per million input tokens (USD).
+ pub price_per_million_in: f32,
+ /// Price per million output tokens (USD).
+ pub price_per_million_out: f32,
+ /// Total cost of the completion (USD).
+ pub total: f32,
+}
+
+impl Price {
+ /// Compute the price of a completion from per-million rates and token counts.
+ pub fn compute(price_per_million_in: f32, price_per_million_out: f32, usage: &Usage) -> Self {
+ let total = (usage.input_tokens as f32 / 1_000_000.0) * price_per_million_in
+ + (usage.output_tokens as f32 / 1_000_000.0) * price_per_million_out;
+ Self {
+ price_per_million_in,
+ price_per_million_out,
+ total,
+ }
+ }
+}
+
+/// The token usage and resolved cost of a single completion.
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct Usage {
+ /// Tokens consumed by the input.
+ pub input_tokens: u32,
+ /// Tokens generated in the output.
+ pub output_tokens: u32,
+ /// The model api id (e.g. `claude-opus-4-8`).
+ pub model: String,
+ /// Resolved price, or `None` when the model had no pricing at record time.
+ pub price: Option<Price>,
+ /// When the completion was recorded.
+ pub created_at: DateTime<Utc>,
+}
+
+/// A recorded completion: who, what feature, optional entity, and the cost.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct CompletionUsage {
+ /// The feature that performed the completion.
+ pub feature: AiFeature,
+ /// The user the completion was performed for (the [system user](SYSTEM_USER_ID)
+ /// for background work).
+ pub user: MacroUserIdStr<'static>,
+ /// The entity the completion related to, if any.
+ pub entity: Option<Uuid>,
+ /// Token usage and cost.
+ pub cost: Usage,
+}
+
+/// Usage for a single feature, with its rolled-up dollar total.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct FeatureUsage {
+ /// The feature.
+ pub feature: AiFeature,
+ /// The individual completions recorded for this feature.
+ pub entries: Vec<CompletionUsage>,
+ /// Total cost across `entries` (USD).
+ pub total: f32,
+}
+
+/// The result of a usage query: per-feature breakdown plus a grand total.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct UsageSummary {
+ /// Per-feature usage.
+ pub entries: Vec<FeatureUsage>,
+ /// Grand total cost across all features (USD).
+ pub total: f32,
+}
+
+/// Parameters for [`UsageService::get_usage`].
+#[derive(Debug, Clone, Default)]
+pub struct UsageApiParams {
+ /// Inclusive lower bound on `created_at`.
+ pub from: Option<DateTime<Utc>>,
+ /// Exclusive upper bound on `created_at`.
+ pub until: Option<DateTime<Utc>>,
+ /// If empty, include all users.
+ pub include_users: Vec<MacroUserIdStr<'static>>,
+ /// If empty, include all features.
+ pub features: Vec<AiFeature>,
+}
+
+/// A usage event handed to a [`UsageRecorder`] by the agent crate. The recorder
+/// resolves pricing and persists it; callers never see the cost.
+#[derive(Debug, Clone)]
+pub struct UsageEvent {
+ /// The feature that performed the completion.
+ pub feature: AiFeature,
+ /// The user the completion was performed for.
+ pub user: MacroUserIdStr<'static>,
+ /// The entity the completion related to, if any.
+ pub entity: Option<Uuid>,
+ /// The model api id.
+ pub model: String,
+ /// Input tokens for this round-trip.
+ pub input_tokens: u64,
+ /// Output tokens for this round-trip.
+ pub output_tokens: u64,
+}
+
+/// The constant attributes of a logical completion (everything except the model
+/// and token counts, which are only known once the completion runs).
+///
+/// Threaded into agent functions so each call site declares which feature it is
+/// and who it is for.
+#[derive(Debug, Clone)]
+pub struct UsageContext {
+ /// The feature performing the completion.
+ pub feature: AiFeature,
+ /// The user the completion is for.
+ pub user: MacroUserIdStr<'static>,
+ /// The entity the completion relates to, if any.
+ pub entity: Option<Uuid>,
+}
+
+impl UsageContext {
+ /// A context for a user-attributed completion.
+ pub fn new(feature: AiFeature, user: MacroUserIdStr<'static>) -> Self {
+ Self {
+ feature,
+ user,
+ entity: None,
+ }
+ }
+
+ /// A context for background/internal work with no originating end-user.
+ pub fn system(feature: AiFeature) -> Self {
+ Self {
+ feature,
+ user: SYSTEM_USER_ID.clone(),
+ entity: None,
+ }
+ }
+
+ /// Set the related entity.
+ pub fn with_entity(mut self, entity: Option<Uuid>) -> Self {
+ self.entity = entity;
+ self
+ }
+
+ /// Build a [`UsageEvent`] from this context plus a completion's model and
+ /// token counts.
+ pub fn into_event(self, model: String, input_tokens: u64, output_tokens: u64) -> UsageEvent {
+ UsageEvent {
+ feature: self.feature,
+ user: self.user,
+ entity: self.entity,
+ model,
+ input_tokens,
+ output_tokens,
+ }
+ }
+}
+
+/// Errors raised by the cost crate.
+#[derive(Debug, Error)]
+pub enum UsageError {
+ /// A database error.
+ #[error(transparent)]
+ Db(#[from] sqlx::Error),
+ /// Any other error.
+ #[error(transparent)]
+ Other(#[from] anyhow::Error),
+}
+
+/// Convenience result alias for the crate.
+pub type Result<T> = std::result::Result<T, UsageError>;
+
+/// Outbound storage port.
+pub trait UsageRepo: Send + Sync + 'static {
+ /// Persist a fully-priced completion row.
+ // TODO: Consumers should have an easier call to make than this
+ // A consumer shouldn't have to know the pricing of the model the just need to supply (feature, input tokens, output tokens, model name)
+ fn insert_usage(&self, usage: &CompletionUsage) -> impl Future<Output = Result<()>> + Send;
+
+ /// Fetch the current per-million `(input, output)` rates for a model, if any.
+ fn get_pricing(&self, model: &str) -> impl Future<Output = Result<Option<(f32, f32)>>> + Send;
+
+ /// Upsert the pricing for a model and recompute the `total` of every
+ /// existing `ai_usage` row for that model.
+ fn set_pricing(
+ &self,
+ model: &str,
+ price_per_million_in: f32,
+ price_per_million_out: f32,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Query recorded completions matching `params`.
+ fn query_usage(
+ &self,
+ params: &UsageApiParams,
+ ) -> impl Future<Output = Result<Vec<CompletionUsage>>> + Send;
+}
+
+/// The recording port used by the agent crate. Recording is best-effort: a
+/// failure must never propagate into the originating call, so the method is
+/// infallible and fire-and-forget.
+pub trait UsageRecorder: Send + Sync {
+ /// Record one completion round-trip.
+ fn record(&self, event: UsageEvent);
+}
+
+/// A [`UsageRecorder`] that drops every event. Used at call sites that cannot
+/// (or should not) record, mirroring the `NoOp*` adapters used elsewhere.
+#[cfg(test)]
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoOpUsageRecorder;
+
+#[cfg(test)]
+impl UsageRecorder for NoOpUsageRecorder {
+ fn record(&self, _event: UsageEvent) {}
+}
+
+/// The admin-facing query / pricing port, implemented by the domain service and
+/// consumed by the inbound axum router.
+pub trait UsageService: Send + Sync + 'static {
+ /// Summarize recorded usage matching `params`.
+ fn get_usage(
+ &self,
+ params: UsageApiParams,
+ ) -> impl Future<Output = Result<UsageSummary>> + Send;
+
+ /// Set the pricing for a model and recompute all of its recorded rows.
+ fn set_pricing(
+ &self,
+ model: String,
+ price_per_million_in: f32,
+ price_per_million_out: f32,
+ ) -> impl Future<Output = Result<()>> + Send;
+}
diff --git a/rust/cloud-storage/ai_usage/src/domain/service.rs b/rust/cloud-storage/ai_usage/src/domain/service.rs
new file mode 100644
index 0000000000..54670edc4a
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/domain/service.rs
@@ -0,0 +1,125 @@
+//! The cost service: resolves pricing, records usage, and answers queries.
+
+use std::collections::BTreeMap;
+
+use chrono::Utc;
+
+use super::ports::*;
+
+/// The cost service. Generic over the storage [`UsageRepo`].
+///
+/// Implements:
+/// - [`UsageRecorder`] for the agent crate (fire-and-forget recording), and
+/// - [`UsageService`] for the inbound admin API (querying and re-pricing).
+#[derive(Clone)]
+pub struct UsageServiceImpl<Repo> {
+ repo: Repo,
+}
+
+impl<Repo> UsageServiceImpl<Repo> {
+ /// Construct the service over a storage repository.
+ pub fn new(repo: Repo) -> Self {
+ Self { repo }
+ }
+}
+
+impl<Repo> UsageServiceImpl<Repo>
+where
+ Repo: UsageRepo + Clone,
+{
+ /// Resolve pricing and persist a single event. Separated out so [`record`]
+ /// can run it on a background task.
+ ///
+ /// [`record`]: UsageRecorder::record
+ async fn record_event(repo: &Repo, event: UsageEvent) -> Result<()> {
+ let mut cost = Usage {
+ input_tokens: event.input_tokens.min(u32::MAX as u64) as u32,
+ output_tokens: event.output_tokens.min(u32::MAX as u64) as u32,
+ model: event.model.clone(),
+ price: None,
+ created_at: Utc::now(),
+ };
+
+ if let Some((per_in, per_out)) = repo.get_pricing(&event.model).await? {
+ cost.price = Some(Price::compute(per_in, per_out, &cost));
+ }
+
+ let row = CompletionUsage {
+ feature: event.feature,
+ user: event.user,
+ entity: event.entity,
+ cost,
+ };
+
+ repo.insert_usage(&row).await
+ }
+}
+
+impl<Repo> UsageRecorder for UsageServiceImpl<Repo>
+where
+ Repo: UsageRepo + Clone + 'static,
+{
+ fn record(&self, event: UsageEvent) {
+ let repo = self.repo.clone();
+ // Recording must never fail or delay the originating call.
+ tokio::spawn(async move {
+ if let Err(e) = Self::record_event(&repo, event).await {
+ tracing::error!(error = ?e, "failed to record ai usage");
+ }
+ });
+ }
+}
+
+impl<Repo> UsageService for UsageServiceImpl<Repo>
+where
+ Repo: UsageRepo + Clone + 'static,
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn get_usage(&self, params: UsageApiParams) -> Result<UsageSummary> {
+ let rows = self.repo.query_usage(&params).await?;
+ Ok(summarize(rows))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn set_pricing(
+ &self,
+ model: String,
+ price_per_million_in: f32,
+ price_per_million_out: f32,
+ ) -> Result<()> {
+ self.repo
+ .set_pricing(&model, price_per_million_in, price_per_million_out)
+ .await
+ }
+}
+
+/// Group recorded completions by feature and roll up dollar totals.
+fn summarize(rows: Vec<CompletionUsage>) -> UsageSummary {
+ let mut by_feature: BTreeMap<AiFeature, Vec<CompletionUsage>> = BTreeMap::new();
+ for row in rows {
+ by_feature.entry(row.feature).or_default().push(row);
+ }
+
+ let mut entries = Vec::with_capacity(by_feature.len());
+ let mut grand_total = 0.0_f32;
+ for (feature, completions) in by_feature {
+ let total: f32 = completions
+ .iter()
+ .filter_map(|c| c.cost.price.as_ref().map(|p| p.total))
+ .sum();
+ grand_total += total;
+ entries.push(FeatureUsage {
+ feature,
+ entries: completions,
+ total,
+ });
+ }
+
+ UsageSummary {
+ entries,
+ total: grand_total,
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/ai_usage/src/domain/service/test.rs b/rust/cloud-storage/ai_usage/src/domain/service/test.rs
new file mode 100644
index 0000000000..e0404a2b58
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/domain/service/test.rs
@@ -0,0 +1,86 @@
+use super::*;
+use macro_user_id::user_id::MacroUserIdStr;
+
+fn user() -> MacroUserIdStr<'static> {
+ SYSTEM_USER_ID.clone()
+}
+
+fn completion(feature: AiFeature, total: Option<f32>) -> CompletionUsage {
+ CompletionUsage {
+ feature,
+ user: user(),
+ entity: None,
+ cost: Usage {
+ input_tokens: 1000,
+ output_tokens: 500,
+ model: "claude-opus-4-8".to_string(),
+ price: total.map(|t| Price {
+ price_per_million_in: 5.0,
+ price_per_million_out: 25.0,
+ total: t,
+ }),
+ created_at: Utc::now(),
+ },
+ }
+}
+
+#[test]
+fn price_compute_uses_per_million_rates() {
+ let usage = Usage {
+ input_tokens: 1_000_000,
+ output_tokens: 1_000_000,
+ model: "m".to_string(),
+ price: None,
+ created_at: Utc::now(),
+ };
+ let price = Price::compute(5.0, 25.0, &usage);
+ assert!((price.total - 30.0).abs() < 1e-3);
+}
+
+#[test]
+fn summarize_groups_by_feature_and_totals() {
+ let rows = vec![
+ completion(AiFeature::Chat, Some(1.0)),
+ completion(AiFeature::Chat, Some(2.5)),
+ completion(AiFeature::Memory, Some(0.5)),
+ completion(AiFeature::Memory, None), // unpriced rows contribute 0
+ ];
+
+ let summary = summarize(rows);
+
+ assert_eq!(summary.entries.len(), 2);
+ assert!((summary.total - 4.0).abs() < 1e-4);
+
+ let chat = summary
+ .entries
+ .iter()
+ .find(|f| f.feature == AiFeature::Chat)
+ .unwrap();
+ assert_eq!(chat.entries.len(), 2);
+ assert!((chat.total - 3.5).abs() < 1e-4);
+
+ let memory = summary
+ .entries
+ .iter()
+ .find(|f| f.feature == AiFeature::Memory)
+ .unwrap();
+ assert_eq!(memory.entries.len(), 2);
+ assert!((memory.total - 0.5).abs() < 1e-4);
+}
+
+#[test]
+fn ai_feature_roundtrips_through_snake_case() {
+ assert_eq!(
+ AiFeature::DynamicCompletionsApi.to_string(),
+ "dynamic_completions_api"
+ );
+ assert_eq!(
+ "channel_bot".parse::<AiFeature>().unwrap(),
+ AiFeature::ChannelBot
+ );
+}
+
+#[test]
+fn system_user_is_valid() {
+ assert_eq!(SYSTEM_USER_ID.as_ref(), "macro|[email protected]");
+}
diff --git a/rust/cloud-storage/ai_usage/src/inbound.rs b/rust/cloud-storage/ai_usage/src/inbound.rs
new file mode 100644
index 0000000000..caa1157629
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/inbound.rs
@@ -0,0 +1,5 @@
+//! Inbound adapters.
+
+pub mod axum_router;
+
+pub use axum_router::ai_usage_router;
diff --git a/rust/cloud-storage/ai_usage/src/inbound/axum_router.rs b/rust/cloud-storage/ai_usage/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..cb27ca6d20
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/inbound/axum_router.rs
@@ -0,0 +1,185 @@
+//! Admin-only HTTP API for querying AI cost and re-pricing models.
+//!
+//! Every route is restricted to Macro admins — callers whose user id resolves
+//! to an `@macro.com` email.
+
+use crate::domain::{AiFeature, UsageApiParams, UsageService, UsageSummary};
+use axum::{
+ Json, Router,
+ extract::State,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::post,
+};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::axum_extractor::MacroUserExtractor;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use utoipa::ToSchema;
+
+/// Domain suffix that identifies a Macro admin.
+const ADMIN_EMAIL_SUFFIX: &str = "@macro.com";
+
+/// Request body for [`get_usage_handler`].
+#[derive(Debug, Default, Deserialize, ToSchema)]
+pub struct UsageRequest {
+ /// Inclusive lower bound on `created_at`.
+ pub from: Option<DateTime<Utc>>,
+ /// Exclusive upper bound on `created_at`.
+ pub until: Option<DateTime<Utc>>,
+ /// If empty, include all users.
+ #[serde(default)]
+ pub include_users: Vec<String>,
+ /// If empty, include all features.
+ #[serde(default)]
+ pub features: Vec<AiFeature>,
+}
+
+/// Request body for [`set_pricing_handler`].
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct SetPricingRequest {
+ /// The model api id to (re)price.
+ pub model: String,
+ /// New price per million input tokens (USD).
+ pub price_per_mil_in: f32,
+ /// New price per million output tokens (USD).
+ pub price_per_mil_out: f32,
+}
+
+/// Error response body.
+#[derive(Serialize, ToSchema)]
+pub struct ErrorBody {
+ /// Human-readable error description.
+ pub error: String,
+}
+
+/// Build the admin AI-cost router.
+pub fn ai_usage_router<T, S>(service: Arc<T>) -> Router<S>
+where
+ T: UsageService,
+ S: Send + Sync + Clone + 'static,
+{
+ Router::new()
+ .route("/ai-cost/usage", post(get_usage_handler::<T>))
+ .route("/ai-cost/pricing", post(set_pricing_handler::<T>))
+ .with_state(service)
+}
+
+/// Returns `Some(403)` unless the caller is a Macro admin.
+fn admin_rejection(user: &MacroUserExtractor) -> Option<Response> {
+ if user.macro_user_id.email_str().ends_with(ADMIN_EMAIL_SUFFIX) {
+ None
+ } else {
+ Some(
+ (
+ StatusCode::FORBIDDEN,
+ Json(ErrorBody {
+ error: "admin access required".to_string(),
+ }),
+ )
+ .into_response(),
+ )
+ }
+}
+
+fn internal_error(context: &str) -> Response {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorBody {
+ error: context.to_string(),
+ }),
+ )
+ .into_response()
+}
+
+/// Query recorded AI usage. Admin only.
+#[utoipa::path(
+ post,
+ path = "/ai-cost/usage",
+ request_body = UsageRequest,
+ responses(
+ (status = 200, description = "Usage summary", body = UsageSummary),
+ (status = 400, description = "Invalid request", body = ErrorBody),
+ (status = 403, description = "Admin access required", body = ErrorBody),
+ (status = 500, description = "Internal server error", body = ErrorBody),
+ ),
+ tag = "ai_usage"
+)]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+pub async fn get_usage_handler<T: UsageService>(
+ State(service): State<Arc<T>>,
+ user: MacroUserExtractor,
+ Json(req): Json<UsageRequest>,
+) -> Response {
+ if let Some(resp) = admin_rejection(&user) {
+ return resp;
+ }
+
+ let include_users: std::result::Result<Vec<MacroUserIdStr<'static>>, _> = req
+ .include_users
+ .into_iter()
+ .map(MacroUserIdStr::try_from)
+ .collect();
+ let include_users = match include_users {
+ Ok(u) => u,
+ Err(e) => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorBody {
+ error: format!("invalid user id: {e}"),
+ }),
+ )
+ .into_response();
+ }
+ };
+
+ let params = UsageApiParams {
+ from: req.from,
+ until: req.until,
+ include_users,
+ features: req.features,
+ };
+
+ match service.get_usage(params).await {
+ Ok(summary) => Json(summary).into_response(),
+ Err(e) => {
+ tracing::error!(error = ?e, "failed to query ai usage");
+ internal_error("failed to query usage")
+ }
+ }
+}
+
+/// Set the pricing for a model and recompute its recorded rows. Admin only.
+#[utoipa::path(
+ post,
+ path = "/ai-cost/pricing",
+ request_body = SetPricingRequest,
+ responses(
+ (status = 200, description = "Pricing updated"),
+ (status = 403, description = "Admin access required", body = ErrorBody),
+ (status = 500, description = "Internal server error", body = ErrorBody),
+ ),
+ tag = "ai_usage"
+)]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+pub async fn set_pricing_handler<T: UsageService>(
+ State(service): State<Arc<T>>,
+ user: MacroUserExtractor,
+ Json(req): Json<SetPricingRequest>,
+) -> Response {
+ if let Some(resp) = admin_rejection(&user) {
+ return resp;
+ }
+
+ match service
+ .set_pricing(req.model, req.price_per_mil_in, req.price_per_mil_out)
+ .await
+ {
+ Ok(()) => StatusCode::OK.into_response(),
+ Err(e) => {
+ tracing::error!(error = ?e, "failed to set pricing");
+ internal_error("failed to set pricing")
+ }
+ }
+}
diff --git a/rust/cloud-storage/ai_usage/src/lib.rs b/rust/cloud-storage/ai_usage/src/lib.rs
new file mode 100644
index 0000000000..82d25ad3ba
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/lib.rs
@@ -0,0 +1,34 @@
+#![deny(missing_docs)]
+
+//! AI cost logging — a robust log of AI usage with a flexible admin query API.
+//!
+//! The crate follows the hexagonal layout used elsewhere in this workspace:
+//! - [`domain`] holds the cost model, ports, and the service that computes
+//! cost from a model id and token counts.
+//! - [`outbound`] holds the Postgres storage adapter.
+//! - [`inbound`] holds the axum router mounted in the document cognition
+//! service (DCS).
+//!
+//! The agent crate records usage through the [`UsageRecorder`](domain::UsageRecorder)
+//! port; recording is best-effort and never fails the originating call.
+
+pub mod domain;
+pub mod inbound;
+pub mod outbound;
+
+pub use domain::{
+ AiFeature, CompletionUsage, FeatureUsage, Price, SYSTEM_USER_ID, Usage, UsageApiParams,
+ UsageContext, UsageEvent, UsageRecorder, UsageRepo, UsageService, UsageSummary,
+};
+
+use std::sync::Arc;
+
+/// Build a [`UsageRecorder`] backed by Postgres over `pool`.
+///
+/// Services construct one of these and thread it into their tool/service
+/// context (and into AI call sites) — there is no global recorder.
+pub fn pg_recorder(pool: sqlx::PgPool) -> Arc<dyn UsageRecorder> {
+ Arc::new(domain::service::UsageServiceImpl::new(
+ outbound::PgUsageRepo::new(pool),
+ ))
+}
diff --git a/rust/cloud-storage/ai_usage/src/outbound.rs b/rust/cloud-storage/ai_usage/src/outbound.rs
new file mode 100644
index 0000000000..838c184c55
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/outbound.rs
@@ -0,0 +1,5 @@
+//! Outbound adapters.
+
+pub mod pg_usage_repo;
+
+pub use pg_usage_repo::PgUsageRepo;
diff --git a/rust/cloud-storage/ai_usage/src/outbound/pg_usage_repo.rs b/rust/cloud-storage/ai_usage/src/outbound/pg_usage_repo.rs
new file mode 100644
index 0000000000..886d0d0e92
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/outbound/pg_usage_repo.rs
@@ -0,0 +1,192 @@
+//! Postgres-backed storage adapter for AI usage and pricing.
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::{
+ AiFeature, CompletionUsage, Price, Result, Usage, UsageApiParams, UsageError, UsageRepo,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Postgres-backed [`UsageRepo`].
+#[derive(Clone)]
+pub struct PgUsageRepo {
+ inner: PgPool,
+}
+
+impl PgUsageRepo {
+ /// Create a repo over a connection pool.
+ pub fn new(inner: PgPool) -> Self {
+ PgUsageRepo { inner }
+ }
+}
+
+impl UsageRepo for PgUsageRepo {
+ async fn insert_usage(&self, usage: &CompletionUsage) -> Result<()> {
+ let id = macro_uuid::generate_uuid_v7();
+ let (per_in, per_out, total) = match &usage.cost.price {
+ Some(p) => (
+ Some(p.price_per_million_in),
+ Some(p.price_per_million_out),
+ Some(p.total),
+ ),
+ None => (None, None, None),
+ };
+
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_usage (
+ id, feature, user_id, entity, model,
+ input_tokens, output_tokens,
+ price_per_million_in, price_per_million_out, total
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ "#,
+ id,
+ usage.feature.to_string(),
+ usage.user.as_ref(),
+ usage.entity,
+ usage.cost.model,
+ i64::from(usage.cost.input_tokens),
+ i64::from(usage.cost.output_tokens),
+ per_in,
+ per_out,
+ total,
+ )
+ .execute(&self.inner)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn get_pricing(&self, model: &str) -> Result<Option<(f32, f32)>> {
+ let row = sqlx::query!(
+ r#"
+ SELECT price_per_million_in, price_per_million_out
+ FROM ai_pricing
+ WHERE model = $1
+ "#,
+ model,
+ )
+ .fetch_optional(&self.inner)
+ .await?;
+
+ Ok(row.map(|r| (r.price_per_million_in, r.price_per_million_out)))
+ }
+
+ async fn set_pricing(
+ &self,
+ model: &str,
+ price_per_million_in: f32,
+ price_per_million_out: f32,
+ ) -> Result<()> {
+ let mut tx = self.inner.begin().await?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (model) DO UPDATE
+ SET price_per_million_in = EXCLUDED.price_per_million_in,
+ price_per_million_out = EXCLUDED.price_per_million_out,
+ updated_at = NOW()
+ "#,
+ model,
+ price_per_million_in,
+ price_per_million_out,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ // Recompute the price of every recorded row for this model.
+ sqlx::query!(
+ r#"
+ UPDATE ai_usage
+ SET price_per_million_in = $2::real,
+ price_per_million_out = $3::real,
+ total = (input_tokens::real / 1000000.0::real) * $2::real
+ + (output_tokens::real / 1000000.0::real) * $3::real
+ WHERE model = $1
+ "#,
+ model,
+ price_per_million_in,
+ price_per_million_out,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ tx.commit().await?;
+ Ok(())
+ }
+
+ async fn query_usage(&self, params: &UsageApiParams) -> Result<Vec<CompletionUsage>> {
+ let users: Vec<String> = params
+ .include_users
+ .iter()
+ .map(|u| u.as_ref().to_string())
+ .collect();
+ let features: Vec<String> = params.features.iter().map(|f| f.to_string()).collect();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ feature,
+ user_id,
+ entity,
+ model,
+ input_tokens,
+ output_tokens,
+ price_per_million_in,
+ price_per_million_out,
+ total,
+ created_at
+ FROM ai_usage
+ WHERE ($1::timestamptz IS NULL OR created_at >= $1)
+ AND ($2::timestamptz IS NULL OR created_at < $2)
+ AND (cardinality($3::text[]) = 0 OR user_id = ANY($3))
+ AND (cardinality($4::text[]) = 0 OR feature = ANY($4))
+ ORDER BY created_at DESC
+ "#,
+ params.from,
+ params.until,
+ &users,
+ &features,
+ )
+ .fetch_all(&self.inner)
+ .await?;
+
+ rows.into_iter()
+ .map(|r| {
+ let feature: AiFeature = r
+ .feature
+ .parse()
+ .map_err(|e| UsageError::Other(anyhow::anyhow!("invalid feature: {e}")))?;
+ let user = MacroUserIdStr::try_from(r.user_id)
+ .map_err(|e| UsageError::Other(anyhow::anyhow!("invalid user id: {e}")))?;
+
+ let price = match (r.price_per_million_in, r.price_per_million_out, r.total) {
+ (Some(per_in), Some(per_out), Some(total)) => Some(Price {
+ price_per_million_in: per_in,
+ price_per_million_out: per_out,
+ total,
+ }),
+ _ => None,
+ };
+
+ Ok(CompletionUsage {
+ feature,
+ user,
+ entity: r.entity,
+ cost: Usage {
+ input_tokens: r.input_tokens.clamp(0, i64::from(u32::MAX)) as u32,
+ output_tokens: r.output_tokens.clamp(0, i64::from(u32::MAX)) as u32,
+ model: r.model,
+ price,
+ created_at: r.created_at,
+ },
+ })
+ })
+ .collect()
+ }
+}
diff --git a/rust/cloud-storage/ai_usage/src/outbound/pg_usage_repo/test.rs b/rust/cloud-storage/ai_usage/src/outbound/pg_usage_repo/test.rs
new file mode 100644
index 0000000000..01596c13d9
--- /dev/null
+++ b/rust/cloud-storage/ai_usage/src/outbound/pg_usage_repo/test.rs
@@ -0,0 +1,107 @@
+use super::*;
+use crate::domain::{AiFeature, CompletionUsage, SYSTEM_USER_ID, Usage, UsageApiParams};
+use chrono::Utc;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+
+fn completion(feature: AiFeature, model: &str, input: u32, output: u32) -> CompletionUsage {
+ CompletionUsage {
+ feature,
+ user: SYSTEM_USER_ID.clone(),
+ entity: None,
+ cost: Usage {
+ input_tokens: input,
+ output_tokens: output,
+ model: model.to_string(),
+ price: None,
+ created_at: Utc::now(),
+ },
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn seeded_pricing_is_available(pool: PgPool) {
+ let repo = PgUsageRepo::new(pool);
+ let price = repo.get_pricing("claude-opus-4-8").await.unwrap();
+ assert_eq!(price, Some((5.0, 25.0)));
+ assert_eq!(repo.get_pricing("nonexistent-model").await.unwrap(), None);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn insert_and_query_roundtrips(pool: PgPool) {
+ let repo = PgUsageRepo::new(pool);
+
+ let mut row = completion(AiFeature::Chat, "claude-opus-4-8", 1_000_000, 1_000_000);
+ row.cost.price = Some(Price::compute(5.0, 25.0, &row.cost));
+ repo.insert_usage(&row).await.unwrap();
+ repo.insert_usage(&completion(AiFeature::Memory, "unknown-model", 10, 20))
+ .await
+ .unwrap();
+
+ let all = repo.query_usage(&UsageApiParams::default()).await.unwrap();
+ assert_eq!(all.len(), 2);
+
+ let chat_only = repo
+ .query_usage(&UsageApiParams {
+ features: vec![AiFeature::Chat],
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ assert_eq!(chat_only.len(), 1);
+ let priced = &chat_only[0];
+ assert_eq!(priced.feature, AiFeature::Chat);
+ assert!((priced.cost.price.as_ref().unwrap().total - 30.0).abs() < 1e-3);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_pricing_recomputes_existing_rows(pool: PgPool) {
+ let repo = PgUsageRepo::new(pool);
+
+ // Record with an unknown model so price starts NULL.
+ repo.insert_usage(&completion(
+ AiFeature::Automation,
+ "brand-new-model",
+ 1_000_000,
+ 0,
+ ))
+ .await
+ .unwrap();
+
+ let before = repo.query_usage(&UsageApiParams::default()).await.unwrap();
+ assert!(before[0].cost.price.is_none());
+
+ repo.set_pricing("brand-new-model", 2.0, 8.0).await.unwrap();
+
+ let after = repo.query_usage(&UsageApiParams::default()).await.unwrap();
+ let price = after[0].cost.price.as_ref().unwrap();
+ assert!((price.total - 2.0).abs() < 1e-3); // 1M input * $2/1M = $2
+ assert_eq!(
+ repo.get_pricing("brand-new-model").await.unwrap(),
+ Some((2.0, 8.0))
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn query_filters_by_user(pool: PgPool) {
+ let repo = PgUsageRepo::new(pool);
+
+ let mut other = completion(AiFeature::Chat, "claude-opus-4-8", 1, 1);
+ other.user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ repo.insert_usage(&other).await.unwrap();
+ repo.insert_usage(&completion(AiFeature::Chat, "claude-opus-4-8", 1, 1))
+ .await
+ .unwrap();
+
+ let only_other = repo
+ .query_usage(&UsageApiParams {
+ include_users: vec![
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
+ ],
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ assert_eq!(only_other.len(), 1);
+ assert_eq!(only_other[0].user.as_ref(), "macro|[email protected]");
+}
diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.toml
index 447bf69d43..3577e9e1a3 100644
--- a/rust/cloud-storage/call/Cargo.toml
+++ b/rust/cloud-storage/call/Cargo.toml
@@ -18,6 +18,7 @@ inbound = [
]
outbound = [
"dep:agent",
+ "dep:ai_usage",
"dep:aws-sdk-s3",
"comms/outbound",
"dep:entity_access_db_utils",
@@ -33,6 +34,7 @@ ports = ["dep:entity_access", "dep:tokio"]
[dependencies]
agent = { path = "../agent", optional = true }
+ai_usage = { path = "../ai_usage", optional = true }
ai_toolset = { path = "../ai_toolset", optional = true }
anyhow = { workspace = true }
async-trait = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs b/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs
index 352d9b13c7..d8c1fdd5cb 100644
--- a/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs
+++ b/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs
@@ -119,13 +119,15 @@ const CALL_NAME_SUMMARY_CHAR_CAP: usize = 4_000;
const CALL_NAME_MAX_CHARS: usize = 80;
/// AI-powered [`CallSummarizer`] that delegates to [`agent::complete`].
-#[derive(Debug, Default, Clone, Copy)]
-pub struct AiCallSummarizer;
+#[derive(Clone)]
+pub struct AiCallSummarizer {
+ recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,
+}
impl AiCallSummarizer {
- /// Create a new [`AiCallSummarizer`].
- pub fn new() -> Self {
- Self
+ /// Create a new [`AiCallSummarizer`] that records usage via `recorder`.
+ pub fn new(recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>) -> Self {
+ Self { recorder }
}
}
@@ -144,6 +146,8 @@ impl CallSummarizer for AiCallSummarizer {
SUMMARIZATION_MODEL,
SUMMARIZATION_SYSTEM_PROMPT,
&user_message,
+ self.recorder.as_ref(),
+ ai_usage::UsageContext::system(ai_usage::AiFeature::CallSummary),
)
.await
.inspect_err(|e| {
@@ -176,11 +180,17 @@ impl CallSummarizer for AiCallSummarizer {
let user_message = format!("Summary:\n\n{summary_for_prompt}");
- let raw = agent::complete(SUMMARIZATION_MODEL, CALL_NAME_SYSTEM_PROMPT, &user_message)
- .await
- .inspect_err(|e| {
- tracing::error!(error = ?e, %call_id, "ai call naming failed");
- })?;
+ let raw = agent::complete(
+ SUMMARIZATION_MODEL,
+ CALL_NAME_SYSTEM_PROMPT,
+ &user_message,
+ self.recorder.as_ref(),
+ ai_usage::UsageContext::system(ai_usage::AiFeature::CallSummary),
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error = ?e, %call_id, "ai call naming failed");
+ })?;
Ok(sanitize_call_name(&raw))
}
@@ -210,6 +220,8 @@ impl CallSummarizer for AiCallSummarizer {
SUMMARIZATION_MODEL,
CUSTOM_SPEAKER_SYSTEM_PROMPT,
&user_message,
+ self.recorder.as_ref(),
+ ai_usage::UsageContext::system(ai_usage::AiFeature::CallSummary),
)
.await
.inspect_err(|e| {
diff --git a/rust/cloud-storage/channel_bots/Cargo.toml b/rust/cloud-storage/channel_bots/Cargo.toml
index febf7eed80..ea511002eb 100644
--- a/rust/cloud-storage/channel_bots/Cargo.toml
+++ b/rust/cloud-storage/channel_bots/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[dependencies]
agent = { path = "../agent" }
+ai_usage = { path = "../ai_usage" }
ai_tools = { path = "../ai_tools" }
ai_toolset = { path = "../ai_toolset" }
anyhow = { workspace = true }
diff --git a/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs b/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs
index 92ce9b7ad1..5130ee27dd 100644
--- a/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs
+++ b/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs
@@ -22,7 +22,7 @@ impl AgentLoopResponder {
/// Create a responder from a pre-configured tool context and toolset.
pub fn new(tool_context: ToolServiceContext, tools: ToolSetWithPrompt) -> Self {
Self {
- agent_loop: AgentLoop::new(),
+ agent_loop: AgentLoop::new(tool_context.recorder.clone()),
tool_context: Arc::new(tool_context),
toolset: tools.toolset,
system_prompt: format!("{}{}", prompt::channel_mention::PROMPT, tools.prompt),
@@ -38,13 +38,17 @@ impl AgentResponder for AgentLoopResponder {
let toolset: Arc<dyn ai_toolset::ToolSet<ToolServiceContext> + Send + Sync> =
self.toolset.clone();
+ let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::ChannelBot, user_id);
+ // Carry the feature on the context so tool-spawned subagents attribute to it.
+ let mut tool_context = (*self.tool_context).clone();
+ tool_context.usage_context = usage_ctx.clone();
let mut session = self
.agent_loop
.session(
toolset,
- self.tool_context.clone(),
+ Arc::new(tool_context),
&self.system_prompt,
- user_id,
+ usage_ctx,
)
.await;
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 3669f6d7f0..956bb2e46c 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -25,6 +25,7 @@ local_queue = []
[dependencies]
agent = { path = "../agent", features = ["debug-messages"] }
+ai_usage = { path = "../ai_usage" }
aho-corasick = "1.1.3"
attachment = { path = "../attachment", features = ["provider"] }
non_empty = { path = "../non_empty" }
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index d7b2cef35b..f00991991b 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -54,6 +54,10 @@ pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;
pub type DcsMemoryService =
memory::domain::service::MemoryServiceImpl<memory::outbound::pg_memory_repo::PgMemoryRepo>;
+/// The AI cost service wired to the Postgres usage repo.
+pub type DcsUsageService =
+ ai_usage::domain::service::UsageServiceImpl<ai_usage::outbound::PgUsageRepo>;
+
/// Concrete MCP router state for DCS.
pub type DcsMcpRouterState = mcp_client::inbound::McpRouterState<
mcp_client::outbound::pg_server_repo::PgServerRepo,
@@ -81,6 +85,7 @@ pub struct ApiContext {
pub stream_repo: Arc<dyn StreamRepo>,
pub document_tool_context: ToolDocumentToolContext,
pub memory_service: Arc<DcsMemoryService>,
+ pub usage_service: Arc<DcsUsageService>,
pub properties_tool_context: ToolPropertiesToolContext,
pub email_tool_context: ToolEmailToolContext,
pub call_tool_context: ToolCallToolContext,
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index bae5de0480..ad7d9d7ef6 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -328,6 +328,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
schedule_tool_context: ai_tools::no_op_schedule_context(),
anthropic_tool_context: ai_tools::build_anthropic_tool_context_test(),
+ recorder: ai_usage::pg_recorder(pool.clone()),
+ usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
};
let all_tools = ai_tools::all_tools();
let all_tools_toolset = all_tools.toolset.clone();
@@ -342,6 +344,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
all_tools,
));
+ let usage_service = Arc::new(ai_usage::domain::service::UsageServiceImpl::new(
+ ai_usage::outbound::PgUsageRepo::new(pool.clone()),
+ ));
+
let api_context = ApiContext {
db: pool.clone(),
sqs_client: Arc::new(sqs_client),
@@ -364,6 +370,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
stream_repo: MockStreamRepo::new(),
document_tool_context: document_tool_context.clone(),
memory_service,
+ usage_service,
properties_tool_context,
email_tool_context,
call_tool_context,
diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
index 871ef4457c..b0664ff1b1 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
@@ -71,6 +71,7 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {
fn api_router(api_context: ApiContext) -> Router {
let memory_service = api_context.memory_service.clone();
+ let usage_service = api_context.usage_service.clone();
let mcp_state = api_context.mcp_state.clone();
@@ -95,6 +96,7 @@ fn api_router(api_context: ApiContext) -> Router {
.nest("/preview", preview::router())
.nest("/id_mapping", id_mapping::router())
.merge(memory::inbound::axum_router::memory_router(memory_service))
+ .merge(ai_usage::inbound::ai_usage_router(usage_service))
.merge(mcp_client::inbound::mcp_router(mcp_state.clone()))
.with_state(api_context.clone())
.route(
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
index e85654b396..0aad732f3b 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
@@ -512,10 +512,16 @@ fn stream_and_save_message(
let toolset: Arc<dyn ai_toolset::ToolSet<_> + Send + Sync> = Arc::new(
mcp_client::domain::service::CombinedToolSet::new(static_tools, &mcp_records).await,
);
- let agent_loop = AgentLoop::new().with_model(&model);
+ let agent_loop =
+ AgentLoop::new(tool_context.recorder.clone()).with_model(&model);
let rig_messages = agent::to_rig_messages(&request);
+ let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::Chat, user_id.clone())
+ .with_entity(macro_uuid::string_to_uuid(&chat_id).ok());
+ // Carry the feature on the context so tool-spawned subagents attribute to it.
+ let mut tool_context = tool_context;
+ tool_context.usage_context = usage_ctx.clone();
let mut session = agent_loop
- .session(toolset, Arc::new(tool_context), &system_prompt, user_id.clone())
+ .session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)
.await;
// Create the AI stream - yield error if it fails
diff --git a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
index 1a43d3459a..c95e7f072a 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
@@ -106,14 +106,14 @@ pub async fn structured_completion(
};
let rig_messages = agent::to_rig_messages(&[user_message]);
- let agent_loop = AgentLoop::new().with_model(model);
+ let agent_loop = AgentLoop::new(ctx.tool_service_context.recorder.clone()).with_model(model);
+ let usage_ctx =
+ ai_usage::UsageContext::new(ai_usage::AiFeature::DynamicCompletionsApi, user_id.clone());
+ // Carry the feature on the context so tool-spawned subagents attribute to it.
+ let mut tool_context = ctx.tool_service_context.clone();
+ tool_context.usage_context = usage_ctx.clone();
let mut session = agent_loop
- .session(
- toolset,
- Arc::new(ctx.tool_service_context.clone()),
- &system_prompt,
- user_id,
- )
+ .session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)
.await;
let mut ai_stream =
@@ -169,6 +169,8 @@ pub async fn structured_completion(
&system_prompt,
rig_messages,
request.output_schema,
+ ctx.tool_service_context.recorder.as_ref(),
+ ai_usage::UsageContext::new(ai_usage::AiFeature::DynamicCompletionsApi, user_id),
)
.await
.map_err(|e| StructuredCompletionError {
diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
index 019cd73162..11b4fa2a2f 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
@@ -17,6 +17,7 @@ use crate::model::{
response::attachments::GetChatsForAttachmentResponse,
stream::{ChatStream, SendChatMessagePayload, StreamError, ToolSet},
};
+use ai_usage::inbound::axum_router::{self as ai_usage_api};
use mcp_client::inbound::axum_router::{
self as mcp_api, AddServerRequest, ServerResponse, StartAuthRequest, StartAuthResponse,
UpdateServerRequest,
@@ -83,6 +84,8 @@ use utoipa::OpenApi;
stream_stop::stop_chat_stream,
structured_completion::structured_completion,
memory_api::get_memory_handler,
+ ai_usage_api::get_usage_handler,
+ ai_usage_api::set_pricing_handler,
mcp_api::list_servers,
mcp_api::add_server,
mcp_api::update_server,
@@ -171,6 +174,17 @@ use utoipa::OpenApi;
MemoryResponse,
MemoryErrorBody,
+ // AI cost
+ ai_usage_api::UsageRequest,
+ ai_usage_api::SetPricingRequest,
+ ai_usage_api::ErrorBody,
+ ai_usage::UsageSummary,
+ ai_usage::FeatureUsage,
+ ai_usage::CompletionUsage,
+ ai_usage::Usage,
+ ai_usage::Price,
+ ai_usage::AiFeature,
+
// MCP
ServerResponse,
AddServerRequest,
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index ce2eabeaba..93af1ed7ec 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -385,6 +385,8 @@ async fn main() -> anyhow::Result<()> {
team_tool_context: ai_tools::build_team_tool_context(db.clone()),
schedule_tool_context: ai_tools::NoOpScheduleContext,
anthropic_tool_context: ai_tools::build_anthropic_tool_context(),
+ recorder: ai_usage::pg_recorder(db.clone()),
+ usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
};
let all_tools = ai_tools::all_tools();
let all_tools_toolset = all_tools.toolset.clone();
@@ -402,6 +404,14 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized memory service");
+ // Build the AI cost service. It backs both the admin query/pricing router
+ // and the usage recorder threaded through the tool service context.
+ let usage_service = Arc::new(ai_usage::domain::service::UsageServiceImpl::new(
+ ai_usage::outbound::PgUsageRepo::new(db.clone()),
+ ));
+
+ tracing::info!("initialized ai cost service");
+
let mcp_credentials_key_b64 = match config.environment {
Environment::Local => config.mcp_credentials_key_secret_name.clone(),
_ => secretsmanager_client
@@ -448,6 +458,7 @@ async fn main() -> anyhow::Result<()> {
stream_repo,
document_tool_context,
memory_service,
+ usage_service,
properties_tool_context,
email_tool_context: email_tool_context.clone(),
call_tool_context,
diff --git a/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs b/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs
index 9559cfa2b1..e1b13447f8 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs
@@ -55,7 +55,13 @@ async fn rename_initial_chat(
stream_id: String,
initial_question: String,
) -> anyhow::Result<()> {
- let name = generate_chat_name(&initial_question).await?;
+ let name = generate_chat_name(
+ &initial_question,
+ user_id.clone(),
+ &chat_id,
+ ctx.tool_service_context.recorder.as_ref(),
+ )
+ .await?;
if name.is_empty() {
anyhow::bail!("generated chat name was empty");
}
@@ -91,13 +97,26 @@ async fn rename_initial_chat(
Ok(())
}
-async fn generate_chat_name(initial_question: &str) -> anyhow::Result<String> {
+async fn generate_chat_name(
+ initial_question: &str,
+ user_id: MacroUserIdStr<'static>,
+ chat_id: &str,
+ recorder: &dyn ai_usage::UsageRecorder,
+) -> anyhow::Result<String> {
let rename_request = format!(
"<chat_first_message>\n{}\n</chat_first_message>\n\nGenerate the chat title now.",
initial_question.trim()
);
- let response =
- agent::complete(AgentModel::Fast, CHAT_RENAME_SYSTEM_PROMPT, &rename_request).await?;
+ let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::ChatRename, user_id)
+ .with_entity(macro_uuid::string_to_uuid(chat_id).ok());
+ let response = agent::complete(
+ AgentModel::Fast,
+ CHAT_RENAME_SYSTEM_PROMPT,
+ &rename_request,
+ recorder,
+ usage_ctx,
+ )
+ .await?;
Ok(clean_chat_name(&response))
}
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 51b6b3e57b..8433d67ea4 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -36,6 +36,7 @@ bytes = { workspace = true }
bzip2 = { workspace = true, default-features = false, features = [
"libbz2-rs-sys",
] }
+ai_usage = { path = "../ai_usage" }
analytics_client = { path = "../analytics_client" }
cal = { path = "../cal", features = ["axum", "outbound"] }
call = { path = "../call" }
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 8078eb5e0a..3602142f3d 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -465,7 +465,7 @@ async fn main() -> anyhow::Result<()> {
recording_storage,
config.livekit_server_url.as_ref(),
)
- .with_summarizer(AiCallSummarizer::new());
+ .with_summarizer(AiCallSummarizer::new(ai_usage::pg_recorder(db.clone())));
if let Some(secret) = internal_call_secret {
call_service_builder = call_service_builder.with_internal_call_secret(secret);
}
@@ -554,7 +554,7 @@ async fn main() -> anyhow::Result<()> {
TextEmbedding3Small::new(openai_api_key),
PgTaskVectorDb::new(db.clone()),
NoOpReranker,
- Arc::new(AgentDuplicateJudge::new()),
+ Arc::new(AgentDuplicateJudge::new(ai_usage::pg_recorder(db.clone()))),
Arc::new(ConnectionGatewayTaskDedupNotifier::new(
conn_gateway_client.clone(),
)),
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 31a406f64c..c8ccae1a67 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -101,6 +101,7 @@ setup_test_envs:
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./referral/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./chat/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./memory/.env
+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./ai_usage/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./call/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./backfill_entity_access/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./entity_access_management/.env
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260616194726_ai_cost_usage_and_pricing.sql b/rust/cloud-storage/macro_db_client/migrations/20260616194726_ai_cost_usage_and_pricing.sql
new file mode 100644
index 0000000000..67f0fe60a1
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260616194726_ai_cost_usage_and_pricing.sql
@@ -0,0 +1,70 @@
+-- AI cost logging: per-completion usage rows and a per-model pricing table.
+
+-- Per-model pricing, keyed by the raw model api id (e.g. "claude-opus-4-8").
+-- Updated via the ai_cost set_pricing endpoint, which also recomputes the
+-- price of every ai_usage row for that model.
+CREATE TABLE ai_pricing (
+ model TEXT PRIMARY KEY,
+ price_per_million_in REAL NOT NULL,
+ price_per_million_out REAL NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+-- One row per completion round-trip. Price columns are nullable: when a model
+-- has no entry in ai_pricing at record time, the price is left NULL and can be
+-- backfilled later via set_pricing.
+CREATE TABLE ai_usage (
+ id UUID PRIMARY KEY,
+ feature TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ entity UUID,
+ model TEXT NOT NULL,
+ input_tokens BIGINT NOT NULL,
+ output_tokens BIGINT NOT NULL,
+ price_per_million_in REAL,
+ price_per_million_out REAL,
+ total REAL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX ai_usage_created_at_idx ON ai_usage (created_at DESC);
+CREATE INDEX ai_usage_feature_idx ON ai_usage (feature);
+CREATE INDEX ai_usage_user_id_idx ON ai_usage (user_id);
+CREATE INDEX ai_usage_model_idx ON ai_usage (model);
+
+-- Seed known model prices (USD per million tokens). Unknown models record a
+-- NULL price until corrected via the set_pricing endpoint.
+--
+-- Anthropic prices are from the Claude pricing catalog; OpenAI prices are from
+-- OpenAI's published pricing page. Either can be corrected at runtime via
+-- set_pricing.
+INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out) VALUES
+ -- Anthropic
+ ('claude-fable-5', 10.0, 50.0),
+ ('claude-mythos-5', 10.0, 50.0),
+ ('claude-opus-4-8', 5.0, 25.0),
+ ('claude-opus-4-7', 5.0, 25.0),
+ ('claude-opus-4-6', 5.0, 25.0),
+ ('claude-opus-4-5', 5.0, 25.0),
+ ('claude-opus-4-1', 15.0, 75.0),
+ ('claude-opus-4-0', 15.0, 75.0),
+ ('claude-sonnet-4-6', 3.0, 15.0),
+ ('claude-sonnet-4-5', 3.0, 15.0),
+ ('claude-sonnet-4-0', 3.0, 15.0),
+ ('claude-haiku-4-5', 1.0, 5.0),
+ ('claude-3-7-sonnet', 3.0, 15.0),
+ ('claude-3-5-sonnet', 3.0, 15.0),
+ ('claude-3-5-haiku', 0.8, 4.0),
+ ('claude-3-opus', 15.0, 75.0),
+ ('claude-3-haiku', 0.25, 1.25),
+ -- OpenAI (per the OpenAI pricing page)
+ ('gpt-5.5', 5.0, 30.0),
+ ('gpt-5.5-pro', 30.0, 180.0),
+ ('gpt-5.4', 2.5, 15.0),
+ ('gpt-5.4-mini', 0.75, 4.5),
+ ('gpt-5.4-nano', 0.2, 1.25),
+ ('gpt-5.4-pro', 30.0, 180.0),
+ ('gpt-5.3-codex', 1.75, 14.0),
+ -- `gpt-5-mini` is the id this codebase emits for the fast OpenAI tier; it is
+ -- not separately listed, so it is priced at the current mini tier.
+ ('gpt-5-mini', 0.75, 4.5);
diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.toml
index e06f1a15a2..49f2beeb36 100644
--- a/rust/cloud-storage/mcp_service/Cargo.toml
+++ b/rust/cloud-storage/mcp_service/Cargo.toml
@@ -6,6 +6,7 @@ publish = false
version = "0.1.0"
[dependencies]
+ai_usage = { path = "../ai_usage" }
ai_tools = { path = "../ai_tools" }
ai_toolset = { path = "../ai_toolset" }
anyhow = { workspace = true }
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 531031a981..5ea2c15632 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -337,6 +337,8 @@ async fn build_tool_context(
team_tool_context: ai_tools::build_team_tool_context(db.clone()),
schedule_tool_context: NoOpScheduleContext,
anthropic_tool_context: ai_tools::build_anthropic_tool_context(),
+ recorder: ai_usage::pg_recorder(db.clone()),
+ usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
};
tracing::info!("initialized tool context");
diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.toml
index 0b3ab3f6e6..64c307ca81 100644
--- a/rust/cloud-storage/memory/Cargo.toml
+++ b/rust/cloud-storage/memory/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[dependencies]
agent = { path = "../agent" }
+ai_usage = { path = "../ai_usage" }
ai_tools = { path = "../ai_tools" }
ai_toolset = { path = "../ai_toolset" }
anyhow = { workspace = true }
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index b97d028601..f8b5641502 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -230,5 +230,7 @@ pub async fn build_tool_service_context(
team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
schedule_tool_context: ai_tools::NoOpScheduleContext,
anthropic_tool_context: ai_tools::build_anthropic_tool_context(),
+ recorder: ai_usage::pg_recorder(pool.clone()),
+ usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
})
}
diff --git a/rust/cloud-storage/memory/src/domain/service.rs b/rust/cloud-storage/memory/src/domain/service.rs
index c0c47c2580..1423ab2295 100644
--- a/rust/cloud-storage/memory/src/domain/service.rs
+++ b/rust/cloud-storage/memory/src/domain/service.rs
@@ -166,16 +166,16 @@ where
previous_memory.as_deref(),
);
- let agent_loop = AgentLoop::new().with_model(GENERATION_MODEL);
+ let agent_loop =
+ AgentLoop::new(self.tool_context.recorder.clone()).with_model(GENERATION_MODEL);
let toolset: Arc<dyn ai_toolset::ToolSet<_> + Send + Sync> =
self.tools.toolset.clone() as _;
+ let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::Memory, user.clone());
+ // Carry the feature on the context so tool-spawned subagents attribute to it.
+ let mut tool_context = self.tool_context.clone();
+ tool_context.usage_context = usage_ctx.clone();
let mut session = agent_loop
- .session(
- toolset,
- Arc::new(self.tool_context.clone()),
- &system_prompt,
- user.clone(),
- )
+ .session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)
.await;
let user_msg = ChatMessage {
@@ -209,7 +209,7 @@ where
}
// 2nd pass: judge the memory quality
- judge_memory(&memory).await?;
+ judge_memory(&memory, user.clone(), self.tool_context.recorder.as_ref()).await?;
self.memory_repo.save_memory(&memory, user).await?;
Ok(memory)
@@ -245,8 +245,12 @@ fn build_generation_system_prompt(
prompt
}
-#[tracing::instrument(skip(memory), err)]
-async fn judge_memory(memory: &str) -> super::Result<()> {
+#[tracing::instrument(skip(memory, user, recorder), err)]
+async fn judge_memory(
+ memory: &str,
+ user: macro_user_id::user_id::MacroUserIdStr<'static>,
+ recorder: &dyn ai_usage::UsageRecorder,
+) -> super::Result<()> {
let user_message = format!(
"Evaluate this memory and respond with ONLY a JSON object \
(no markdown, no code fences):\n\
@@ -254,9 +258,15 @@ async fn judge_memory(memory: &str) -> super::Result<()> {
---\n\n{memory}"
);
- let response = agent::complete(JUDGE_MODEL, JUDGE_PROMPT, &user_message)
- .await
- .map_err(|e| anyhow::anyhow!(e))?;
+ let response = agent::complete(
+ JUDGE_MODEL,
+ JUDGE_PROMPT,
+ &user_message,
+ recorder,
+ ai_usage::UsageContext::new(ai_usage::AiFeature::Memory, user),
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
let judgement: MemoryJudgement = serde_json::from_str(response.trim())
.map_err(|e| anyhow::anyhow!("failed to parse judge response: {e}\nraw: {response}"))?;
diff --git a/rust/cloud-storage/scheduled_action/Cargo.toml b/rust/cloud-storage/scheduled_action/Cargo.toml
index e9e6f6fdb3..574b5aaba6 100644
--- a/rust/cloud-storage/scheduled_action/Cargo.toml
+++ b/rust/cloud-storage/scheduled_action/Cargo.toml
@@ -28,6 +28,7 @@ macro_uuid = { path = "../macro_uuid"}
chrono = { workspace = true}
chrono-tz = { version = "0.10.4", features = ["serde"] }
agent = { path = "../agent" }
+ai_usage = { path = "../ai_usage" }
tokio = { workspace = true }
futures = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
index 9ec7f5880b..cd8973a1b8 100644
--- a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
+++ b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
@@ -129,14 +129,14 @@ async fn run_tool_loop(
};
let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = tools.toolset;
- let agent_loop = AgentLoop::new().with_model(&agent_task.model);
+ let agent_loop = AgentLoop::new(tool_context.recorder.clone()).with_model(&agent_task.model);
+ let usage_ctx =
+ ai_usage::UsageContext::new(ai_usage::AiFeature::Automation, action.owner.clone());
+ // Carry the feature on the context so tool-spawned subagents attribute to it.
+ let mut tool_context = tool_context.clone();
+ tool_context.usage_context = usage_ctx.clone();
let mut session = agent_loop
- .session(
- toolset,
- Arc::new(tool_context.clone()),
- &system_prompt,
- action.owner.clone(),
- )
+ .session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)
.await;
let user_msg = ChatMessage {
diff --git a/rust/cloud-storage/task_dedup/Cargo.toml b/rust/cloud-storage/task_dedup/Cargo.toml
index d65e51b880..d0bcbcf2c5 100644
--- a/rust/cloud-storage/task_dedup/Cargo.toml
+++ b/rust/cloud-storage/task_dedup/Cargo.toml
@@ -30,6 +30,7 @@ default = ["backfill"]
[dependencies]
agent = { path = "../agent" }
+ai_usage = { path = "../ai_usage" }
anyhow = { workspace = true }
async-trait = { workspace = true }
connection_gateway_client = { path = "../connection_gateway_client" }
diff --git a/rust/cloud-storage/task_dedup/src/outbound/judge.rs b/rust/cloud-storage/task_dedup/src/outbound/judge.rs
index ce6490421b..08968262a0 100644
--- a/rust/cloud-storage/task_dedup/src/outbound/judge.rs
+++ b/rust/cloud-storage/task_dedup/src/outbound/judge.rs
@@ -42,6 +42,7 @@ In the reason, briefly compare the concrete categories that matter most for the
/// can't fabricate matches.
pub struct AgentDuplicateJudge {
model: AgentModel,
+ recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,
}
#[derive(Debug, Deserialize, Serialize)]
@@ -52,15 +53,19 @@ struct DuplicateJudgeOutput {
impl AgentDuplicateJudge {
/// Creates a new judge using the fast agent model.
- pub fn new() -> Self {
+ pub fn new(recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>) -> Self {
Self {
model: AgentModel::Fast,
+ recorder,
}
}
/// Creates a new judge with an explicit agent model.
- pub fn with_model(model: AgentModel) -> Self {
- Self { model }
+ pub fn with_model(
+ model: AgentModel,
+ recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,
+ ) -> Self {
+ Self { model, recorder }
}
fn unavailable(&self, reason: &str) -> JudgeResult {
@@ -72,12 +77,6 @@ impl AgentDuplicateJudge {
}
}
-impl Default for AgentDuplicateJudge {
- fn default() -> Self {
- Self::new()
- }
-}
-
#[async_trait]
impl TaskDuplicateJudge for AgentDuplicateJudge {
async fn judge(&self, left: &str, right: &str) -> JudgeResult {
@@ -110,6 +109,8 @@ impl TaskDuplicateJudge for AgentDuplicateJudge {
DUPLICATE_JUDGE_SYSTEM_PROMPT,
vec![Message::user(prompt)],
schema,
+ self.recorder.as_ref(),
+ ai_usage::UsageContext::system(ai_usage::AiFeature::Automation),
)
.await;