Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

feat(app-server): expose account token usage [1 of 2] (#25344)

Felipe Coury5e62c735b2b2
diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json
index c6e1aa3302..6d9be4ec02 100644
--- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json
+++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json
@@ -5969,6 +5969,29 @@
"title": "Account/rateLimits/readRequest",
"type": "object"
},
+ {
+ "properties": {
+ "id": {
+ "$ref": "#/definitions/RequestId"
+ },
+ "method": {
+ "enum": [
+ "account/usage/read"
+ ],
+ "title": "Account/usage/readRequestMethod",
+ "type": "string"
+ },
+ "params": {
+ "type": "null"
+ }
+ },
+ "required": [
+ "id",
+ "method"
+ ],
+ "title": "Account/usage/readRequest",
+ "type": "object"
+ },
{
"properties": {
"id": {
diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json
index 10bde05597..a5578e0072 100644
--- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json
+++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json
@@ -1833,6 +1833,29 @@
"title": "Account/rateLimits/readRequest",
"type": "object"
},
+ {
+ "properties": {
+ "id": {
+ "$ref": "#/definitions/v2/RequestId"
+ },
+ "method": {
+ "enum": [
+ "account/usage/read"
+ ],
+ "title": "Account/usage/readRequestMethod",
+ "type": "string"
+ },
+ "params": {
+ "type": "null"
+ }
+ },
+ "required": [
+ "id",
+ "method"
+ ],
+ "title": "Account/usage/readRequest",
+ "type": "object"
+ },
{
"properties": {
"id": {
@@ -5759,6 +5782,62 @@
"title": "AccountRateLimitsUpdatedNotification",
"type": "object"
},
+ "AccountTokenUsageDailyBucket": {
+ "properties": {
+ "startDate": {
+ "type": "string"
+ },
+ "tokens": {
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "startDate",
+ "tokens"
+ ],
+ "type": "object"
+ },
+ "AccountTokenUsageSummary": {
+ "properties": {
+ "currentStreakDays": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "lifetimeTokens": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "longestRunningTurnSec": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "longestStreakDays": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "peakDailyTokens": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "type": "object"
+ },
"AccountUpdatedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -9626,6 +9705,28 @@
"title": "GetAccountResponse",
"type": "object"
},
+ "GetAccountTokenUsageResponse": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "properties": {
+ "dailyUsageBuckets": {
+ "items": {
+ "$ref": "#/definitions/v2/AccountTokenUsageDailyBucket"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "summary": {
+ "$ref": "#/definitions/v2/AccountTokenUsageSummary"
+ }
+ },
+ "required": [
+ "summary"
+ ],
+ "title": "GetAccountTokenUsageResponse",
+ "type": "object"
+ },
"GitInfo": {
"properties": {
"branch": {
diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json
index e4c91e7586..36b95b4f64 100644
--- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json
+++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json
@@ -104,6 +104,62 @@
"title": "AccountRateLimitsUpdatedNotification",
"type": "object"
},
+ "AccountTokenUsageDailyBucket": {
+ "properties": {
+ "startDate": {
+ "type": "string"
+ },
+ "tokens": {
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "startDate",
+ "tokens"
+ ],
+ "type": "object"
+ },
+ "AccountTokenUsageSummary": {
+ "properties": {
+ "currentStreakDays": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "lifetimeTokens": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "longestRunningTurnSec": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "longestStreakDays": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "peakDailyTokens": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "type": "object"
+ },
"AccountUpdatedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -2679,6 +2735,29 @@
"title": "Account/rateLimits/readRequest",
"type": "object"
},
+ {
+ "properties": {
+ "id": {
+ "$ref": "#/definitions/RequestId"
+ },
+ "method": {
+ "enum": [
+ "account/usage/read"
+ ],
+ "title": "Account/usage/readRequestMethod",
+ "type": "string"
+ },
+ "params": {
+ "type": "null"
+ }
+ },
+ "required": [
+ "id",
+ "method"
+ ],
+ "title": "Account/usage/readRequest",
+ "type": "object"
+ },
{
"properties": {
"id": {
@@ -6079,6 +6158,28 @@
"title": "GetAccountResponse",
"type": "object"
},
+ "GetAccountTokenUsageResponse": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "properties": {
+ "dailyUsageBuckets": {
+ "items": {
+ "$ref": "#/definitions/AccountTokenUsageDailyBucket"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "summary": {
+ "$ref": "#/definitions/AccountTokenUsageSummary"
+ }
+ },
+ "required": [
+ "summary"
+ ],
+ "title": "GetAccountTokenUsageResponse",
+ "type": "object"
+ },
"GitInfo": {
"properties": {
"branch": {
diff --git a/codex-rs/app-server-protocol/schema/json/v2/GetAccountTokenUsageResponse.json b/codex-rs/app-server-protocol/schema/json/v2/GetAccountTokenUsageResponse.json
new file mode 100644
index 0000000000..557a297ce1
--- /dev/null
+++ b/codex-rs/app-server-protocol/schema/json/v2/GetAccountTokenUsageResponse.json
@@ -0,0 +1,80 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "definitions": {
+ "AccountTokenUsageDailyBucket": {
+ "properties": {
+ "startDate": {
+ "type": "string"
+ },
+ "tokens": {
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "startDate",
+ "tokens"
+ ],
+ "type": "object"
+ },
+ "AccountTokenUsageSummary": {
+ "properties": {
+ "currentStreakDays": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "lifetimeTokens": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "longestRunningTurnSec": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "longestStreakDays": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "peakDailyTokens": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "type": "object"
+ }
+ },
+ "properties": {
+ "dailyUsageBuckets": {
+ "items": {
+ "$ref": "#/definitions/AccountTokenUsageDailyBucket"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "summary": {
+ "$ref": "#/definitions/AccountTokenUsageSummary"
+ }
+ },
+ "required": [
+ "summary"
+ ],
+ "title": "GetAccountTokenUsageResponse",
+ "type": "object"
+}
\ No newline at end of file
diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts
index e19ac2dfde..c91792c726 100644
--- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts
+++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts
@@ -86,4 +86,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta
/**
* Request from the client to the server.
*/
-export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/goal/set", id: RequestId, params: ThreadGoalSetParams, } | { "method": "thread/goal/get", id: RequestId, params: ThreadGoalGetParams, } | { "method": "thread/goal/clear", id: RequestId, params: ThreadGoalClearParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/extraRoots/set", id: RequestId, params: SkillsExtraRootsSetParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, };
+export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/goal/set", id: RequestId, params: ThreadGoalSetParams, } | { "method": "thread/goal/get", id: RequestId, params: ThreadGoalGetParams, } | { "method": "thread/goal/clear", id: RequestId, params: ThreadGoalClearParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/extraRoots/set", id: RequestId, params: SkillsExtraRootsSetParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/usage/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, };
diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AccountTokenUsageDailyBucket.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AccountTokenUsageDailyBucket.ts
new file mode 100644
index 0000000000..a92c6c00c4
--- /dev/null
+++ b/codex-rs/app-server-protocol/schema/typescript/v2/AccountTokenUsageDailyBucket.ts
@@ -0,0 +1,5 @@
+// GENERATED CODE! DO NOT MODIFY BY HAND!
+
+// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
+
+export type AccountTokenUsageDailyBucket = { startDate: string, tokens: bigint, };
diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AccountTokenUsageSummary.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AccountTokenUsageSummary.ts
new file mode 100644
index 0000000000..6f87acdaff
--- /dev/null
+++ b/codex-rs/app-server-protocol/schema/typescript/v2/AccountTokenUsageSummary.ts
@@ -0,0 +1,5 @@
+// GENERATED CODE! DO NOT MODIFY BY HAND!
+
+// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
+
+export type AccountTokenUsageSummary = { lifetimeTokens: bigint | null, peakDailyTokens: bigint | null, longestRunningTurnSec: bigint | null, currentStreakDays: bigint | null, longestStreakDays: bigint | null, };
diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/GetAccountTokenUsageResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/GetAccountTokenUsageResponse.ts
new file mode 100644
index 0000000000..175c915272
--- /dev/null
+++ b/codex-rs/app-server-protocol/schema/typescript/v2/GetAccountTokenUsageResponse.ts
@@ -0,0 +1,7 @@
+// GENERATED CODE! DO NOT MODIFY BY HAND!
+
+// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
+import type { AccountTokenUsageDailyBucket } from "./AccountTokenUsageDailyBucket";
+import type { AccountTokenUsageSummary } from "./AccountTokenUsageSummary";
+
+export type GetAccountTokenUsageResponse = { summary: AccountTokenUsageSummary, dailyUsageBuckets: Array<AccountTokenUsageDailyBucket> | null, };
diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts
index bb19c92bdf..727c049d10 100644
--- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts
+++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts
@@ -3,6 +3,8 @@
export type { Account } from "./Account";
export type { AccountLoginCompletedNotification } from "./AccountLoginCompletedNotification";
export type { AccountRateLimitsUpdatedNotification } from "./AccountRateLimitsUpdatedNotification";
+export type { AccountTokenUsageDailyBucket } from "./AccountTokenUsageDailyBucket";
+export type { AccountTokenUsageSummary } from "./AccountTokenUsageSummary";
export type { AccountUpdatedNotification } from "./AccountUpdatedNotification";
export type { ActivePermissionProfile } from "./ActivePermissionProfile";
export type { AddCreditsNudgeCreditType } from "./AddCreditsNudgeCreditType";
@@ -141,6 +143,7 @@ export type { FsWriteFileResponse } from "./FsWriteFileResponse";
export type { GetAccountParams } from "./GetAccountParams";
export type { GetAccountRateLimitsResponse } from "./GetAccountRateLimitsResponse";
export type { GetAccountResponse } from "./GetAccountResponse";
+export type { GetAccountTokenUsageResponse } from "./GetAccountTokenUsageResponse";
export type { GitInfo } from "./GitInfo";
export type { GrantedPermissionProfile } from "./GrantedPermissionProfile";
export type { GuardianApprovalReview } from "./GuardianApprovalReview";
diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs
index 47410551cf..a624387e4d 100644
--- a/codex-rs/app-server-protocol/src/protocol/common.rs
+++ b/codex-rs/app-server-protocol/src/protocol/common.rs
@@ -949,6 +949,12 @@ client_request_definitions! {
response: v2::GetAccountRateLimitsResponse,
},
+ GetAccountTokenUsage => "account/usage/read" {
+ params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
+ serialization: None,
+ response: v2::GetAccountTokenUsageResponse,
+ },
+
SendAddCreditsNudgeEmail => "account/sendAddCreditsNudgeEmail" {
params: v2::SendAddCreditsNudgeEmailParams,
serialization: global("account-auth"),
@@ -2372,6 +2378,24 @@ mod tests {
Ok(())
}
+ #[test]
+ fn serialize_get_account_token_usage() -> Result<()> {
+ let request = ClientRequest::GetAccountTokenUsage {
+ request_id: RequestId::Integer(1),
+ params: None,
+ };
+ assert_eq!(request.id(), &RequestId::Integer(1));
+ assert_eq!(request.method(), "account/usage/read");
+ assert_eq!(
+ json!({
+ "method": "account/usage/read",
+ "id": 1,
+ }),
+ serde_json::to_value(&request)?,
+ );
+ Ok(())
+ }
+
#[test]
fn serialize_client_response() -> Result<()> {
let cwd = absolute_path("/tmp");
diff --git a/codex-rs/app-server-protocol/src/protocol/v2/account.rs b/codex-rs/app-server-protocol/src/protocol/v2/account.rs
index 83f1bc02b8..58fc93cc76 100644
--- a/codex-rs/app-server-protocol/src/protocol/v2/account.rs
+++ b/codex-rs/app-server-protocol/src/protocol/v2/account.rs
@@ -258,6 +258,33 @@ pub struct GetAccountRateLimitsResponse {
pub rate_limits_by_limit_id: Option<HashMap<String, RateLimitSnapshot>>,
}
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(export_to = "v2/")]
+pub struct GetAccountTokenUsageResponse {
+ pub summary: AccountTokenUsageSummary,
+ pub daily_usage_buckets: Option<Vec<AccountTokenUsageDailyBucket>>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(export_to = "v2/")]
+pub struct AccountTokenUsageSummary {
+ pub lifetime_tokens: Option<i64>,
+ pub peak_daily_tokens: Option<i64>,
+ pub longest_running_turn_sec: Option<i64>,
+ pub current_streak_days: Option<i64>,
+ pub longest_streak_days: Option<i64>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(export_to = "v2/")]
+pub struct AccountTokenUsageDailyBucket {
+ pub start_date: String,
+ pub tokens: i64,
+}
+
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md
index d112eeff9d..b7fc6b82a3 100644
--- a/codex-rs/app-server/README.md
+++ b/codex-rs/app-server/README.md
@@ -1779,6 +1779,7 @@ Codex supports these authentication modes. The current mode is surfaced in `acco
- `account/logout` — sign out; triggers `account/updated`.
- `account/updated` (notify) — emitted whenever auth mode changes (`authMode`: `apikey`, `chatgpt`, or `null`) and includes the current ChatGPT `planType` when available.
- `account/rateLimits/read` — fetch ChatGPT rate limits and an optional effective monthly credit limit; updates arrive via `account/rateLimits/updated` (notify).
+- `account/usage/read` — fetch ChatGPT account token-activity summary and daily buckets.
- `account/rateLimits/updated` (notify) — emitted whenever a user's ChatGPT rate limits change. This is a sparse rolling update; merge available values into the most recent `account/rateLimits/read` response or refetch that snapshot.
- `account/sendAddCreditsNudgeEmail` — ask ChatGPT to email the workspace owner about depleted credits or a reached usage limit.
- `mcpServer/oauthLogin/completed` (notify) — emitted after a `mcpServer/oauth/login` flow finishes for a server; payload includes `{ name, success, error? }`.
diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs
index 6c578ce8e5..07bc06218e 100644
--- a/codex-rs/app-server/src/message_processor.rs
+++ b/codex-rs/app-server/src/message_processor.rs
@@ -1294,6 +1294,9 @@ impl MessageProcessor {
ClientRequest::GetAccountRateLimits { .. } => {
self.account_processor.get_account_rate_limits().await
}
+ ClientRequest::GetAccountTokenUsage { .. } => {
+ self.account_processor.get_account_token_usage().await
+ }
ClientRequest::SendAddCreditsNudgeEmail { params, .. } => {
self.account_processor
.send_add_credits_nudge_email(params)
diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs
index 0e94528a7a..00468b0a99 100644
--- a/codex-rs/app-server/src/request_processors.rs
+++ b/codex-rs/app-server/src/request_processors.rs
@@ -22,6 +22,8 @@ use codex_analytics::InputError;
use codex_analytics::TurnSteerRequestError;
use codex_app_server_protocol::Account;
use codex_app_server_protocol::AccountLoginCompletedNotification;
+use codex_app_server_protocol::AccountTokenUsageDailyBucket;
+use codex_app_server_protocol::AccountTokenUsageSummary;
use codex_app_server_protocol::AccountUpdatedNotification;
use codex_app_server_protocol::AddCreditsNudgeCreditType;
use codex_app_server_protocol::AddCreditsNudgeEmailStatus;
@@ -64,6 +66,7 @@ use codex_app_server_protocol::FeedbackUploadResponse;
use codex_app_server_protocol::GetAccountParams;
use codex_app_server_protocol::GetAccountRateLimitsResponse;
use codex_app_server_protocol::GetAccountResponse;
+use codex_app_server_protocol::GetAccountTokenUsageResponse;
use codex_app_server_protocol::GetAuthStatusParams;
use codex_app_server_protocol::GetAuthStatusResponse;
use codex_app_server_protocol::GetConversationSummaryParams;
@@ -266,6 +269,7 @@ use codex_app_server_protocol::WindowsSandboxSetupStartResponse;
use codex_arg0::Arg0DispatchPaths;
use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType;
use codex_backend_client::Client as BackendClient;
+use codex_backend_client::TokenUsageProfile;
use codex_chatgpt::connectors;
use codex_chatgpt::workspace_settings;
use codex_config::CloudConfigBundleLoadError;
diff --git a/codex-rs/app-server/src/request_processors/account_processor.rs b/codex-rs/app-server/src/request_processors/account_processor.rs
index 8ebfc037e1..21160d6810 100644
--- a/codex-rs/app-server/src/request_processors/account_processor.rs
+++ b/codex-rs/app-server/src/request_processors/account_processor.rs
@@ -2,6 +2,7 @@ use super::*;
// Duration before a browser ChatGPT login attempt is abandoned.
const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60);
+const ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
// The override is intentionally available only in debug builds, matching the login path below.
#[cfg(debug_assertions)]
const LOGIN_ISSUER_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER";
@@ -131,6 +132,14 @@ impl AccountRequestProcessor {
.map(|response| Some(response.into()))
}
+ pub(crate) async fn get_account_token_usage(
+ &self,
+ ) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
+ self.get_account_token_usage_response()
+ .await
+ .map(|response| Some(response.into()))
+ }
+
pub(crate) async fn send_add_credits_nudge_email(
&self,
params: SendAddCreditsNudgeEmailParams,
@@ -848,6 +857,55 @@ impl AccountRequestProcessor {
)
}
+ async fn get_account_token_usage_response(
+ &self,
+ ) -> Result<GetAccountTokenUsageResponse, JSONRPCErrorError> {
+ let Some(auth) = self.auth_manager.auth().await else {
+ return Err(invalid_request(
+ "codex account authentication required to read token usage",
+ ));
+ };
+
+ if !auth.uses_codex_backend() {
+ return Err(invalid_request(
+ "chatgpt authentication required to read token usage",
+ ));
+ }
+
+ let client = BackendClient::from_auth(self.config.chatgpt_base_url.clone(), &auth)
+ .map_err(|err| internal_error(format!("failed to construct backend client: {err}")))?;
+ let profile = tokio::time::timeout(
+ ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT,
+ client.get_token_usage_profile(),
+ )
+ .await
+ .map_err(|_| internal_error("token usage profile fetch timed out"))?
+ .map_err(|err| internal_error(format!("failed to fetch token usage profile: {err}")))?;
+ Ok(Self::account_token_usage_response(profile))
+ }
+
+ fn account_token_usage_response(profile: TokenUsageProfile) -> GetAccountTokenUsageResponse {
+ let stats = profile.stats;
+ GetAccountTokenUsageResponse {
+ summary: AccountTokenUsageSummary {
+ lifetime_tokens: stats.lifetime_tokens,
+ peak_daily_tokens: stats.peak_daily_tokens,
+ longest_running_turn_sec: stats.longest_running_turn_sec,
+ current_streak_days: stats.current_streak_days,
+ longest_streak_days: stats.longest_streak_days,
+ },
+ daily_usage_buckets: stats.daily_usage_buckets.map(|buckets| {
+ buckets
+ .into_iter()
+ .map(|bucket| AccountTokenUsageDailyBucket {
+ start_date: bucket.start_date,
+ tokens: bucket.tokens,
+ })
+ .collect()
+ }),
+ }
+ }
+
async fn send_add_credits_nudge_email_response(
&self,
params: SendAddCreditsNudgeEmailParams,
@@ -952,3 +1010,45 @@ impl AccountRequestProcessor {
Ok((primary, rate_limits_by_limit_id))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use codex_backend_client::TokenUsageProfileDailyBucket;
+ use codex_backend_client::TokenUsageProfileStats;
+ use pretty_assertions::assert_eq;
+
+ #[test]
+ fn account_token_usage_response_maps_profile_stats_and_daily_buckets() {
+ let response = AccountRequestProcessor::account_token_usage_response(TokenUsageProfile {
+ stats: TokenUsageProfileStats {
+ lifetime_tokens: Some(123),
+ peak_daily_tokens: Some(45),
+ longest_running_turn_sec: Some(67),
+ current_streak_days: Some(8),
+ longest_streak_days: Some(9),
+ daily_usage_buckets: Some(vec![TokenUsageProfileDailyBucket {
+ start_date: "2026-05-29".to_string(),
+ tokens: 10,
+ }]),
+ },
+ });
+
+ assert_eq!(
+ response,
+ GetAccountTokenUsageResponse {
+ summary: AccountTokenUsageSummary {
+ lifetime_tokens: Some(123),
+ peak_daily_tokens: Some(45),
+ longest_running_turn_sec: Some(67),
+ current_streak_days: Some(8),
+ longest_streak_days: Some(9),
+ },
+ daily_usage_buckets: Some(vec![AccountTokenUsageDailyBucket {
+ start_date: "2026-05-29".to_string(),
+ tokens: 10,
+ }]),
+ }
+ );
+ }
+}
diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs
index 24d2776590..52275eb4be 100644
--- a/codex-rs/backend-client/src/client.rs
+++ b/codex-rs/backend-client/src/client.rs
@@ -4,6 +4,7 @@ use crate::types::ConfigBundleResponse;
use crate::types::PaginatedListTaskListItem;
use crate::types::RateLimitReachedKind as BackendRateLimitReachedKind;
use crate::types::RateLimitStatusPayload;
+use crate::types::TokenUsageProfile;
use crate::types::TurnAttemptsSiblingTurnsResponse;
use anyhow::Result;
use codex_api::SharedAuthProvider;
@@ -313,6 +314,20 @@ impl Client {
self.decode_json(&url, &ct, &body)
}
+ pub async fn get_token_usage_profile(&self) -> Result<TokenUsageProfile> {
+ let url = self.token_usage_profile_url();
+ let req = self.http.get(&url).headers(self.headers());
+ let (body, ct) = self.exec_request(req, "GET", &url).await?;
+ self.decode_json(&url, &ct, &body)
+ }
+
+ fn token_usage_profile_url(&self) -> String {
+ match self.path_style {
+ PathStyle::CodexApi => format!("{}/api/codex/profiles/me", self.base_url),
+ PathStyle::ChatGptApi => format!("{}/wham/profiles/me", self.base_url),
+ }
+ }
+
pub async fn send_add_credits_nudge_email(
&self,
credit_type: AddCreditsNudgeCreditType,
@@ -883,29 +898,13 @@ mod tests {
#[test]
fn add_credits_nudge_email_uses_expected_paths_and_bodies() {
- let codex_client = Client {
- base_url: "https://example.test".to_string(),
- http: reqwest::Client::new(),
- auth_provider: codex_model_provider::unauthenticated_auth_provider(),
- user_agent: None,
- chatgpt_account_id: None,
- chatgpt_account_is_fedramp: false,
- path_style: PathStyle::CodexApi,
- };
+ let codex_client = test_client("https://example.test", PathStyle::CodexApi);
assert_eq!(
codex_client.send_add_credits_nudge_email_url(),
"https://example.test/api/codex/accounts/send_add_credits_nudge_email"
);
- let chatgpt_client = Client {
- base_url: "https://chatgpt.com/backend-api".to_string(),
- http: reqwest::Client::new(),
- auth_provider: codex_model_provider::unauthenticated_auth_provider(),
- user_agent: None,
- chatgpt_account_id: None,
- chatgpt_account_is_fedramp: false,
- path_style: PathStyle::ChatGptApi,
- };
+ let chatgpt_client = test_client("https://chatgpt.com/backend-api", PathStyle::ChatGptApi);
assert_eq!(
chatgpt_client.send_add_credits_nudge_email_url(),
"https://chatgpt.com/backend-api/wham/accounts/send_add_credits_nudge_email"
@@ -926,4 +925,31 @@ mod tests {
serde_json::json!({ "credit_type": "usage_limit" })
);
}
+
+ #[test]
+ fn token_usage_profile_uses_expected_paths() {
+ let codex_client = test_client("https://example.test", PathStyle::CodexApi);
+ assert_eq!(
+ codex_client.token_usage_profile_url(),
+ "https://example.test/api/codex/profiles/me"
+ );
+
+ let chatgpt_client = test_client("https://chatgpt.com/backend-api", PathStyle::ChatGptApi);
+ assert_eq!(
+ chatgpt_client.token_usage_profile_url(),
+ "https://chatgpt.com/backend-api/wham/profiles/me"
+ );
+ }
+
+ fn test_client(base_url: &str, path_style: PathStyle) -> Client {
+ Client {
+ base_url: base_url.to_string(),
+ http: reqwest::Client::new(),
+ auth_provider: codex_model_provider::unauthenticated_auth_provider(),
+ user_agent: None,
+ chatgpt_account_id: None,
+ chatgpt_account_is_fedramp: false,
+ path_style,
+ }
+ }
}
diff --git a/codex-rs/backend-client/src/lib.rs b/codex-rs/backend-client/src/lib.rs
index dfd7e816f6..e50fd8db40 100644
--- a/codex-rs/backend-client/src/lib.rs
+++ b/codex-rs/backend-client/src/lib.rs
@@ -14,4 +14,7 @@ pub use types::DeliveredRequirementsToml;
pub use types::DeliveredTomlFragment;
pub use types::PaginatedListTaskListItem;
pub use types::TaskListItem;
+pub use types::TokenUsageProfile;
+pub use types::TokenUsageProfileDailyBucket;
+pub use types::TokenUsageProfileStats;
pub use types::TurnAttemptsSiblingTurnsResponse;
diff --git a/codex-rs/backend-client/src/types.rs b/codex-rs/backend-client/src/types.rs
index 06989241fa..3ccacbc8c9 100644
--- a/codex-rs/backend-client/src/types.rs
+++ b/codex-rs/backend-client/src/types.rs
@@ -409,6 +409,27 @@ pub struct TurnAttemptsSiblingTurnsResponse {
pub sibling_turns: Vec<HashMap<String, Value>>,
}
+#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
+pub struct TokenUsageProfile {
+ pub stats: TokenUsageProfileStats,
+}
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
+pub struct TokenUsageProfileStats {
+ pub lifetime_tokens: Option<i64>,
+ pub peak_daily_tokens: Option<i64>,
+ pub longest_running_turn_sec: Option<i64>,
+ pub current_streak_days: Option<i64>,
+ pub longest_streak_days: Option<i64>,
+ pub daily_usage_buckets: Option<Vec<TokenUsageProfileDailyBucket>>,
+}
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
+pub struct TokenUsageProfileDailyBucket {
+ pub start_date: String,
+ pub tokens: i64,
+}
+
#[cfg(test)]
mod tests {
use super::*;