Initial Clippy

This commit is contained in:
Richard Lee
2026-04-04 13:20:29 -07:00
parent dedd1c386a
commit e6d2da4716
33 changed files with 1713 additions and 1 deletions
+1
View File
@@ -1978,6 +1978,7 @@ dependencies = [
"codex-app-server-protocol",
"codex-apply-patch",
"codex-arg0",
"codex-backend-client",
"codex-cloud-requirements",
"codex-core",
"codex-feedback",
@@ -147,6 +147,20 @@
],
"type": "object"
},
"CodexAvatarEquipParams": {
"properties": {
"avatarId": {
"type": "string"
}
},
"required": [
"avatarId"
],
"type": "object"
},
"CodexAvatarInventoryReadParams": {
"type": "object"
},
"CollaborationMode": {
"description": "Collaboration mode for a Codex session.",
"properties": {
@@ -4538,6 +4552,54 @@
"title": "Account/rateLimits/readRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/inventory/read"
],
"title": "Avatar/inventory/readRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarInventoryReadParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/inventory/readRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/equip"
],
"title": "Avatar/equipRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarEquipParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/equipRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -0,0 +1,54 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"awardId": {
"type": "string"
},
"awardedAt": {
"format": "int64",
"type": "integer"
},
"awardedBy": {
"type": [
"string",
"null"
]
},
"metadataJson": {
"type": [
"string",
"null"
]
},
"sourceRef": {
"type": [
"string",
"null"
]
},
"sourceSummary": {
"type": [
"string",
"null"
]
},
"sourceType": {
"type": "string"
}
},
"required": [
"accountUserId",
"avatarId",
"awardId",
"awardedAt",
"sourceType"
],
"title": "CodexAvatarAward",
"type": "object"
}
@@ -1319,6 +1319,54 @@
"title": "Account/rateLimits/readRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/v2/RequestId"
},
"method": {
"enum": [
"avatar/inventory/read"
],
"title": "Avatar/inventory/readRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/CodexAvatarInventoryReadParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/inventory/readRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/v2/RequestId"
},
"method": {
"enum": [
"avatar/equip"
],
"title": "Avatar/equipRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/CodexAvatarEquipParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/equipRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -1637,6 +1685,60 @@
],
"title": "ClientRequest"
},
"CodexAvatarAward": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"awardId": {
"type": "string"
},
"awardedAt": {
"format": "int64",
"type": "integer"
},
"awardedBy": {
"type": [
"string",
"null"
]
},
"metadataJson": {
"type": [
"string",
"null"
]
},
"sourceRef": {
"type": [
"string",
"null"
]
},
"sourceSummary": {
"type": [
"string",
"null"
]
},
"sourceType": {
"type": "string"
}
},
"required": [
"accountUserId",
"avatarId",
"awardId",
"awardedAt",
"sourceType"
],
"title": "CodexAvatarAward",
"type": "object"
},
"CommandExecutionApprovalDecision": {
"oneOf": [
{
@@ -5553,6 +5655,175 @@
],
"type": "string"
},
"CodexAvatarDefinition": {
"properties": {
"assetRef": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"createdAt": {
"format": "int64",
"type": "integer"
},
"description": {
"type": "string"
},
"displayName": {
"type": "string"
},
"rarity": {
"$ref": "#/definitions/v2/CodexAvatarRarity"
},
"slug": {
"type": "string"
},
"sortOrder": {
"format": "int64",
"type": "integer"
},
"status": {
"$ref": "#/definitions/v2/CodexAvatarStatus"
},
"updatedAt": {
"format": "int64",
"type": "integer"
}
},
"required": [
"assetRef",
"avatarId",
"createdAt",
"description",
"displayName",
"rarity",
"slug",
"sortOrder",
"status",
"updatedAt"
],
"type": "object"
},
"CodexAvatarEquipParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"avatarId": {
"type": "string"
}
},
"required": [
"avatarId"
],
"title": "CodexAvatarEquipParams",
"type": "object"
},
"CodexAvatarInventoryReadParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "CodexAvatarInventoryReadParams",
"type": "object"
},
"CodexAvatarInventoryReadResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accountUserId": {
"type": "string"
},
"avatarDefinitions": {
"items": {
"$ref": "#/definitions/v2/CodexAvatarDefinition"
},
"type": "array"
},
"catalogVersion": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"equippedAt": {
"format": "int64",
"type": "integer"
},
"equippedAvatarId": {
"type": "string"
},
"ownedAvatars": {
"items": {
"$ref": "#/definitions/v2/CodexAvatarOwnership"
},
"type": "array"
},
"syncedAt": {
"format": "int64",
"type": "integer"
},
"updatedAt": {
"format": "int64",
"type": "integer"
}
},
"required": [
"accountUserId",
"avatarDefinitions",
"equippedAt",
"equippedAvatarId",
"ownedAvatars",
"syncedAt",
"updatedAt"
],
"title": "CodexAvatarInventoryReadResponse",
"type": "object"
},
"CodexAvatarOwnership": {
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"firstUnlockedAt": {
"format": "int64",
"type": "integer"
},
"lastAwardedAt": {
"format": "int64",
"type": "integer"
},
"sourceSummary": {
"type": [
"string",
"null"
]
}
},
"required": [
"accountUserId",
"avatarId",
"firstUnlockedAt",
"lastAwardedAt"
],
"type": "object"
},
"CodexAvatarRarity": {
"enum": [
"common",
"rare",
"epic",
"legendary"
],
"type": "string"
},
"CodexAvatarStatus": {
"enum": [
"active",
"hidden",
"retired"
],
"type": "string"
},
"CodexErrorInfo": {
"description": "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.",
"oneOf": [
@@ -1894,6 +1894,54 @@
"title": "Account/rateLimits/readRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/inventory/read"
],
"title": "Avatar/inventory/readRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarInventoryReadParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/inventory/readRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/equip"
],
"title": "Avatar/equipRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarEquipParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/equipRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -2212,6 +2260,175 @@
],
"title": "ClientRequest"
},
"CodexAvatarDefinition": {
"properties": {
"assetRef": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"createdAt": {
"format": "int64",
"type": "integer"
},
"description": {
"type": "string"
},
"displayName": {
"type": "string"
},
"rarity": {
"$ref": "#/definitions/CodexAvatarRarity"
},
"slug": {
"type": "string"
},
"sortOrder": {
"format": "int64",
"type": "integer"
},
"status": {
"$ref": "#/definitions/CodexAvatarStatus"
},
"updatedAt": {
"format": "int64",
"type": "integer"
}
},
"required": [
"assetRef",
"avatarId",
"createdAt",
"description",
"displayName",
"rarity",
"slug",
"sortOrder",
"status",
"updatedAt"
],
"type": "object"
},
"CodexAvatarEquipParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"avatarId": {
"type": "string"
}
},
"required": [
"avatarId"
],
"title": "CodexAvatarEquipParams",
"type": "object"
},
"CodexAvatarInventoryReadParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "CodexAvatarInventoryReadParams",
"type": "object"
},
"CodexAvatarInventoryReadResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accountUserId": {
"type": "string"
},
"avatarDefinitions": {
"items": {
"$ref": "#/definitions/CodexAvatarDefinition"
},
"type": "array"
},
"catalogVersion": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"equippedAt": {
"format": "int64",
"type": "integer"
},
"equippedAvatarId": {
"type": "string"
},
"ownedAvatars": {
"items": {
"$ref": "#/definitions/CodexAvatarOwnership"
},
"type": "array"
},
"syncedAt": {
"format": "int64",
"type": "integer"
},
"updatedAt": {
"format": "int64",
"type": "integer"
}
},
"required": [
"accountUserId",
"avatarDefinitions",
"equippedAt",
"equippedAvatarId",
"ownedAvatars",
"syncedAt",
"updatedAt"
],
"title": "CodexAvatarInventoryReadResponse",
"type": "object"
},
"CodexAvatarOwnership": {
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"firstUnlockedAt": {
"format": "int64",
"type": "integer"
},
"lastAwardedAt": {
"format": "int64",
"type": "integer"
},
"sourceSummary": {
"type": [
"string",
"null"
]
}
},
"required": [
"accountUserId",
"avatarId",
"firstUnlockedAt",
"lastAwardedAt"
],
"type": "object"
},
"CodexAvatarRarity": {
"enum": [
"common",
"rare",
"epic",
"legendary"
],
"type": "string"
},
"CodexAvatarStatus": {
"enum": [
"active",
"hidden",
"retired"
],
"type": "string"
},
"CodexErrorInfo": {
"description": "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.",
"oneOf": [
@@ -0,0 +1,13 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"avatarId": {
"type": "string"
}
},
"required": [
"avatarId"
],
"title": "CodexAvatarEquipParams",
"type": "object"
}
@@ -0,0 +1,5 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "CodexAvatarInventoryReadParams",
"type": "object"
}
@@ -0,0 +1,153 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"CodexAvatarDefinition": {
"properties": {
"assetRef": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"createdAt": {
"format": "int64",
"type": "integer"
},
"description": {
"type": "string"
},
"displayName": {
"type": "string"
},
"rarity": {
"$ref": "#/definitions/CodexAvatarRarity"
},
"slug": {
"type": "string"
},
"sortOrder": {
"format": "int64",
"type": "integer"
},
"status": {
"$ref": "#/definitions/CodexAvatarStatus"
},
"updatedAt": {
"format": "int64",
"type": "integer"
}
},
"required": [
"assetRef",
"avatarId",
"createdAt",
"description",
"displayName",
"rarity",
"slug",
"sortOrder",
"status",
"updatedAt"
],
"type": "object"
},
"CodexAvatarOwnership": {
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"firstUnlockedAt": {
"format": "int64",
"type": "integer"
},
"lastAwardedAt": {
"format": "int64",
"type": "integer"
},
"sourceSummary": {
"type": [
"string",
"null"
]
}
},
"required": [
"accountUserId",
"avatarId",
"firstUnlockedAt",
"lastAwardedAt"
],
"type": "object"
},
"CodexAvatarRarity": {
"enum": [
"common",
"rare",
"epic",
"legendary"
],
"type": "string"
},
"CodexAvatarStatus": {
"enum": [
"active",
"hidden",
"retired"
],
"type": "string"
}
},
"properties": {
"accountUserId": {
"type": "string"
},
"avatarDefinitions": {
"items": {
"$ref": "#/definitions/CodexAvatarDefinition"
},
"type": "array"
},
"catalogVersion": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"equippedAt": {
"format": "int64",
"type": "integer"
},
"equippedAvatarId": {
"type": "string"
},
"ownedAvatars": {
"items": {
"$ref": "#/definitions/CodexAvatarOwnership"
},
"type": "array"
},
"syncedAt": {
"format": "int64",
"type": "integer"
},
"updatedAt": {
"format": "int64",
"type": "integer"
}
},
"required": [
"accountUserId",
"avatarDefinitions",
"equippedAt",
"equippedAvatarId",
"ownedAvatars",
"syncedAt",
"updatedAt"
],
"title": "CodexAvatarInventoryReadResponse",
"type": "object"
}
File diff suppressed because one or more lines are too long
@@ -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 CodexAvatarAward = { awardId: string, accountUserId: string, avatarId: string, sourceType: string, sourceRef: string | null, awardedAt: bigint, awardedBy: string | null, metadataJson: string | null, sourceSummary: string | null, };
@@ -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 { CodexAvatarRarity } from "./CodexAvatarRarity";
import type { CodexAvatarStatus } from "./CodexAvatarStatus";
export type CodexAvatarDefinition = { avatarId: string, slug: string, displayName: string, description: string, rarity: CodexAvatarRarity, assetRef: string, status: CodexAvatarStatus, sortOrder: bigint, createdAt: bigint, updatedAt: bigint, };
@@ -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 CodexAvatarEquipParams = { avatarId: string, };
@@ -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 CodexAvatarInventoryReadParams = Record<string, never>;
@@ -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 { CodexAvatarDefinition } from "./CodexAvatarDefinition";
import type { CodexAvatarOwnership } from "./CodexAvatarOwnership";
export type CodexAvatarInventoryReadResponse = { accountUserId: string, avatarDefinitions: Array<CodexAvatarDefinition>, ownedAvatars: Array<CodexAvatarOwnership>, equippedAvatarId: string, equippedAt: bigint, updatedAt: bigint, syncedAt: bigint, catalogVersion: bigint | null, };
@@ -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 CodexAvatarOwnership = { accountUserId: string, avatarId: string, firstUnlockedAt: bigint, lastAwardedAt: bigint, sourceSummary: string | null, };
@@ -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 CodexAvatarRarity = "common" | "rare" | "epic" | "legendary";
@@ -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 CodexAvatarStatus = "active" | "hidden" | "retired";
@@ -31,6 +31,14 @@ export type { CancelLoginAccountStatus } from "./CancelLoginAccountStatus";
export type { ChatgptAuthTokensRefreshParams } from "./ChatgptAuthTokensRefreshParams";
export type { ChatgptAuthTokensRefreshReason } from "./ChatgptAuthTokensRefreshReason";
export type { ChatgptAuthTokensRefreshResponse } from "./ChatgptAuthTokensRefreshResponse";
export type { CodexAvatarAward } from "./CodexAvatarAward";
export type { CodexAvatarDefinition } from "./CodexAvatarDefinition";
export type { CodexAvatarEquipParams } from "./CodexAvatarEquipParams";
export type { CodexAvatarInventoryReadParams } from "./CodexAvatarInventoryReadParams";
export type { CodexAvatarInventoryReadResponse } from "./CodexAvatarInventoryReadResponse";
export type { CodexAvatarOwnership } from "./CodexAvatarOwnership";
export type { CodexAvatarRarity } from "./CodexAvatarRarity";
export type { CodexAvatarStatus } from "./CodexAvatarStatus";
export type { CodexErrorInfo } from "./CodexErrorInfo";
export type { CollabAgentState } from "./CollabAgentState";
export type { CollabAgentStatus } from "./CollabAgentStatus";
@@ -118,6 +118,7 @@ pub fn generate_ts_with_options(
ServerRequest::export_all_to(out_dir)?;
export_server_responses(out_dir)?;
ServerNotification::export_all_to(out_dir)?;
crate::protocol::v2::CodexAvatarAward::export_all_to(out_dir)?;
if !options.experimental_api {
filter_experimental_ts(out_dir)?;
@@ -206,6 +207,12 @@ pub fn generate_json_with_experimental(out_dir: &Path, experimental_api: bool) -
|d| write_json_schema_with_return::<crate::ServerRequest>(d, "ServerRequest"),
|d| write_json_schema_with_return::<crate::ClientNotification>(d, "ClientNotification"),
|d| write_json_schema_with_return::<crate::ServerNotification>(d, "ServerNotification"),
|d| {
write_json_schema_with_return::<crate::protocol::v2::CodexAvatarAward>(
d,
"CodexAvatarAward",
)
},
];
let mut schemas: Vec<GeneratedSchema> = Vec::new();
@@ -485,6 +485,16 @@ client_request_definitions! {
response: v2::GetAccountRateLimitsResponse,
},
AvatarInventoryRead => "avatar/inventory/read" {
params: v2::CodexAvatarInventoryReadParams,
response: v2::CodexAvatarInventoryReadResponse,
},
AvatarEquip => "avatar/equip" {
params: v2::CodexAvatarEquipParams,
response: v2::CodexAvatarInventoryReadResponse,
},
FeedbackUpload => "feedback/upload" {
params: v2::FeedbackUploadParams,
response: v2::FeedbackUploadResponse,
@@ -1517,6 +1527,44 @@ mod tests {
Ok(())
}
#[test]
fn serialize_avatar_inventory_read() -> Result<()> {
let request = ClientRequest::AvatarInventoryRead {
request_id: RequestId::Integer(7),
params: v2::CodexAvatarInventoryReadParams::default(),
};
assert_eq!(
json!({
"method": "avatar/inventory/read",
"id": 7,
"params": {}
}),
serde_json::to_value(&request)?,
);
Ok(())
}
#[test]
fn serialize_avatar_equip() -> Result<()> {
let request = ClientRequest::AvatarEquip {
request_id: RequestId::Integer(8),
params: v2::CodexAvatarEquipParams {
avatar_id: "clippy".to_string(),
},
};
assert_eq!(
json!({
"method": "avatar/equip",
"id": 8,
"params": {
"avatarId": "clippy"
}
}),
serde_json::to_value(&request)?,
);
Ok(())
}
#[test]
fn account_serializes_fields_in_camel_case() -> Result<()> {
let api_key = v2::Account::ApiKey {};
@@ -1737,6 +1737,93 @@ pub struct GetAccountResponse {
pub requires_openai_auth: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum CodexAvatarStatus {
Active,
Hidden,
Retired,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum CodexAvatarRarity {
Common,
Rare,
Epic,
Legendary,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CodexAvatarDefinition {
pub avatar_id: String,
pub slug: String,
pub display_name: String,
pub description: String,
pub rarity: CodexAvatarRarity,
pub asset_ref: String,
pub status: CodexAvatarStatus,
pub sort_order: i64,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CodexAvatarOwnership {
pub account_user_id: String,
pub avatar_id: String,
pub first_unlocked_at: i64,
pub last_awarded_at: i64,
pub source_summary: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CodexAvatarAward {
pub award_id: String,
pub account_user_id: String,
pub avatar_id: String,
pub source_type: String,
pub source_ref: Option<String>,
pub awarded_at: i64,
pub awarded_by: Option<String>,
pub metadata_json: Option<String>,
pub source_summary: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CodexAvatarInventoryReadParams {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
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 CodexAvatarInventoryReadResponse {
pub account_user_id: String,
pub avatar_definitions: Vec<CodexAvatarDefinition>,
pub owned_avatars: Vec<CodexAvatarOwnership>,
pub equipped_avatar_id: String,
pub equipped_at: i64,
pub updated_at: i64,
pub synced_at: i64,
pub catalog_version: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -7,6 +7,7 @@ use crate::export::filter_experimental_ts_tree;
use crate::export::generate_index_ts_tree;
use crate::protocol::common::visit_client_response_types;
use crate::protocol::common::visit_server_response_types;
use crate::protocol::v2::CodexAvatarAward;
use anyhow::Context;
use anyhow::Result;
use serde_json::Map;
@@ -65,6 +66,7 @@ pub fn generate_typescript_schema_fixture_subtree_for_tests() -> Result<BTreeMap
visit_server_response_types(visitor);
})?;
collect_typescript_fixture_file::<ServerNotification>(&mut files, &mut seen)?;
collect_typescript_fixture_file::<CodexAvatarAward>(&mut files, &mut seen)?;
filter_experimental_ts_tree(&mut files)?;
generate_index_ts_tree(&mut files);
+153
View File
@@ -0,0 +1,153 @@
use crate::error_code::INTERNAL_ERROR_CODE;
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
use codex_app_server_protocol::CodexAvatarDefinition;
use codex_app_server_protocol::CodexAvatarEquipParams;
use codex_app_server_protocol::CodexAvatarInventoryReadResponse;
use codex_app_server_protocol::CodexAvatarOwnership;
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::CodexAvatarDefinition as BackendAvatarDefinition;
use codex_backend_client::CodexAvatarInventoryResponse as BackendAvatarInventoryResponse;
use codex_backend_client::CodexAvatarOwnership as BackendAvatarOwnership;
use codex_backend_client::CodexAvatarRarity as BackendAvatarRarity;
use codex_backend_client::CodexAvatarStatus as BackendAvatarStatus;
use codex_backend_client::RequestError;
use codex_core::AuthManager;
use serde_json::Value;
pub(crate) async fn read_avatar_inventory(
auth_manager: &AuthManager,
chatgpt_base_url: &str,
) -> Result<CodexAvatarInventoryReadResponse, JSONRPCErrorError> {
let client = avatar_backend_client(auth_manager, chatgpt_base_url).await?;
let response = client
.get_avatar_inventory()
.await
.map_err(|err| backend_avatar_error("read avatar inventory", err))?;
Ok(map_avatar_inventory_response(response))
}
pub(crate) async fn equip_avatar(
auth_manager: &AuthManager,
chatgpt_base_url: &str,
params: CodexAvatarEquipParams,
) -> Result<CodexAvatarInventoryReadResponse, JSONRPCErrorError> {
let client = avatar_backend_client(auth_manager, chatgpt_base_url).await?;
let response = client
.equip_avatar(params.avatar_id)
.await
.map_err(|err| backend_avatar_error("equip avatar", err))?;
Ok(map_avatar_inventory_response(response))
}
async fn avatar_backend_client(
auth_manager: &AuthManager,
chatgpt_base_url: &str,
) -> Result<BackendClient, JSONRPCErrorError> {
let Some(auth) = auth_manager.auth().await else {
return Err(JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: "codex account authentication required to manage avatars".to_string(),
data: None,
});
};
if !auth.is_chatgpt_auth() {
return Err(JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: "chatgpt authentication required to manage avatars".to_string(),
data: None,
});
}
BackendClient::from_auth(chatgpt_base_url.to_string(), &auth).map_err(|err| JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
message: format!("failed to construct backend client: {err}"),
data: None,
})
}
fn backend_avatar_error(action: &str, err: RequestError) -> JSONRPCErrorError {
match &err {
RequestError::UnexpectedStatus { status, body, .. } if status.as_u16() == 400 => {
JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: avatar_error_detail(body)
.unwrap_or_else(|| format!("failed to {action}: {err}")),
data: None,
}
}
_ => JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
message: format!("failed to {action}: {err}"),
data: None,
},
}
}
fn avatar_error_detail(body: &str) -> Option<String> {
let value: Value = serde_json::from_str(body).ok()?;
value
.get("detail")
.and_then(Value::as_str)
.map(str::to_string)
}
fn map_avatar_inventory_response(
response: BackendAvatarInventoryResponse,
) -> CodexAvatarInventoryReadResponse {
CodexAvatarInventoryReadResponse {
account_user_id: response.account_user_id,
avatar_definitions: response
.avatar_definitions
.into_iter()
.map(map_avatar_definition)
.collect(),
owned_avatars: response
.owned_avatars
.into_iter()
.map(map_avatar_ownership)
.collect(),
equipped_avatar_id: response.equipped_avatar_id,
equipped_at: response.equipped_at,
updated_at: response.updated_at,
synced_at: response.synced_at,
catalog_version: response.catalog_version,
}
}
fn map_avatar_definition(definition: BackendAvatarDefinition) -> CodexAvatarDefinition {
CodexAvatarDefinition {
avatar_id: definition.avatar_id,
slug: definition.slug,
display_name: definition.display_name,
description: definition.description,
rarity: match definition.rarity {
BackendAvatarRarity::Common => CodexAvatarRarity::Common,
BackendAvatarRarity::Rare => CodexAvatarRarity::Rare,
BackendAvatarRarity::Epic => CodexAvatarRarity::Epic,
BackendAvatarRarity::Legendary => CodexAvatarRarity::Legendary,
},
asset_ref: definition.asset_ref,
status: match definition.status {
BackendAvatarStatus::Active => CodexAvatarStatus::Active,
BackendAvatarStatus::Hidden => CodexAvatarStatus::Hidden,
BackendAvatarStatus::Retired => CodexAvatarStatus::Retired,
},
sort_order: definition.sort_order,
created_at: definition.created_at,
updated_at: definition.updated_at,
}
}
fn map_avatar_ownership(ownership: BackendAvatarOwnership) -> CodexAvatarOwnership {
CodexAvatarOwnership {
account_user_id: ownership.account_user_id,
avatar_id: ownership.avatar_id,
first_unlocked_at: ownership.first_unlocked_at,
last_awarded_at: ownership.last_awarded_at,
source_summary: ownership.source_summary,
}
}
@@ -1,3 +1,4 @@
use crate::avatar_rpc;
use crate::bespoke_event_handling::apply_bespoke_event_handling;
use crate::command_exec::CommandExecManager;
use crate::command_exec::StartCommandExecParams;
@@ -33,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::CodexAvatarEquipParams;
use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo;
use codex_app_server_protocol::CollaborationModeListParams;
use codex_app_server_protocol::CollaborationModeListResponse;
@@ -904,6 +906,17 @@ impl CodexMessageProcessor {
self.get_account(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::AvatarInventoryRead {
request_id,
params: _,
} => {
self.avatar_inventory_read(to_connection_request_id(request_id))
.await;
}
ClientRequest::AvatarEquip { request_id, params } => {
self.avatar_equip(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::GitDiffToRemote { request_id, params } => {
self.git_diff_to_origin(to_connection_request_id(request_id), params.cwd)
.await;
@@ -1686,6 +1699,32 @@ impl CodexMessageProcessor {
}
}
async fn avatar_inventory_read(&self, request_id: ConnectionRequestId) {
match avatar_rpc::read_avatar_inventory(&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 avatar_equip(&self, request_id: ConnectionRequestId, params: CodexAvatarEquipParams) {
match avatar_rpc::equip_avatar(&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 fetch_account_rate_limits(
&self,
) -> Result<
+1
View File
@@ -61,6 +61,7 @@ use tracing_subscriber::registry::Registry;
use tracing_subscriber::util::SubscriberInitExt;
mod app_server_tracing;
mod avatar_rpc;
mod bespoke_event_handling;
mod codex_message_processor;
mod command_exec;
@@ -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::CodexAvatarEquipParams;
use codex_app_server_protocol::CollaborationModeListParams;
use codex_app_server_protocol::CommandExecParams;
use codex_app_server_protocol::CommandExecResizeParams;
@@ -296,6 +297,21 @@ impl McpProcess {
self.send_request("account/read", params).await
}
/// Send an `avatar/inventory/read` JSON-RPC request.
pub async fn send_avatar_inventory_read_request(&mut self) -> anyhow::Result<i64> {
let params = Some(serde_json::json!({}));
self.send_request("avatar/inventory/read", params).await
}
/// Send an `avatar/equip` JSON-RPC request.
pub async fn send_avatar_equip_request(
&mut self,
params: CodexAvatarEquipParams,
) -> anyhow::Result<i64> {
let params = Some(serde_json::to_value(params)?);
self.send_request("avatar/equip", 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,
@@ -0,0 +1,320 @@
use anyhow::Result;
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::CodexAvatarDefinition;
use codex_app_server_protocol::CodexAvatarEquipParams;
use codex_app_server_protocol::CodexAvatarInventoryReadResponse;
use codex_app_server_protocol::CodexAvatarOwnership;
use codex_app_server_protocol::CodexAvatarRarity;
use codex_app_server_protocol::CodexAvatarStatus;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use codex_core::auth::AuthCredentialsStoreMode;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
#[tokio::test]
async fn avatar_inventory_read_requires_auth() -> Result<()> {
let codex_home = TempDir::new()?;
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_inventory_read_request().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,
"codex account authentication required to manage avatars"
);
Ok(())
}
#[tokio::test]
async fn avatar_inventory_read_requires_chatgpt_auth() -> Result<()> {
let codex_home = TempDir::new()?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let login_request_id = mcp
.send_login_account_api_key_request("sk-test-key")
.await?;
let login_response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(login_request_id)),
)
.await??;
let login: LoginAccountResponse = to_response(login_response)?;
assert_eq!(login, LoginAccountResponse::ApiKey {});
let request_id = mcp.send_avatar_inventory_read_request().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,
"chatgpt authentication required to manage avatars"
);
Ok(())
}
#[tokio::test]
async fn avatar_inventory_read_returns_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("GET"))
.and(path("/api/codex/avatars/inventory"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(snapshot_json("prism")))
.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_inventory_read_request().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("prism"));
Ok(())
}
#[tokio::test]
async fn avatar_equip_forwards_backend_validation_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/equip"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"detail": "cannot equip unowned avatar prism",
})))
.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_equip_request(CodexAvatarEquipParams {
avatar_id: "prism".to_string(),
})
.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, "cannot equip unowned avatar prism");
Ok(())
}
#[tokio::test]
async fn avatar_equip_returns_snapshot_with_clippy_fallback() -> 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/equip"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(snapshot_json("clippy")))
.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_equip_request(CodexAvatarEquipParams {
avatar_id: "sunset".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("clippy"));
Ok(())
}
fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result<()> {
std::fs::write(
codex_home.join("config.toml"),
format!("chatgpt_base_url = \"{base_url}\"\n"),
)
}
fn snapshot_json(equipped_avatar_id: &str) -> Value {
json!({
"accountUserId": "account-123",
"avatarDefinitions": [
{
"avatarId": "clippy",
"slug": "clippy",
"displayName": "Clippy",
"description": "The default Codex paperclip avatar",
"rarity": "common",
"assetRef": "builtin:clippy",
"status": "active",
"sortOrder": 0,
"createdAt": 0,
"updatedAt": 0,
},
{
"avatarId": "prism",
"slug": "prism",
"displayName": "Prism",
"description": "A shiny earnable avatar",
"rarity": "rare",
"assetRef": "builtin:prism",
"status": "hidden",
"sortOrder": 10,
"createdAt": 1000,
"updatedAt": 2000,
}
],
"ownedAvatars": [
{
"accountUserId": "account-123",
"avatarId": "clippy",
"firstUnlockedAt": 100,
"lastAwardedAt": 100,
"sourceSummary": "Default avatar",
},
{
"accountUserId": "account-123",
"avatarId": "prism",
"firstUnlockedAt": 200,
"lastAwardedAt": 300,
"sourceSummary": "Quest reward",
}
],
"equippedAvatarId": equipped_avatar_id,
"equippedAt": 400,
"updatedAt": 500,
"syncedAt": 600,
"catalogVersion": 700,
})
}
fn expected_snapshot(equipped_avatar_id: &str) -> CodexAvatarInventoryReadResponse {
CodexAvatarInventoryReadResponse {
account_user_id: "account-123".to_string(),
avatar_definitions: vec![
CodexAvatarDefinition {
avatar_id: "clippy".to_string(),
slug: "clippy".to_string(),
display_name: "Clippy".to_string(),
description: "The default Codex paperclip avatar".to_string(),
rarity: CodexAvatarRarity::Common,
asset_ref: "builtin:clippy".to_string(),
status: CodexAvatarStatus::Active,
sort_order: 0,
created_at: 0,
updated_at: 0,
},
CodexAvatarDefinition {
avatar_id: "prism".to_string(),
slug: "prism".to_string(),
display_name: "Prism".to_string(),
description: "A shiny earnable avatar".to_string(),
rarity: CodexAvatarRarity::Rare,
asset_ref: "builtin:prism".to_string(),
status: CodexAvatarStatus::Hidden,
sort_order: 10,
created_at: 1000,
updated_at: 2000,
},
],
owned_avatars: vec![
CodexAvatarOwnership {
account_user_id: "account-123".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(),
avatar_id: "prism".to_string(),
first_unlocked_at: 200,
last_awarded_at: 300,
source_summary: Some("Quest reward".to_string()),
},
],
equipped_avatar_id: equipped_avatar_id.to_string(),
equipped_at: 400,
updated_at: 500,
synced_at: 600,
catalog_version: Some(700),
}
}
@@ -1,6 +1,7 @@
mod account;
mod analytics;
mod app_list;
mod avatar;
mod collaboration_mode_list;
#[cfg(unix)]
mod command_exec;
+106
View File
@@ -1,8 +1,11 @@
use crate::types::CodeTaskDetailsResponse;
use crate::types::CodexAvatarEquipRequest;
use crate::types::CodexAvatarInventoryResponse;
use crate::types::ConfigFileResponse;
use crate::types::PaginatedListTaskListItem;
use crate::types::RateLimitStatusPayload;
use crate::types::TurnAttemptsSiblingTurnsResponse;
use crate::types::WorkspaceOutOfCreditsNotificationResponse;
use anyhow::Result;
use codex_client::build_reqwest_client_with_custom_ca;
use codex_core::auth::CodexAuth;
@@ -265,6 +268,38 @@ impl Client {
Ok(Self::rate_limit_snapshots_from_payload(payload))
}
pub async fn get_avatar_inventory(
&self,
) -> std::result::Result<CodexAvatarInventoryResponse, RequestError> {
let url = match self.path_style {
PathStyle::CodexApi => format!("{}/api/codex/avatars/inventory", self.base_url),
PathStyle::ChatGptApi => format!("{}/wham/avatars/inventory", 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::<CodexAvatarInventoryResponse>(&url, &ct, &body)
.map_err(RequestError::from)
}
pub async fn equip_avatar(
&self,
avatar_id: String,
) -> std::result::Result<CodexAvatarInventoryResponse, RequestError> {
let url = match self.path_style {
PathStyle::CodexApi => format!("{}/api/codex/avatars/equip", self.base_url),
PathStyle::ChatGptApi => format!("{}/wham/avatars/equip", self.base_url),
};
let req = self
.http
.post(&url)
.headers(self.headers())
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.json(&CodexAvatarEquipRequest { avatar_id });
let (body, ct) = self.exec_request_detailed(req, "POST", &url).await?;
self.decode_json::<CodexAvatarInventoryResponse>(&url, &ct, &body)
.map_err(RequestError::from)
}
pub async fn list_tasks(
&self,
limit: Option<i32>,
@@ -357,6 +392,16 @@ impl Client {
.map_err(RequestError::from)
}
pub async fn post_workspace_out_of_credits_notification(
&self,
) -> std::result::Result<WorkspaceOutOfCreditsNotificationResponse, RequestError> {
let url = self.workspace_out_of_credits_notification_url()?;
let req = self.http.post(&url).headers(self.headers());
let (body, ct) = self.exec_request_detailed(req, "POST", &url).await?;
self.decode_json::<WorkspaceOutOfCreditsNotificationResponse>(&url, &ct, &body)
.map_err(RequestError::from)
}
/// Create a new task (user turn) by POSTing to the appropriate backend path
/// based on `path_style`. Returns the created task id.
pub async fn create_task(&self, request_body: serde_json::Value) -> Result<String> {
@@ -498,6 +543,20 @@ impl Client {
let seconds_i64 = i64::from(seconds);
Some((seconds_i64 + 59) / 60)
}
fn workspace_out_of_credits_notification_url(
&self,
) -> std::result::Result<String, RequestError> {
match self.path_style {
PathStyle::ChatGptApi => Ok(format!(
"{}/credits/workspace_out_of_credits_notifications",
self.base_url
)),
PathStyle::CodexApi => Err(RequestError::Other(anyhow::anyhow!(
"workspace out-of-credits notifications are only supported for ChatGPT backend-api"
))),
}
}
}
#[cfg(test)]
@@ -649,4 +708,51 @@ mod tests {
.unwrap_or_else(|| snapshots[0].clone());
assert_eq!(preferred.limit_id.as_deref(), Some("codex"));
}
#[test]
fn workspace_notification_url_uses_chatgpt_credits_path() {
let client = Client::new("https://chatgpt.com").expect("client");
let url = client
.workspace_out_of_credits_notification_url()
.expect("chatgpt backend-api url");
assert_eq!(
url,
"https://chatgpt.com/backend-api/credits/workspace_out_of_credits_notifications"
);
}
#[test]
fn workspace_notification_url_rejects_codex_api_paths() {
let client = Client::new("https://api.openai.com").expect("client");
let err = client
.workspace_out_of_credits_notification_url()
.expect_err("codex api path should be rejected");
assert_eq!(
err.to_string(),
"workspace out-of-credits notifications are only supported for ChatGPT backend-api"
);
}
#[test]
fn workspace_notification_response_decodes() {
let client = Client::new("https://chatgpt.com").expect("client");
let response: WorkspaceOutOfCreditsNotificationResponse = client
.decode_json(
"https://chatgpt.com/backend-api/credits/workspace_out_of_credits_notifications",
"application/json",
r#"{"status":"cooldown_active"}"#,
)
.expect("response should decode");
assert_eq!(
response,
WorkspaceOutOfCreditsNotificationResponse {
status: crate::types::WorkspaceOutOfCreditsNotificationStatus::CooldownActive,
}
);
}
}
+8
View File
@@ -5,7 +5,15 @@ pub use client::Client;
pub use client::RequestError;
pub use types::CodeTaskDetailsResponse;
pub use types::CodeTaskDetailsResponseExt;
pub use types::CodexAvatarDefinition;
pub use types::CodexAvatarEquipRequest;
pub use types::CodexAvatarInventoryResponse;
pub use types::CodexAvatarOwnership;
pub use types::CodexAvatarRarity;
pub use types::CodexAvatarStatus;
pub use types::ConfigFileResponse;
pub use types::PaginatedListTaskListItem;
pub use types::TaskListItem;
pub use types::TurnAttemptsSiblingTurnsResponse;
pub use types::WorkspaceOutOfCreditsNotificationResponse;
pub use types::WorkspaceOutOfCreditsNotificationStatus;
+74
View File
@@ -9,10 +9,84 @@ pub use codex_backend_openapi_models::models::RateLimitWindowSnapshot;
pub use codex_backend_openapi_models::models::TaskListItem;
use serde::Deserialize;
use serde::Serialize;
use serde::de::Deserializer;
use serde_json::Value;
use std::collections::HashMap;
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceOutOfCreditsNotificationStatus {
Sent,
CooldownActive,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct WorkspaceOutOfCreditsNotificationResponse {
pub status: WorkspaceOutOfCreditsNotificationStatus,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum CodexAvatarStatus {
Active,
Hidden,
Retired,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum CodexAvatarRarity {
Common,
Rare,
Epic,
Legendary,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodexAvatarDefinition {
pub avatar_id: String,
pub slug: String,
pub display_name: String,
pub description: String,
pub rarity: CodexAvatarRarity,
pub asset_ref: String,
pub status: CodexAvatarStatus,
pub sort_order: i64,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodexAvatarOwnership {
pub account_user_id: String,
pub avatar_id: String,
pub first_unlocked_at: i64,
pub last_awarded_at: i64,
pub source_summary: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodexAvatarEquipRequest {
pub avatar_id: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodexAvatarInventoryResponse {
pub account_user_id: String,
pub avatar_definitions: Vec<CodexAvatarDefinition>,
pub owned_avatars: Vec<CodexAvatarOwnership>,
pub equipped_avatar_id: String,
pub equipped_at: i64,
pub updated_at: i64,
pub synced_at: i64,
pub catalog_version: Option<i64>,
}
/// 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.
+1
View File
@@ -26,6 +26,7 @@ clap = { workspace = true, features = ["derive"] }
codex-arg0 = { workspace = true }
codex-app-server-client = { workspace = true }
codex-app-server-protocol = { workspace = true }
codex-backend-client = { workspace = true }
codex-cloud-requirements = { workspace = true }
codex-core = { workspace = true }
codex-feedback = { workspace = true }
+19
View File
@@ -9,6 +9,7 @@ mod event_processor;
mod event_processor_with_human_output;
pub mod event_processor_with_jsonl_output;
pub mod exec_events;
mod workspace_out_of_credits;
pub use cli::Cli;
pub use cli::Command;
@@ -730,6 +731,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
// Track whether a fatal error was reported by the server so we can
// exit with a non-zero status for automation-friendly signaling.
let mut error_seen = false;
let mut workspace_out_of_credits_candidate = false;
let mut interrupt_channel_open = true;
let primary_thread_id_for_requests = primary_thread_id.to_string();
loop {
@@ -768,6 +770,14 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
handle_server_request(&client, request, &mut error_seen).await;
}
InProcessServerEvent::ServerNotification(mut notification) => {
if workspace_out_of_credits::notification_is_usage_limit_failure(
&notification,
&primary_thread_id_for_requests,
&task_id,
) {
workspace_out_of_credits_candidate = true;
}
if let ServerNotification::Error(payload) = &notification {
if payload.thread_id == primary_thread_id_for_requests
&& payload.turn_id == task_id
@@ -824,6 +834,15 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
warn!("in-process app-server shutdown failed: {err}");
}
event_processor.print_final_output();
if let Err(err) = workspace_out_of_credits::maybe_prompt_for_workspace_out_of_credits(
&config,
workspace_out_of_credits_candidate && error_seen,
!json_mode,
)
.await
{
warn!("workspace out-of-credits prompt failed: {err}");
}
if error_seen {
std::process::exit(1);
}