diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 83b086c237..9204ba4083 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -147,6 +147,63 @@ ], "type": "object" }, + "CodexAvatarAdminAwardGrantParams": { + "properties": { + "accountUserId": { + "type": "string" + }, + "avatarId": { + "type": "string" + }, + "awardId": { + "type": "string" + }, + "awardedAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "awardedBy": { + "type": [ + "string", + "null" + ] + }, + "metadataJson": { + "type": [ + "string", + "null" + ] + }, + "sourceRef": { + "type": [ + "string", + "null" + ] + }, + "sourceSummary": { + "type": [ + "string", + "null" + ] + }, + "sourceType": { + "type": "string" + } + }, + "required": [ + "accountUserId", + "avatarId", + "awardId", + "sourceType" + ], + "type": "object" + }, + "CodexAvatarAdminCapabilitiesReadParams": { + "type": "object" + }, "CodexAvatarEquipParams": { "properties": { "avatarId": { @@ -4600,6 +4657,54 @@ "title": "Avatar/equipRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "avatar/admin/award" + ], + "title": "Avatar/admin/awardRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CodexAvatarAdminAwardGrantParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Avatar/admin/awardRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "avatar/admin/capabilities/read" + ], + "title": "Avatar/admin/capabilities/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CodexAvatarAdminCapabilitiesReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Avatar/admin/capabilities/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 5f26d681f3..564a51055b 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 @@ -1367,6 +1367,54 @@ "title": "Avatar/equipRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "avatar/admin/award" + ], + "title": "Avatar/admin/awardRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/CodexAvatarAdminAwardGrantParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Avatar/admin/awardRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "avatar/admin/capabilities/read" + ], + "title": "Avatar/admin/capabilities/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/CodexAvatarAdminCapabilitiesReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Avatar/admin/capabilities/readRequest", + "type": "object" + }, { "properties": { "id": { @@ -5655,6 +5703,80 @@ ], "type": "string" }, + "CodexAvatarAdminAwardGrantParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "accountUserId": { + "type": "string" + }, + "avatarId": { + "type": "string" + }, + "awardId": { + "type": "string" + }, + "awardedAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "awardedBy": { + "type": [ + "string", + "null" + ] + }, + "metadataJson": { + "type": [ + "string", + "null" + ] + }, + "sourceRef": { + "type": [ + "string", + "null" + ] + }, + "sourceSummary": { + "type": [ + "string", + "null" + ] + }, + "sourceType": { + "type": "string" + } + }, + "required": [ + "accountUserId", + "avatarId", + "awardId", + "sourceType" + ], + "title": "CodexAvatarAdminAwardGrantParams", + "type": "object" + }, + "CodexAvatarAdminCapabilitiesReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "CodexAvatarAdminCapabilitiesReadParams", + "type": "object" + }, + "CodexAvatarAdminCapabilitiesReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "canGrantAwards": { + "type": "boolean" + } + }, + "required": [ + "canGrantAwards" + ], + "title": "CodexAvatarAdminCapabilitiesReadResponse", + "type": "object" + }, "CodexAvatarDefinition": { "properties": { "assetRef": { 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 3d613f3d6e..3040338e7d 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 @@ -1942,6 +1942,54 @@ "title": "Avatar/equipRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "avatar/admin/award" + ], + "title": "Avatar/admin/awardRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CodexAvatarAdminAwardGrantParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Avatar/admin/awardRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "avatar/admin/capabilities/read" + ], + "title": "Avatar/admin/capabilities/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CodexAvatarAdminCapabilitiesReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Avatar/admin/capabilities/readRequest", + "type": "object" + }, { "properties": { "id": { @@ -2260,6 +2308,80 @@ ], "title": "ClientRequest" }, + "CodexAvatarAdminAwardGrantParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "accountUserId": { + "type": "string" + }, + "avatarId": { + "type": "string" + }, + "awardId": { + "type": "string" + }, + "awardedAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "awardedBy": { + "type": [ + "string", + "null" + ] + }, + "metadataJson": { + "type": [ + "string", + "null" + ] + }, + "sourceRef": { + "type": [ + "string", + "null" + ] + }, + "sourceSummary": { + "type": [ + "string", + "null" + ] + }, + "sourceType": { + "type": "string" + } + }, + "required": [ + "accountUserId", + "avatarId", + "awardId", + "sourceType" + ], + "title": "CodexAvatarAdminAwardGrantParams", + "type": "object" + }, + "CodexAvatarAdminCapabilitiesReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "CodexAvatarAdminCapabilitiesReadParams", + "type": "object" + }, + "CodexAvatarAdminCapabilitiesReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "canGrantAwards": { + "type": "boolean" + } + }, + "required": [ + "canGrantAwards" + ], + "title": "CodexAvatarAdminCapabilitiesReadResponse", + "type": "object" + }, "CodexAvatarDefinition": { "properties": { "assetRef": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminAwardGrantParams.json b/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminAwardGrantParams.json new file mode 100644 index 0000000000..2e3aa0cdfd --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminAwardGrantParams.json @@ -0,0 +1,56 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "accountUserId": { + "type": "string" + }, + "avatarId": { + "type": "string" + }, + "awardId": { + "type": "string" + }, + "awardedAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "awardedBy": { + "type": [ + "string", + "null" + ] + }, + "metadataJson": { + "type": [ + "string", + "null" + ] + }, + "sourceRef": { + "type": [ + "string", + "null" + ] + }, + "sourceSummary": { + "type": [ + "string", + "null" + ] + }, + "sourceType": { + "type": "string" + } + }, + "required": [ + "accountUserId", + "avatarId", + "awardId", + "sourceType" + ], + "title": "CodexAvatarAdminAwardGrantParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminCapabilitiesReadParams.json b/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminCapabilitiesReadParams.json new file mode 100644 index 0000000000..432ebe1c8a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminCapabilitiesReadParams.json @@ -0,0 +1,5 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "CodexAvatarAdminCapabilitiesReadParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminCapabilitiesReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminCapabilitiesReadResponse.json new file mode 100644 index 0000000000..5a0ea18bd1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/CodexAvatarAdminCapabilitiesReadResponse.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "canGrantAwards": { + "type": "boolean" + } + }, + "required": [ + "canGrantAwards" + ], + "title": "CodexAvatarAdminCapabilitiesReadResponse", + "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 6720878fea..b0c859aa80 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -9,6 +9,8 @@ import type { InitializeParams } from "./InitializeParams"; import type { RequestId } from "./RequestId"; import type { AppsListParams } from "./v2/AppsListParams"; import type { CancelLoginAccountParams } from "./v2/CancelLoginAccountParams"; +import type { CodexAvatarAdminAwardGrantParams } from "./v2/CodexAvatarAdminAwardGrantParams"; +import type { CodexAvatarAdminCapabilitiesReadParams } from "./v2/CodexAvatarAdminCapabilitiesReadParams"; import type { CodexAvatarEquipParams } from "./v2/CodexAvatarEquipParams"; import type { CodexAvatarInventoryReadParams } from "./v2/CodexAvatarInventoryReadParams"; import type { CommandExecParams } from "./v2/CommandExecParams"; @@ -66,4 +68,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/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/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": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "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": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "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": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "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": "avatar/inventory/read", id: RequestId, params: CodexAvatarInventoryReadParams, } | { "method": "avatar/equip", id: RequestId, params: CodexAvatarEquipParams, } | { "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/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/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": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "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": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "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": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "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": "avatar/inventory/read", id: RequestId, params: CodexAvatarInventoryReadParams, } | { "method": "avatar/equip", id: RequestId, params: CodexAvatarEquipParams, } | { "method": "avatar/admin/award", id: RequestId, params: CodexAvatarAdminAwardGrantParams, } | { "method": "avatar/admin/capabilities/read", id: RequestId, params: CodexAvatarAdminCapabilitiesReadParams, } | { "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/CodexAvatarAdminAwardGrantParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminAwardGrantParams.ts new file mode 100644 index 0000000000..f6f8ef3bc9 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminAwardGrantParams.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 CodexAvatarAdminAwardGrantParams = { accountUserId: string, awardId: string, avatarId: string, sourceType: string, sourceRef?: string | null, awardedAt?: bigint | null, awardedBy?: string | null, metadataJson?: string | null, sourceSummary?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminCapabilitiesReadParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminCapabilitiesReadParams.ts new file mode 100644 index 0000000000..779bcb635c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminCapabilitiesReadParams.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 CodexAvatarAdminCapabilitiesReadParams = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminCapabilitiesReadResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminCapabilitiesReadResponse.ts new file mode 100644 index 0000000000..34044da918 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CodexAvatarAdminCapabilitiesReadResponse.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 CodexAvatarAdminCapabilitiesReadResponse = { canGrantAwards: boolean, }; 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 c3de3e7b9c..518de28430 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -31,6 +31,9 @@ export type { CancelLoginAccountStatus } from "./CancelLoginAccountStatus"; export type { ChatgptAuthTokensRefreshParams } from "./ChatgptAuthTokensRefreshParams"; export type { ChatgptAuthTokensRefreshReason } from "./ChatgptAuthTokensRefreshReason"; export type { ChatgptAuthTokensRefreshResponse } from "./ChatgptAuthTokensRefreshResponse"; +export type { CodexAvatarAdminAwardGrantParams } from "./CodexAvatarAdminAwardGrantParams"; +export type { CodexAvatarAdminCapabilitiesReadParams } from "./CodexAvatarAdminCapabilitiesReadParams"; +export type { CodexAvatarAdminCapabilitiesReadResponse } from "./CodexAvatarAdminCapabilitiesReadResponse"; export type { CodexAvatarAward } from "./CodexAvatarAward"; export type { CodexAvatarDefinition } from "./CodexAvatarDefinition"; export type { CodexAvatarEquipParams } from "./CodexAvatarEquipParams"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 390fa525ab..2f1a207108 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -495,6 +495,16 @@ client_request_definitions! { response: v2::CodexAvatarInventoryReadResponse, }, + AvatarAdminAward => "avatar/admin/award" { + params: v2::CodexAvatarAdminAwardGrantParams, + response: v2::CodexAvatarInventoryReadResponse, + }, + + AvatarAdminCapabilitiesRead => "avatar/admin/capabilities/read" { + params: v2::CodexAvatarAdminCapabilitiesReadParams, + response: v2::CodexAvatarAdminCapabilitiesReadResponse, + }, + FeedbackUpload => "feedback/upload" { params: v2::FeedbackUploadParams, response: v2::FeedbackUploadResponse, @@ -1565,6 +1575,60 @@ mod tests { Ok(()) } + #[test] + fn serialize_avatar_admin_award() -> Result<()> { + let request = ClientRequest::AvatarAdminAward { + request_id: RequestId::Integer(9), + params: v2::CodexAvatarAdminAwardGrantParams { + account_user_id: "target-user-123".to_string(), + award_id: "manual-grant-1".to_string(), + avatar_id: "prism".to_string(), + source_type: "manual-admin-grant".to_string(), + source_ref: Some("support-ticket-1".to_string()), + awarded_at: Some(123), + awarded_by: Some("admin-user".to_string()), + metadata_json: Some("{\"reason\":\"support\"}".to_string()), + source_summary: Some("Manual support grant".to_string()), + }, + }; + assert_eq!( + json!({ + "method": "avatar/admin/award", + "id": 9, + "params": { + "accountUserId": "target-user-123", + "awardId": "manual-grant-1", + "avatarId": "prism", + "sourceType": "manual-admin-grant", + "sourceRef": "support-ticket-1", + "awardedAt": 123, + "awardedBy": "admin-user", + "metadataJson": "{\"reason\":\"support\"}", + "sourceSummary": "Manual support grant" + } + }), + serde_json::to_value(&request)?, + ); + Ok(()) + } + + #[test] + fn serialize_avatar_admin_capabilities_read() -> Result<()> { + let request = ClientRequest::AvatarAdminCapabilitiesRead { + request_id: RequestId::Integer(10), + params: v2::CodexAvatarAdminCapabilitiesReadParams::default(), + }; + assert_eq!( + json!({ + "method": "avatar/admin/capabilities/read", + "id": 10, + "params": {} + }), + serde_json::to_value(&request)?, + ); + Ok(()) + } + #[test] fn account_serializes_fields_in_camel_case() -> Result<()> { let api_key = v2::Account::ApiKey {}; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index dce23c0dcf..de57fc7111 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1810,6 +1810,38 @@ pub struct CodexAvatarEquipParams { pub avatar_id: String, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct CodexAvatarAdminAwardGrantParams { + pub account_user_id: String, + pub award_id: String, + pub avatar_id: String, + pub source_type: String, + #[ts(optional = nullable)] + pub source_ref: Option, + #[ts(optional = nullable)] + pub awarded_at: Option, + #[ts(optional = nullable)] + pub awarded_by: Option, + #[ts(optional = nullable)] + pub metadata_json: Option, + #[ts(optional = nullable)] + pub source_summary: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct CodexAvatarAdminCapabilitiesReadParams {} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct CodexAvatarAdminCapabilitiesReadResponse { + pub can_grant_awards: bool, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/codex-rs/app-server/src/avatar_rpc.rs b/codex-rs/app-server/src/avatar_rpc.rs index 969ae60ddc..26777e4678 100644 --- a/codex-rs/app-server/src/avatar_rpc.rs +++ b/codex-rs/app-server/src/avatar_rpc.rs @@ -1,5 +1,7 @@ use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; +use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams; +use codex_app_server_protocol::CodexAvatarAdminCapabilitiesReadResponse; use codex_app_server_protocol::CodexAvatarDefinition; use codex_app_server_protocol::CodexAvatarEquipParams; use codex_app_server_protocol::CodexAvatarInventoryReadResponse; @@ -8,6 +10,8 @@ use codex_app_server_protocol::CodexAvatarRarity; use codex_app_server_protocol::CodexAvatarStatus; use codex_app_server_protocol::JSONRPCErrorError; use codex_backend_client::Client as BackendClient; +use codex_backend_client::CodexAvatarAdminAwardGrantRequest as BackendAvatarAdminAwardGrantRequest; +use codex_backend_client::CodexAvatarAdminCapabilitiesResponse as BackendAvatarAdminCapabilitiesResponse; use codex_backend_client::CodexAvatarDefinition as BackendAvatarDefinition; use codex_backend_client::CodexAvatarInventoryResponse as BackendAvatarInventoryResponse; use codex_backend_client::CodexAvatarOwnership as BackendAvatarOwnership; @@ -42,6 +46,41 @@ pub(crate) async fn equip_avatar( Ok(map_avatar_inventory_response(response)) } +pub(crate) async fn grant_admin_avatar_award( + auth_manager: &AuthManager, + chatgpt_base_url: &str, + params: CodexAvatarAdminAwardGrantParams, +) -> Result { + let client = avatar_backend_client(auth_manager, chatgpt_base_url).await?; + let response = client + .grant_admin_avatar_award(BackendAvatarAdminAwardGrantRequest { + account_user_id: params.account_user_id, + award_id: params.award_id, + avatar_id: params.avatar_id, + source_type: params.source_type, + source_ref: params.source_ref, + awarded_at: params.awarded_at, + awarded_by: params.awarded_by, + metadata_json: params.metadata_json, + source_summary: params.source_summary, + }) + .await + .map_err(|err| backend_avatar_error("grant avatar award", err))?; + Ok(map_avatar_inventory_response(response)) +} + +pub(crate) async fn read_avatar_admin_capabilities( + auth_manager: &AuthManager, + chatgpt_base_url: &str, +) -> Result { + let client = avatar_backend_client(auth_manager, chatgpt_base_url).await?; + let response = client + .get_avatar_admin_capabilities() + .await + .map_err(|err| backend_avatar_error("read avatar admin capabilities", err))?; + Ok(map_avatar_admin_capabilities_response(response)) +} + async fn avatar_backend_client( auth_manager: &AuthManager, chatgpt_base_url: &str, @@ -71,7 +110,9 @@ async fn avatar_backend_client( fn backend_avatar_error(action: &str, err: RequestError) -> JSONRPCErrorError { match &err { - RequestError::UnexpectedStatus { status, body, .. } if status.as_u16() == 400 => { + RequestError::UnexpectedStatus { status, body, .. } + if status.as_u16() == 400 || status.as_u16() == 403 => + { JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, message: avatar_error_detail(body) @@ -118,6 +159,14 @@ fn map_avatar_inventory_response( } } +fn map_avatar_admin_capabilities_response( + response: BackendAvatarAdminCapabilitiesResponse, +) -> CodexAvatarAdminCapabilitiesReadResponse { + CodexAvatarAdminCapabilitiesReadResponse { + can_grant_awards: response.can_grant_awards, + } +} + fn map_avatar_definition(definition: BackendAvatarDefinition) -> CodexAvatarDefinition { CodexAvatarDefinition { avatar_id: definition.avatar_id, diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index a71195856e..b0b1c55053 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -34,6 +34,7 @@ use codex_app_server_protocol::CancelLoginAccountResponse; use codex_app_server_protocol::CancelLoginAccountStatus; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::ClientResponse; +use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams; use codex_app_server_protocol::CodexAvatarEquipParams; use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo; use codex_app_server_protocol::CollaborationModeListParams; @@ -917,6 +918,17 @@ impl CodexMessageProcessor { self.avatar_equip(to_connection_request_id(request_id), params) .await; } + ClientRequest::AvatarAdminAward { request_id, params } => { + self.avatar_admin_award(to_connection_request_id(request_id), params) + .await; + } + ClientRequest::AvatarAdminCapabilitiesRead { + request_id, + params: _, + } => { + self.avatar_admin_capabilities_read(to_connection_request_id(request_id)) + .await; + } ClientRequest::GitDiffToRemote { request_id, params } => { self.git_diff_to_origin(to_connection_request_id(request_id), params.cwd) .await; @@ -1725,6 +1737,43 @@ impl CodexMessageProcessor { } } + async fn avatar_admin_award( + &self, + request_id: ConnectionRequestId, + params: CodexAvatarAdminAwardGrantParams, + ) { + match avatar_rpc::grant_admin_avatar_award( + &self.auth_manager, + &self.config.chatgpt_base_url, + params, + ) + .await + { + Ok(response) => { + self.outgoing.send_response(request_id, response).await; + } + Err(error) => { + self.outgoing.send_error(request_id, error).await; + } + } + } + + async fn avatar_admin_capabilities_read(&self, request_id: ConnectionRequestId) { + match avatar_rpc::read_avatar_admin_capabilities( + &self.auth_manager, + &self.config.chatgpt_base_url, + ) + .await + { + Ok(response) => { + self.outgoing.send_response(request_id, response).await; + } + Err(error) => { + self.outgoing.send_error(request_id, error).await; + } + } + } + async fn fetch_account_rate_limits( &self, ) -> Result< diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index a112a97e50..f88bc461d6 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -15,6 +15,7 @@ use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::CancelLoginAccountParams; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientNotification; +use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams; use codex_app_server_protocol::CodexAvatarEquipParams; use codex_app_server_protocol::CollaborationModeListParams; use codex_app_server_protocol::CommandExecParams; @@ -312,6 +313,22 @@ impl McpProcess { self.send_request("avatar/equip", params).await } + /// Send an `avatar/admin/award` JSON-RPC request. + pub async fn send_avatar_admin_award_request( + &mut self, + params: CodexAvatarAdminAwardGrantParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("avatar/admin/award", params).await + } + + /// Send an `avatar/admin/capabilities/read` JSON-RPC request. + pub async fn send_avatar_admin_capabilities_read_request(&mut self) -> anyhow::Result { + let params = Some(serde_json::json!({})); + self.send_request("avatar/admin/capabilities/read", params) + .await + } + /// Send an `account/login/start` JSON-RPC request with ChatGPT auth tokens. pub async fn send_chatgpt_auth_tokens_login_request( &mut self, diff --git a/codex-rs/app-server/tests/suite/v2/avatar.rs b/codex-rs/app-server/tests/suite/v2/avatar.rs index 4a2352760d..472139b0c6 100644 --- a/codex-rs/app-server/tests/suite/v2/avatar.rs +++ b/codex-rs/app-server/tests/suite/v2/avatar.rs @@ -3,6 +3,8 @@ use app_test_support::ChatGptAuthFixture; use app_test_support::McpProcess; use app_test_support::to_response; use app_test_support::write_chatgpt_auth; +use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams; +use codex_app_server_protocol::CodexAvatarAdminCapabilitiesReadResponse; use codex_app_server_protocol::CodexAvatarDefinition; use codex_app_server_protocol::CodexAvatarEquipParams; use codex_app_server_protocol::CodexAvatarInventoryReadResponse; @@ -23,6 +25,7 @@ use tokio::time::timeout; use wiremock::Mock; use wiremock::MockServer; use wiremock::ResponseTemplate; +use wiremock::matchers::body_json; use wiremock::matchers::header; use wiremock::matchers::method; use wiremock::matchers::path; @@ -206,6 +209,163 @@ async fn avatar_equip_returns_snapshot_with_clippy_fallback() -> Result<()> { Ok(()) } +#[tokio::test] +async fn avatar_admin_award_forwards_request_and_returns_target_user_snapshot() -> Result<()> { + let codex_home = TempDir::new()?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .plan_type("pro"), + AuthCredentialsStoreMode::File, + )?; + + let server = MockServer::start().await; + write_chatgpt_base_url(codex_home.path(), &server.uri())?; + Mock::given(method("POST")) + .and(path("/api/codex/avatars/admin/awards")) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .and(body_json(json!({ + "accountUserId": "target-user-456", + "awardId": "manual-grant-1", + "avatarId": "prism", + "sourceType": "manual-admin-grant", + "sourceRef": "support-ticket-1", + "awardedAt": 123, + "awardedBy": "admin-user", + "metadataJson": "{\"reason\":\"support\"}", + "sourceSummary": "Manual support grant" + }))) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(snapshot_json_for_user("prism", "target-user-456")), + ) + .mount(&server) + .await; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_avatar_admin_award_request(CodexAvatarAdminAwardGrantParams { + account_user_id: "target-user-456".to_string(), + award_id: "manual-grant-1".to_string(), + avatar_id: "prism".to_string(), + source_type: "manual-admin-grant".to_string(), + source_ref: Some("support-ticket-1".to_string()), + awarded_at: Some(123), + awarded_by: Some("admin-user".to_string()), + metadata_json: Some("{\"reason\":\"support\"}".to_string()), + source_summary: Some("Manual support grant".to_string()), + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let received: CodexAvatarInventoryReadResponse = to_response(response)?; + + assert_eq!( + received, + expected_snapshot_for_user("prism", "target-user-456") + ); + Ok(()) +} + +#[tokio::test] +async fn avatar_admin_award_forwards_backend_permission_error() -> Result<()> { + let codex_home = TempDir::new()?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .plan_type("pro"), + AuthCredentialsStoreMode::File, + )?; + + let server = MockServer::start().await; + write_chatgpt_base_url(codex_home.path(), &server.uri())?; + Mock::given(method("POST")) + .and(path("/api/codex/avatars/admin/awards")) + .respond_with(ResponseTemplate::new(403).set_body_json(json!({ + "detail": "Not a Codex admin", + }))) + .mount(&server) + .await; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_avatar_admin_award_request(CodexAvatarAdminAwardGrantParams { + account_user_id: "target-user-456".to_string(), + award_id: "manual-grant-1".to_string(), + avatar_id: "prism".to_string(), + source_type: "manual-admin-grant".to_string(), + source_ref: None, + awarded_at: None, + awarded_by: None, + metadata_json: None, + source_summary: None, + }) + .await?; + let error: JSONRPCError = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(error.id, RequestId::Integer(request_id)); + assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); + assert_eq!(error.error.message, "Not a Codex admin"); + Ok(()) +} + +#[tokio::test] +async fn avatar_admin_capabilities_read_returns_backend_capability_flags() -> Result<()> { + let codex_home = TempDir::new()?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .plan_type("pro"), + AuthCredentialsStoreMode::File, + )?; + + let server = MockServer::start().await; + write_chatgpt_base_url(codex_home.path(), &server.uri())?; + Mock::given(method("GET")) + .and(path("/api/codex/avatars/admin/capabilities")) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "canGrantAwards": true, + }))) + .mount(&server) + .await; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp.send_avatar_admin_capabilities_read_request().await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let received: CodexAvatarAdminCapabilitiesReadResponse = to_response(response)?; + + assert_eq!( + received, + CodexAvatarAdminCapabilitiesReadResponse { + can_grant_awards: true, + } + ); + Ok(()) +} + fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result<()> { std::fs::write( codex_home.join("config.toml"), @@ -214,8 +374,12 @@ fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result< } fn snapshot_json(equipped_avatar_id: &str) -> Value { + snapshot_json_for_user(equipped_avatar_id, "account-123") +} + +fn snapshot_json_for_user(equipped_avatar_id: &str, account_user_id: &str) -> Value { json!({ - "accountUserId": "account-123", + "accountUserId": account_user_id, "avatarDefinitions": [ { "avatarId": "clippy", @@ -244,14 +408,14 @@ fn snapshot_json(equipped_avatar_id: &str) -> Value { ], "ownedAvatars": [ { - "accountUserId": "account-123", + "accountUserId": account_user_id, "avatarId": "clippy", "firstUnlockedAt": 100, "lastAwardedAt": 100, "sourceSummary": "Default avatar", }, { - "accountUserId": "account-123", + "accountUserId": account_user_id, "avatarId": "prism", "firstUnlockedAt": 200, "lastAwardedAt": 300, @@ -267,8 +431,15 @@ fn snapshot_json(equipped_avatar_id: &str) -> Value { } fn expected_snapshot(equipped_avatar_id: &str) -> CodexAvatarInventoryReadResponse { + expected_snapshot_for_user(equipped_avatar_id, "account-123") +} + +fn expected_snapshot_for_user( + equipped_avatar_id: &str, + account_user_id: &str, +) -> CodexAvatarInventoryReadResponse { CodexAvatarInventoryReadResponse { - account_user_id: "account-123".to_string(), + account_user_id: account_user_id.to_string(), avatar_definitions: vec![ CodexAvatarDefinition { avatar_id: "clippy".to_string(), @@ -297,14 +468,14 @@ fn expected_snapshot(equipped_avatar_id: &str) -> CodexAvatarInventoryReadRespon ], owned_avatars: vec![ CodexAvatarOwnership { - account_user_id: "account-123".to_string(), + account_user_id: account_user_id.to_string(), avatar_id: "clippy".to_string(), first_unlocked_at: 100, last_awarded_at: 100, source_summary: Some("Default avatar".to_string()), }, CodexAvatarOwnership { - account_user_id: "account-123".to_string(), + account_user_id: account_user_id.to_string(), avatar_id: "prism".to_string(), first_unlocked_at: 200, last_awarded_at: 300, diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index 6acfa97b8f..2ffda03ab1 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -1,4 +1,6 @@ use crate::types::CodeTaskDetailsResponse; +use crate::types::CodexAvatarAdminAwardGrantRequest; +use crate::types::CodexAvatarAdminCapabilitiesResponse; use crate::types::CodexAvatarEquipRequest; use crate::types::CodexAvatarInventoryResponse; use crate::types::ConfigFileResponse; @@ -300,6 +302,42 @@ impl Client { .map_err(RequestError::from) } + pub async fn grant_admin_avatar_award( + &self, + request_body: CodexAvatarAdminAwardGrantRequest, + ) -> std::result::Result { + let url = match self.path_style { + PathStyle::CodexApi => format!("{}/api/codex/avatars/admin/awards", self.base_url), + PathStyle::ChatGptApi => format!("{}/wham/avatars/admin/awards", self.base_url), + }; + let req = self + .http + .post(&url) + .headers(self.headers()) + .header(CONTENT_TYPE, HeaderValue::from_static("application/json")) + .json(&request_body); + let (body, ct) = self.exec_request_detailed(req, "POST", &url).await?; + self.decode_json::(&url, &ct, &body) + .map_err(RequestError::from) + } + + pub async fn get_avatar_admin_capabilities( + &self, + ) -> std::result::Result { + let url = match self.path_style { + PathStyle::CodexApi => { + format!("{}/api/codex/avatars/admin/capabilities", self.base_url) + } + PathStyle::ChatGptApi => { + format!("{}/wham/avatars/admin/capabilities", self.base_url) + } + }; + let req = self.http.get(&url).headers(self.headers()); + let (body, ct) = self.exec_request_detailed(req, "GET", &url).await?; + self.decode_json::(&url, &ct, &body) + .map_err(RequestError::from) + } + pub async fn list_tasks( &self, limit: Option, diff --git a/codex-rs/backend-client/src/lib.rs b/codex-rs/backend-client/src/lib.rs index f4e11408da..aa8f3bf407 100644 --- a/codex-rs/backend-client/src/lib.rs +++ b/codex-rs/backend-client/src/lib.rs @@ -5,6 +5,8 @@ pub use client::Client; pub use client::RequestError; pub use types::CodeTaskDetailsResponse; pub use types::CodeTaskDetailsResponseExt; +pub use types::CodexAvatarAdminAwardGrantRequest; +pub use types::CodexAvatarAdminCapabilitiesResponse; pub use types::CodexAvatarDefinition; pub use types::CodexAvatarEquipRequest; pub use types::CodexAvatarInventoryResponse; diff --git a/codex-rs/backend-client/src/types.rs b/codex-rs/backend-client/src/types.rs index ddcfdc5aa1..8a1c2d100a 100644 --- a/codex-rs/backend-client/src/types.rs +++ b/codex-rs/backend-client/src/types.rs @@ -74,6 +74,20 @@ pub struct CodexAvatarEquipRequest { pub avatar_id: String, } +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct CodexAvatarAdminAwardGrantRequest { + pub account_user_id: String, + pub award_id: String, + pub avatar_id: String, + pub source_type: String, + pub source_ref: Option, + pub awarded_at: Option, + pub awarded_by: Option, + pub metadata_json: Option, + pub source_summary: Option, +} + #[derive(Clone, Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct CodexAvatarInventoryResponse { @@ -87,6 +101,12 @@ pub struct CodexAvatarInventoryResponse { pub catalog_version: Option, } +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct CodexAvatarAdminCapabilitiesResponse { + pub can_grant_awards: bool, +} + /// Hand-rolled models for the Cloud Tasks task-details response. /// The generated OpenAPI models are pretty bad. This is a half-step /// towards hand-rolling them. diff --git a/codex-rs/exec/src/workspace_out_of_credits.rs b/codex-rs/exec/src/workspace_out_of_credits.rs new file mode 100644 index 0000000000..270349f07b --- /dev/null +++ b/codex-rs/exec/src/workspace_out_of_credits.rs @@ -0,0 +1,376 @@ +use codex_app_server_protocol::CodexErrorInfo; +use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::TurnError; +use codex_backend_client::Client as BackendClient; +use codex_backend_client::WorkspaceOutOfCreditsNotificationStatus; +use codex_core::AuthManager; +use codex_core::CodexAuth; +use codex_core::config::Config; +use codex_protocol::account::PlanType; +use codex_protocol::protocol::RateLimitSnapshot; +use std::io; +use std::io::IsTerminal; + +const REQUEST_PROMPT: &str = + "Workspace out of credits. Request more from your workspace owner? [y/N]"; +const REQUEST_SENT_MESSAGE: &str = "Request sent!"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PromptDecisionInput { + candidate_usage_limit_failure: bool, + human_output: bool, + stdin_is_tty: bool, + stderr_is_tty: bool, + auth_supports_request: bool, +} + +pub(crate) fn notification_is_usage_limit_failure( + notification: &ServerNotification, + thread_id: &str, + turn_id: &str, +) -> bool { + match notification { + ServerNotification::Error(payload) => { + payload.thread_id == thread_id + && payload.turn_id == turn_id + && !payload.will_retry + && turn_error_is_usage_limit(&payload.error) + } + ServerNotification::TurnCompleted(payload) => { + payload.thread_id == thread_id + && payload.turn.id == turn_id + && payload.turn.status == codex_app_server_protocol::TurnStatus::Failed + && payload + .turn + .error + .as_ref() + .is_some_and(turn_error_is_usage_limit) + } + _ => false, + } +} + +pub(crate) async fn maybe_prompt_for_workspace_out_of_credits( + config: &Config, + candidate_usage_limit_failure: bool, + human_output: bool, +) -> anyhow::Result<()> { + let stdin_is_tty = io::stdin().is_terminal(); + let stderr_is_tty = io::stderr().is_terminal(); + let initial_decision = PromptDecisionInput { + candidate_usage_limit_failure, + human_output, + stdin_is_tty, + stderr_is_tty, + auth_supports_request: false, + }; + if !terminal_prompt_prerequisites_met(initial_decision) { + return Ok(()); + } + + let auth_manager = AuthManager::shared( + config.codex_home.clone(), + /*enable_codex_api_key_env*/ true, + config.cli_auth_credentials_store_mode, + ); + let auth = auth_manager.auth().await; + let auth_supports_request = auth_supports_workspace_request(auth.as_ref()); + let decision = PromptDecisionInput { + auth_supports_request, + ..initial_decision + }; + if !decision.auth_supports_request { + return Ok(()); + } + + let Some(auth) = auth else { + return Ok(()); + }; + let client = BackendClient::from_auth(config.chatgpt_base_url.clone(), &auth)?; + let rate_limits = client.get_rate_limits().await?; + if !should_offer_workspace_out_of_credits_prompt(decision, Some(&rate_limits)) { + return Ok(()); + } + + if !prompt_for_workspace_request()? { + return Ok(()); + } + + let response = client.post_workspace_out_of_credits_notification().await?; + match response.status { + WorkspaceOutOfCreditsNotificationStatus::Sent + | WorkspaceOutOfCreditsNotificationStatus::CooldownActive => { + eprintln!("{REQUEST_SENT_MESSAGE}"); + } + } + Ok(()) +} + +fn turn_error_is_usage_limit(error: &TurnError) -> bool { + matches!( + error.codex_error_info, + Some(CodexErrorInfo::UsageLimitExceeded) + ) +} + +fn terminal_prompt_prerequisites_met(input: PromptDecisionInput) -> bool { + input.candidate_usage_limit_failure + && input.human_output + && input.stdin_is_tty + && input.stderr_is_tty +} + +fn auth_supports_workspace_request(auth: Option<&CodexAuth>) -> bool { + auth.is_some_and(|auth| auth.is_chatgpt_auth() && auth.get_account_id().is_some()) +} + +fn should_offer_workspace_out_of_credits_prompt( + input: PromptDecisionInput, + snapshot: Option<&RateLimitSnapshot>, +) -> bool { + terminal_prompt_prerequisites_met(input) + && input.auth_supports_request + && snapshot.is_some_and(rate_limits_confirm_workspace_out_of_credits) +} + +fn rate_limits_confirm_workspace_out_of_credits(snapshot: &RateLimitSnapshot) -> bool { + if snapshot.plan_type != Some(PlanType::SelfServeBusinessUsageBased) { + return false; + } + + let Some(credits) = snapshot.credits.as_ref() else { + return false; + }; + if credits.unlimited { + return false; + } + + credits + .balance + .as_deref() + .and_then(parse_credit_balance) + .is_some_and(|balance| balance <= 0.0) +} + +fn parse_credit_balance(balance: &str) -> Option { + balance.trim().parse::().ok() +} + +fn prompt_for_workspace_request() -> io::Result { + eprintln!("{REQUEST_PROMPT}"); + + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + Ok(parse_affirmative_response(&input)) +} + +fn parse_affirmative_response(input: &str) -> bool { + let answer = input.trim(); + answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes") +} + +#[cfg(test)] +mod tests { + use super::*; + use codex_app_server_protocol::ErrorNotification; + use codex_app_server_protocol::Turn; + use codex_app_server_protocol::TurnCompletedNotification; + use codex_app_server_protocol::TurnStatus; + use codex_protocol::protocol::CreditsSnapshot; + use pretty_assertions::assert_eq; + + fn zero_credit_snapshot() -> RateLimitSnapshot { + RateLimitSnapshot { + limit_id: Some("codex".to_string()), + limit_name: None, + primary: None, + secondary: None, + credits: Some(CreditsSnapshot { + has_credits: false, + unlimited: false, + balance: Some("0".to_string()), + }), + plan_type: Some(PlanType::SelfServeBusinessUsageBased), + } + } + + fn usage_limit_turn_error() -> TurnError { + TurnError { + message: "You've hit your usage limit.".to_string(), + codex_error_info: Some(CodexErrorInfo::UsageLimitExceeded), + additional_details: None, + } + } + + #[test] + fn error_notification_marks_usage_limit_failure() { + let notification = ServerNotification::Error(ErrorNotification { + error: usage_limit_turn_error(), + will_retry: false, + thread_id: "thread-1".to_string(), + turn_id: "turn-1".to_string(), + }); + + assert!(notification_is_usage_limit_failure( + ¬ification, + "thread-1", + "turn-1" + )); + } + + #[test] + fn unrelated_notification_does_not_mark_usage_limit_failure() { + let notification = ServerNotification::Error(ErrorNotification { + error: TurnError { + message: "network failed".to_string(), + codex_error_info: Some(CodexErrorInfo::ResponseStreamDisconnected { + http_status_code: Some(503), + }), + additional_details: None, + }, + will_retry: false, + thread_id: "thread-1".to_string(), + turn_id: "turn-1".to_string(), + }); + + assert!(!notification_is_usage_limit_failure( + ¬ification, + "thread-1", + "turn-1" + )); + } + + #[test] + fn failed_turn_marks_usage_limit_failure() { + let notification = ServerNotification::TurnCompleted(TurnCompletedNotification { + thread_id: "thread-1".to_string(), + turn: Turn { + id: "turn-1".to_string(), + items: Vec::new(), + status: TurnStatus::Failed, + error: Some(usage_limit_turn_error()), + }, + }); + + assert!(notification_is_usage_limit_failure( + ¬ification, + "thread-1", + "turn-1" + )); + } + + #[test] + fn prompt_decision_requires_ttys_and_human_output() { + let snapshot = zero_credit_snapshot(); + let input = PromptDecisionInput { + candidate_usage_limit_failure: true, + human_output: false, + stdin_is_tty: true, + stderr_is_tty: true, + auth_supports_request: true, + }; + + assert!(!should_offer_workspace_out_of_credits_prompt( + input, + Some(&snapshot) + )); + } + + #[test] + fn prompt_decision_requires_supported_auth() { + let snapshot = zero_credit_snapshot(); + let input = PromptDecisionInput { + candidate_usage_limit_failure: true, + human_output: true, + stdin_is_tty: true, + stderr_is_tty: true, + auth_supports_request: false, + }; + + assert!(!should_offer_workspace_out_of_credits_prompt( + input, + Some(&snapshot) + )); + } + + #[test] + fn workspace_out_of_credits_confirmation_requires_zero_balance() { + assert!(rate_limits_confirm_workspace_out_of_credits( + &zero_credit_snapshot() + )); + } + + #[test] + fn workspace_out_of_credits_confirmation_rejects_missing_balance() { + let mut snapshot = zero_credit_snapshot(); + snapshot.credits.as_mut().expect("credits").balance = None; + + assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot)); + } + + #[test] + fn workspace_out_of_credits_confirmation_rejects_positive_balance() { + let mut snapshot = zero_credit_snapshot(); + snapshot.credits.as_mut().expect("credits").balance = Some("12.5".to_string()); + + assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot)); + } + + #[test] + fn workspace_out_of_credits_confirmation_rejects_wrong_plan() { + let mut snapshot = zero_credit_snapshot(); + snapshot.plan_type = Some(PlanType::Team); + + assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot)); + } + + #[test] + fn workspace_out_of_credits_confirmation_rejects_unlimited_credits() { + let mut snapshot = zero_credit_snapshot(); + snapshot.credits = Some(CreditsSnapshot { + has_credits: true, + unlimited: true, + balance: Some("0".to_string()), + }); + + assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot)); + } + + #[test] + fn chatgpt_auth_with_account_id_is_supported() { + let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); + + assert!(auth_supports_workspace_request(Some(&auth))); + } + + #[test] + fn api_key_auth_is_not_supported() { + let auth = CodexAuth::from_api_key("test-key"); + + assert!(!auth_supports_workspace_request(Some(&auth))); + } + + #[test] + fn affirmative_response_accepts_y_and_yes() { + assert!(parse_affirmative_response("y")); + assert!(parse_affirmative_response("YES")); + assert!(!parse_affirmative_response("")); + assert!(!parse_affirmative_response("n")); + } + + #[test] + fn prompt_decision_accepts_usage_limit_zero_credit_case() { + let input = PromptDecisionInput { + candidate_usage_limit_failure: true, + human_output: true, + stdin_is_tty: true, + stderr_is_tty: true, + auth_supports_request: true, + }; + + assert_eq!( + should_offer_workspace_out_of_credits_prompt(input, Some(&zero_credit_snapshot())), + true + ); + } +}