Skip to main content

codex_codes/
protocol.rs

1//! App-server protocol types for the Codex CLI.
2//!
3//! Every wire type is generated from the upstream JSON Schema bundle by
4//! `scripts/codegen_protocol.py` and lives in [`crate::protocol_generated::types`].
5//! This module re-exports them and adds the JSON-RPC method-name constants
6//! the dispatch layer matches against.
7//!
8//! # Parsing notifications
9//!
10//! Prefer the typed dispatch in [`crate::messages`] over manual `method` checks:
11//!
12//! ```
13//! use codex_codes::{Notification, ServerMessage};
14//!
15//! fn handle(msg: ServerMessage) {
16//!     if let ServerMessage::Notification(Notification::TurnCompleted(c)) = msg {
17//!         println!("Turn on thread {} completed", c.thread_id);
18//!     }
19//! }
20//! ```
21
22pub use crate::protocol_generated::types::*;
23
24/// JSON-RPC method names used by the app-server protocol.
25///
26/// Use these constants when matching on [`crate::ServerMessage::Notification`] or
27/// [`crate::ServerMessage::Request`] method fields to avoid typos.
28pub mod methods {
29    // Client → server requests
30    pub const INITIALIZE: &str = "initialize";
31    pub const INITIALIZED: &str = "initialized";
32    pub const THREAD_START: &str = "thread/start";
33    pub const THREAD_ARCHIVE: &str = "thread/archive";
34    pub const THREAD_DELETE: &str = "thread/delete";
35    pub const TURN_START: &str = "turn/start";
36    pub const TURN_INTERRUPT: &str = "turn/interrupt";
37    pub const TURN_STEER: &str = "turn/steer";
38    pub const THREAD_RESUME: &str = "thread/resume";
39    pub const THREAD_FORK: &str = "thread/fork";
40    pub const THREAD_UNSUBSCRIBE: &str = "thread/unsubscribe";
41    pub const THREAD_NAME_SET: &str = "thread/name/set";
42    pub const THREAD_METADATA_UPDATE: &str = "thread/metadata/update";
43    pub const THREAD_ATTACHMENT_ADD: &str = "thread/attachment/add";
44    pub const THREAD_ATTACHMENT_LIST: &str = "thread/attachment/list";
45    pub const THREAD_ATTACHMENT_REMOVE: &str = "thread/attachment/remove";
46    pub const THREAD_ATTACHMENT_OWNER_LIST: &str = "thread/attachmentOwner/list";
47    pub const THREAD_UNARCHIVE: &str = "thread/unarchive";
48    pub const THREAD_COMPACT_START: &str = "thread/compact/start";
49    pub const THREAD_SHELLCOMMAND: &str = "thread/shellCommand";
50    pub const THREAD_APPROVEGUARDIANDENIEDACTION: &str = "thread/approveGuardianDeniedAction";
51    pub const THREAD_LIST: &str = "thread/list";
52    pub const THREAD_LOADED_LIST: &str = "thread/loaded/list";
53    pub const THREAD_READ: &str = "thread/read";
54    pub const THREAD_INJECT_ITEMS: &str = "thread/inject_items";
55    pub const THREAD_ITEMS_LIST: &str = "thread/items/list";
56    pub const THREAD_TURNS_LIST: &str = "thread/turns/list";
57    pub const THREAD_REVERT: &str = "thread/revert";
58    pub const SKILLS_LIST: &str = "skills/list";
59    pub const HOOKS_LIST: &str = "hooks/list";
60    pub const MARKETPLACE_ADD: &str = "marketplace/add";
61    pub const MARKETPLACE_REMOVE: &str = "marketplace/remove";
62    pub const MARKETPLACE_UPGRADE: &str = "marketplace/upgrade";
63    pub const PLUGIN_LIST: &str = "plugin/list";
64    pub const PLUGIN_READ: &str = "plugin/read";
65    pub const PLUGIN_SKILL_READ: &str = "plugin/skill/read";
66    pub const PLUGIN_SHARE_SAVE: &str = "plugin/share/save";
67    pub const PLUGIN_SHARE_UPDATETARGETS: &str = "plugin/share/updateTargets";
68    pub const PLUGIN_SHARE_LIST: &str = "plugin/share/list";
69    pub const PLUGIN_SHARE_CHECKOUT: &str = "plugin/share/checkout";
70    pub const PLUGIN_SHARE_DELETE: &str = "plugin/share/delete";
71    pub const APP_LIST: &str = "app/list";
72    pub const APP_READ: &str = "app/read";
73    pub const APP_INSTALLED: &str = "app/installed";
74    pub const FS_READFILE: &str = "fs/readFile";
75    pub const FS_WRITEFILE: &str = "fs/writeFile";
76    pub const FS_CREATEDIRECTORY: &str = "fs/createDirectory";
77    pub const FS_GETMETADATA: &str = "fs/getMetadata";
78    pub const FS_READDIRECTORY: &str = "fs/readDirectory";
79    pub const FS_REMOVE: &str = "fs/remove";
80    pub const FS_COPY: &str = "fs/copy";
81    pub const FS_WATCH: &str = "fs/watch";
82    pub const FS_UNWATCH: &str = "fs/unwatch";
83    pub const SKILLS_CONFIG_WRITE: &str = "skills/config/write";
84    pub const PLUGIN_INSTALL: &str = "plugin/install";
85    pub const PLUGIN_UNINSTALL: &str = "plugin/uninstall";
86    pub const REVIEW_START: &str = "review/start";
87    pub const MODEL_LIST: &str = "model/list";
88    pub const ACCOUNT_GATEWAYOAUTH_READ: &str = "account/gatewayOAuth/read";
89    pub const ACCOUNT_GATEWAYOAUTH_LOGIN: &str = "account/gatewayOAuth/login";
90    pub const ACCOUNT_GATEWAYOAUTH_CANCEL: &str = "account/gatewayOAuth/cancel";
91    pub const MODELPROVIDER_LIST: &str = "modelProvider/list";
92    pub const MODELPROVIDER_CONFIG_WRITE: &str = "modelProvider/config/write";
93    pub const MODELPROVIDER_DEFAULT_SET: &str = "modelProvider/default/set";
94    pub const MODELPROVIDER_CAPABILITIES_READ: &str = "modelProvider/capabilities/read";
95    pub const EXPERIMENTALFEATURE_LIST: &str = "experimentalFeature/list";
96    pub const EXPERIMENTALFEATURE_ENABLEMENT_SET: &str = "experimentalFeature/enablement/set";
97    pub const MCPSERVER_OAUTH_LOGIN: &str = "mcpServer/oauth/login";
98    pub const CONFIG_MCPSERVER_RELOAD: &str = "config/mcpServer/reload";
99    pub const MCPSERVERSTATUS_LIST: &str = "mcpServerStatus/list";
100    pub const MCPSERVER_RESOURCE_READ: &str = "mcpServer/resource/read";
101    pub const MCPSERVER_TOOL_CALL: &str = "mcpServer/tool/call";
102    pub const WINDOWSSANDBOX_SETUPSTART: &str = "windowsSandbox/setupStart";
103    pub const WINDOWSSANDBOX_READINESS: &str = "windowsSandbox/readiness";
104    pub const ACCOUNT_LOGIN_START: &str = "account/login/start";
105    pub const ACCOUNT_LOGIN_CANCEL: &str = "account/login/cancel";
106    pub const ACCOUNT_LOGOUT: &str = "account/logout";
107    pub const ACCOUNT_RATELIMITS_READ: &str = "account/rateLimits/read";
108    pub const ACCOUNT_SENDADDCREDITSNUDGEEMAIL: &str = "account/sendAddCreditsNudgeEmail";
109    pub const FEEDBACK_UPLOAD: &str = "feedback/upload";
110    pub const FEEDBACK_SAVE: &str = "feedback/save";
111    pub const COMMAND_EXEC: &str = "command/exec";
112    pub const COMMAND_EXEC_WRITE: &str = "command/exec/write";
113    pub const COMMAND_EXEC_TERMINATE: &str = "command/exec/terminate";
114    pub const COMMAND_EXEC_RESIZE: &str = "command/exec/resize";
115    pub const CONFIG_READ: &str = "config/read";
116    pub const EXTERNALAGENTCONFIG_DETECT: &str = "externalAgentConfig/detect";
117    pub const EXTERNALAGENTCONFIG_IMPORT: &str = "externalAgentConfig/import";
118    pub const CONFIG_VALUE_WRITE: &str = "config/value/write";
119    pub const CONFIG_BATCHWRITE: &str = "config/batchWrite";
120    pub const CONFIGREQUIREMENTS_READ: &str = "configRequirements/read";
121    pub const ACCOUNT_READ: &str = "account/read";
122    pub const FUZZYFILESEARCH: &str = "fuzzyFileSearch";
123    pub const ACCOUNT_USAGE_READ: &str = "account/usage/read";
124    pub const PERMISSION_PROFILE_LIST: &str = "permissionProfile/list";
125    pub const PLUGIN_INSTALLED: &str = "plugin/installed";
126    pub const PLUGIN_RECONCILE: &str = "plugin/reconcile";
127    pub const SKILLS_EXTRA_ROOTS_SET: &str = "skills/extraRoots/set";
128    pub const THREAD_GOAL_GET: &str = "thread/goal/get";
129    pub const THREAD_GOAL_SET: &str = "thread/goal/set";
130    pub const THREAD_GOAL_CLEAR: &str = "thread/goal/clear";
131    pub const THREADSECTION_LIST: &str = "threadSection/list";
132    pub const THREADSECTION_CREATE: &str = "threadSection/create";
133    pub const THREADSECTION_UPDATE: &str = "threadSection/update";
134    pub const THREADSECTION_DELETE: &str = "threadSection/delete";
135    pub const THREAD_SECTION_MOVE: &str = "thread/section/move";
136    pub const ACCOUNT_RATELIMITRESETCREDIT_CONSUME: &str = "account/rateLimitResetCredit/consume";
137    pub const ACCOUNT_WORKSPACEMESSAGES_READ: &str = "account/workspaceMessages/read";
138    pub const ACCOUNT_SECURITYSETUP_READ: &str = "account/securitySetup/read";
139    pub const EXTERNALAGENTCONFIG_IMPORT_READHISTORIES: &str =
140        "externalAgentConfig/import/readHistories";
141    pub const EXTERNALAGENTCONFIG_IMPORT_RECORDHISTORY: &str =
142        "externalAgentConfig/import/recordHistory";
143
144    // Server → client notifications
145    pub const THREAD_STARTED: &str = "thread/started";
146    pub const STRICT_REVIEW_REQUIRED: &str = "autoApprovalReview/strictReviewRequired";
147    pub const PROJECT_CHANGED: &str = "project/changed";
148    pub const THREAD_PROJECT_UPDATED: &str = "thread/project/updated";
149    pub const THREAD_QUEUE_CHANGED: &str = "thread/queue/changed";
150    pub const THREAD_REVERTED: &str = "thread/reverted";
151    pub const THREAD_PREDICTION_UPDATED: &str = "thread/prediction/updated";
152    pub const MCP_SERVER_EVENT_STREAM: &str = "mcpServer/event/stream/notification";
153    pub const THREAD_STATUS_CHANGED: &str = "thread/status/changed";
154    pub const THREAD_READ_STATE_CHANGED: &str = "thread/readState/changed";
155    pub const THREAD_SECTION_CHANGED: &str = "thread/section/changed";
156    pub const THREAD_TOKEN_USAGE_UPDATED: &str = "thread/tokenUsage/updated";
157    pub const TURN_STARTED: &str = "turn/started";
158    pub const TURN_COMPLETED: &str = "turn/completed";
159    pub const ITEM_STARTED: &str = "item/started";
160    pub const ITEM_COMPLETED: &str = "item/completed";
161    pub const AGENT_MESSAGE_DELTA: &str = "item/agentMessage/delta";
162    pub const CMD_OUTPUT_DELTA: &str = "item/commandExecution/outputDelta";
163    pub const FILE_CHANGE_OUTPUT_DELTA: &str = "item/fileChange/outputDelta";
164    pub const REASONING_DELTA: &str = "item/reasoning/summaryTextDelta";
165    pub const ERROR: &str = "error";
166    pub const ACCOUNT_RATE_LIMITS_UPDATED: &str = "account/rateLimits/updated";
167    pub const MCP_SERVER_STARTUP_STATUS_UPDATED: &str = "mcpServer/startupStatus/updated";
168    pub const MCP_SERVER_OAUTH_LOGIN_COMPLETED: &str = "mcpServer/oauthLogin/completed";
169    pub const REMOTE_CONTROL_STATUS_CHANGED: &str = "remoteControl/status/changed";
170    pub const FILE_CHANGE_PATCH_UPDATED: &str = "item/fileChange/patchUpdated";
171    pub const PLAN_DELTA: &str = "item/plan/delta";
172    pub const TURN_PLAN_UPDATED: &str = "turn/plan/updated";
173    pub const TURN_DIFF_UPDATED: &str = "turn/diff/updated";
174    pub const REASONING_SUMMARY_PART_ADDED: &str = "item/reasoning/summaryPartAdded";
175    pub const REASONING_TEXT_DELTA: &str = "item/reasoning/textDelta";
176    pub const ACCOUNT_LOGIN_COMPLETED: &str = "account/login/completed";
177    pub const DEPRECATION_NOTICE: &str = "deprecationNotice";
178    pub const GUARDIAN_WARNING: &str = "guardianWarning";
179    pub const WARNING: &str = "warning";
180    pub const THREAD_ARCHIVED: &str = "thread/archived";
181    pub const THREAD_CLOSED: &str = "thread/closed";
182    pub const THREAD_DELETED: &str = "thread/deleted";
183    pub const THREAD_UNARCHIVED: &str = "thread/unarchived";
184    pub const THREAD_GOAL_CLEARED: &str = "thread/goal/cleared";
185    pub const THREAD_NAME_UPDATED: &str = "thread/name/updated";
186    pub const THREAD_ATTACHMENT_UPDATED: &str = "thread/attachment/updated";
187    pub const SKILLS_CHANGED: &str = "skills/changed";
188    pub const FS_CHANGED: &str = "fs/changed";
189    pub const CONFIG_WARNING: &str = "configWarning";
190    pub const ACCOUNT_UPDATED: &str = "account/updated";
191    pub const ACCOUNT_GATEWAY_OAUTH_CHANGED: &str = "account/gatewayOAuth/changed";
192    pub const APP_LIST_UPDATED: &str = "app/list/updated";
193    pub const COMMAND_EXEC_OUTPUT_DELTA: &str = "command/exec/outputDelta";
194    pub const EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED: &str = "externalAgentConfig/import/completed";
195    pub const FUZZY_FILE_SEARCH_SESSION_COMPLETED: &str = "fuzzyFileSearch/sessionCompleted";
196    pub const FUZZY_FILE_SEARCH_SESSION_UPDATED: &str = "fuzzyFileSearch/sessionUpdated";
197    pub const HOOK_COMPLETED: &str = "hook/completed";
198    pub const HOOK_STARTED: &str = "hook/started";
199    pub const ITEM_AUTO_APPROVAL_REVIEW_COMPLETED: &str = "item/autoApprovalReview/completed";
200    pub const ITEM_AUTO_APPROVAL_REVIEW_STARTED: &str = "item/autoApprovalReview/started";
201    pub const ITEM_COMMAND_EXEC_TERMINAL_INTERACTION: &str =
202        "item/commandExecution/terminalInteraction";
203    pub const ITEM_MCP_TOOL_CALL_PROGRESS: &str = "item/mcpToolCall/progress";
204    pub const MODEL_REROUTED: &str = "model/rerouted";
205    pub const MODEL_VERIFICATION: &str = "model/verification";
206    pub const PROCESS_EXITED: &str = "process/exited";
207    pub const PROCESS_OUTPUT_DELTA: &str = "process/outputDelta";
208    pub const SERVER_REQUEST_RESOLVED: &str = "serverRequest/resolved";
209    pub const THREAD_SEARCH_PARTIAL: &str = "thread/search/partial";
210    pub const THREAD_COMPACTED: &str = "thread/compacted";
211    pub const THREAD_GOAL_UPDATED: &str = "thread/goal/updated";
212    pub const THREAD_REALTIME_CLOSED: &str = "thread/realtime/closed";
213    pub const THREAD_REALTIME_ERROR: &str = "thread/realtime/error";
214    pub const THREAD_REALTIME_ITEM_ADDED: &str = "thread/realtime/itemAdded";
215    pub const THREAD_REALTIME_OUTPUT_AUDIO_DELTA: &str = "thread/realtime/outputAudio/delta";
216    pub const THREAD_REALTIME_SDP: &str = "thread/realtime/sdp";
217    pub const THREAD_REALTIME_STARTED: &str = "thread/realtime/started";
218    pub const THREAD_REALTIME_TRANSCRIPT_DELTA: &str = "thread/realtime/transcript/delta";
219    pub const THREAD_REALTIME_TRANSCRIPT_DONE: &str = "thread/realtime/transcript/done";
220    pub const THREAD_REALTIME_ITEM_STARTED: &str = "thread/realtime/item/started";
221    pub const THREAD_REALTIME_ITEM_COMPLETED: &str = "thread/realtime/item/completed";
222    pub const THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA: &str = "thread/realtime/item/transcript/delta";
223    pub const MODEL_PROVIDER_AUTH_RECOVERY_STARTED: &str = "modelProvider/authRecoveryStarted";
224    pub const MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED: &str = "modelProvider/authRecoveryCompleted";
225    pub const WINDOWS_WORLD_WRITABLE_WARNING: &str = "windows/worldWritableWarning";
226    pub const WINDOWS_SANDBOX_SETUP_COMPLETED: &str = "windowsSandbox/setupCompleted";
227    pub const THREAD_SETTINGS_UPDATED: &str = "thread/settings/updated";
228    pub const TURN_MODERATION_METADATA: &str = "turn/moderationMetadata";
229    pub const EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS: &str = "externalAgentConfig/import/progress";
230    pub const MODEL_SAFETY_BUFFERING_UPDATED: &str = "model/safetyBuffering/updated";
231    pub const THREAD_ENVIRONMENT_CONNECTED: &str = "thread/environment/connected";
232    pub const THREAD_ENVIRONMENT_DISCONNECTED: &str = "thread/environment/disconnected";
233
234    // Server → client requests (approval flow, v2 envelope)
235    pub const CMD_EXEC_APPROVAL: &str = "item/commandExecution/requestApproval";
236    pub const FILE_CHANGE_APPROVAL: &str = "item/fileChange/requestApproval";
237    pub const TOOL_REQUEST_USER_INPUT: &str = "item/tool/requestUserInput";
238    pub const MCP_SERVER_ELICITATION_REQUEST: &str = "mcpServer/elicitation/request";
239    pub const PERMISSIONS_REQUEST_APPROVAL: &str = "item/permissions/requestApproval";
240    pub const ITEM_TOOL_CALL: &str = "item/tool/call";
241    pub const CHATGPT_AUTH_TOKENS_REFRESH: &str = "account/chatgptAuthTokens/refresh";
242    pub const ATTESTATION_GENERATE: &str = "attestation/generate";
243    pub const APPLY_PATCH_APPROVAL: &str = "applyPatchApproval";
244    pub const EXEC_COMMAND_APPROVAL: &str = "execCommandApproval";
245}
246
247// ──────────────────────────────────────────────────────────────────────────
248// Ergonomic constructors over the generated wire types.
249//
250// The types themselves are code-generated from the upstream schema; these
251// hand-written impls live here so they survive regeneration. (`Default` for
252// params whose fields are all serde-defaultable is derived by the codegen
253// itself since #203.) They cover one pain point for downstream consumers:
254//
255//   * `accept` / `decline` / `approved` / `denied` constructors for the
256//     approval-response payloads, so callers don't hand-roll `serde_json`
257//     objects and can't typo the wire `decision` string.
258// ──────────────────────────────────────────────────────────────────────────
259
260impl FileChangeRequestApprovalResponse {
261    /// Approve this file-change request (`{"decision":"accept"}`).
262    pub fn accept() -> Self {
263        Self {
264            decision: FileChangeApprovalDecision::Accept,
265        }
266    }
267
268    /// Approve this and future file changes for the session.
269    pub fn accept_for_session() -> Self {
270        Self {
271            decision: FileChangeApprovalDecision::AcceptForSession,
272        }
273    }
274
275    /// Decline this file-change request (`{"decision":"decline"}`).
276    pub fn decline() -> Self {
277        Self {
278            decision: FileChangeApprovalDecision::Decline,
279        }
280    }
281
282    /// Cancel the turn in response to this request.
283    pub fn cancel() -> Self {
284        Self {
285            decision: FileChangeApprovalDecision::Cancel,
286        }
287    }
288}
289
290impl CommandExecutionRequestApprovalResponse {
291    /// Approve this command execution (`{"decision":"accept"}`).
292    pub fn accept() -> Self {
293        Self {
294            decision: CommandExecutionApprovalDecision::Accept,
295        }
296    }
297
298    /// Approve this and future command executions for the session.
299    pub fn accept_for_session() -> Self {
300        Self {
301            decision: CommandExecutionApprovalDecision::AcceptForSession,
302        }
303    }
304
305    /// Decline this command execution (`{"decision":"decline"}`).
306    pub fn decline() -> Self {
307        Self {
308            decision: CommandExecutionApprovalDecision::Decline,
309        }
310    }
311
312    /// Cancel the turn in response to this request.
313    pub fn cancel() -> Self {
314        Self {
315            decision: CommandExecutionApprovalDecision::Cancel,
316        }
317    }
318}
319
320impl ExecCommandApprovalResponse {
321    /// Approve the exec command (`{"decision":"approved"}`).
322    pub fn approved() -> Self {
323        Self {
324            decision: ReviewDecision::Approved,
325        }
326    }
327
328    /// Approve the exec command for the rest of the session.
329    pub fn approved_for_session() -> Self {
330        Self {
331            decision: ReviewDecision::ApprovedForSession,
332        }
333    }
334
335    /// Deny the exec command (`{"decision":{"denied":{"rejection":...}}}`).
336    pub fn denied(rejection: impl Into<String>) -> Self {
337        Self {
338            decision: ReviewDecision::Denied {
339                rejection: rejection.into(),
340            },
341        }
342    }
343
344    /// Abort the turn in response to the request.
345    pub fn abort() -> Self {
346        Self {
347            decision: ReviewDecision::Abort,
348        }
349    }
350}
351
352impl ApplyPatchApprovalResponse {
353    /// Approve the patch (`{"decision":"approved"}`).
354    pub fn approved() -> Self {
355        Self {
356            decision: ReviewDecision::Approved,
357        }
358    }
359
360    /// Approve this and future patches for the session.
361    pub fn approved_for_session() -> Self {
362        Self {
363            decision: ReviewDecision::ApprovedForSession,
364        }
365    }
366
367    /// Deny the patch (`{"decision":{"denied":{"rejection":...}}}`).
368    pub fn denied(rejection: impl Into<String>) -> Self {
369        Self {
370            decision: ReviewDecision::Denied {
371                rejection: rejection.into(),
372            },
373        }
374    }
375
376    /// Abort the turn in response to the request.
377    pub fn abort() -> Self {
378        Self {
379            decision: ReviewDecision::Abort,
380        }
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387
388    #[test]
389    fn thread_start_params_default_is_empty_object() {
390        let p = ThreadStartParams::default();
391        assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!({}));
392    }
393
394    #[test]
395    fn turn_start_params_default_round_trips() {
396        let p = TurnStartParams::default();
397        let v = serde_json::to_value(&p).unwrap();
398        // thread_id + input are required-but-defaulted; everything else omits.
399        assert_eq!(v["threadId"], "");
400        assert_eq!(v["input"], serde_json::json!([]));
401    }
402
403    #[test]
404    fn thread_resume_and_fork_params_default() {
405        let _ = ThreadResumeParams::default();
406        let _ = ThreadForkParams::default();
407    }
408
409    #[test]
410    fn file_change_approval_response_wire_shape() {
411        assert_eq!(
412            serde_json::to_value(FileChangeRequestApprovalResponse::accept()).unwrap(),
413            serde_json::json!({"decision": "accept"})
414        );
415        assert_eq!(
416            serde_json::to_value(FileChangeRequestApprovalResponse::decline()).unwrap(),
417            serde_json::json!({"decision": "decline"})
418        );
419    }
420
421    #[test]
422    fn command_execution_approval_response_wire_shape() {
423        assert_eq!(
424            serde_json::to_value(CommandExecutionRequestApprovalResponse::accept()).unwrap(),
425            serde_json::json!({"decision": "accept"})
426        );
427        assert_eq!(
428            serde_json::to_value(CommandExecutionRequestApprovalResponse::cancel()).unwrap(),
429            serde_json::json!({"decision": "cancel"})
430        );
431    }
432
433    #[test]
434    fn exec_and_apply_patch_approval_response_wire_shape() {
435        assert_eq!(
436            serde_json::to_value(ExecCommandApprovalResponse::approved()).unwrap(),
437            serde_json::json!({"decision": "approved"})
438        );
439        assert_eq!(
440            serde_json::to_value(ApplyPatchApprovalResponse::denied("keep the original file"))
441                .unwrap(),
442            serde_json::json!({"decision": {"denied": {"rejection": "keep the original file"}}})
443        );
444    }
445
446    #[test]
447    fn hook_event_name_model_request_round_trips() {
448        for (event, wire) in [
449            (HookEventName::PreModelRequest, "preModelRequest"),
450            (HookEventName::PostModelRequest, "postModelRequest"),
451        ] {
452            assert_eq!(serde_json::to_value(&event).unwrap(), wire);
453            assert_eq!(
454                serde_json::from_value::<HookEventName>(serde_json::json!(wire)).unwrap(),
455                event
456            );
457        }
458    }
459
460    #[test]
461    fn gcp_account_round_trips() {
462        let wire = serde_json::json!({"type": "gcp"});
463        assert_eq!(serde_json::to_value(Account::Gcp).unwrap(), wire);
464        assert_eq!(
465            serde_json::from_value::<Account>(wire).unwrap(),
466            Account::Gcp
467        );
468        let response: GetAccountResponse = serde_json::from_value(serde_json::json!({
469            "account": {"type": "gcp"},
470            "requiresOpenaiAuth": false
471        }))
472        .unwrap();
473        assert_eq!(response.account, Some(Account::Gcp));
474        assert_eq!(response.user_id, None);
475    }
476
477    #[test]
478    fn get_account_response_carries_user_id() {
479        let wire = serde_json::json!({
480            "account": {"type": "gcp"},
481            "requiresOpenaiAuth": false,
482            "userId": "user-abc123"
483        });
484        let response: GetAccountResponse = serde_json::from_value(wire.clone()).unwrap();
485        assert_eq!(response.user_id.as_deref(), Some("user-abc123"));
486        assert_eq!(serde_json::to_value(&response).unwrap(), wire);
487    }
488
489    #[test]
490    fn account_security_setup_response_round_trips() {
491        use crate::protocol_generated::types::{
492            AccountSecuritySetupAction, AccountSecuritySetupNotice, GetAccountSecuritySetupResponse,
493        };
494
495        let wire = serde_json::json!({
496            "notice": {
497                "accountId": "acct-1",
498                "userId": "user-1",
499                "title": "Secure your account",
500                "description": "Turn on multi-factor authentication.",
501                "action": {"label": "Set up MFA", "url": "https://chatgpt.com/security"}
502            }
503        });
504        let response: GetAccountSecuritySetupResponse =
505            serde_json::from_value(wire.clone()).unwrap();
506        assert_eq!(
507            response.notice,
508            Some(AccountSecuritySetupNotice {
509                account_id: "acct-1".to_string(),
510                user_id: "user-1".to_string(),
511                title: "Secure your account".to_string(),
512                description: "Turn on multi-factor authentication.".to_string(),
513                action: AccountSecuritySetupAction {
514                    label: "Set up MFA".to_string(),
515                    url: "https://chatgpt.com/security".to_string(),
516                },
517            })
518        );
519        assert_eq!(serde_json::to_value(&response).unwrap(), wire);
520
521        let empty = serde_json::json!({"notice": null});
522        let response: GetAccountSecuritySetupResponse =
523            serde_json::from_value(empty.clone()).unwrap();
524        assert_eq!(response.notice, None);
525        assert_eq!(serde_json::to_value(&response).unwrap(), empty);
526        assert_eq!(
527            serde_json::from_value::<GetAccountSecuritySetupResponse>(serde_json::json!({}))
528                .unwrap(),
529            GetAccountSecuritySetupResponse::default()
530        );
531    }
532}