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_UNARCHIVE: &str = "thread/unarchive";
44    pub const THREAD_COMPACT_START: &str = "thread/compact/start";
45    pub const THREAD_SHELLCOMMAND: &str = "thread/shellCommand";
46    pub const THREAD_APPROVEGUARDIANDENIEDACTION: &str = "thread/approveGuardianDeniedAction";
47    pub const THREAD_ROLLBACK: &str = "thread/rollback";
48    pub const THREAD_LIST: &str = "thread/list";
49    pub const THREAD_LOADED_LIST: &str = "thread/loaded/list";
50    pub const THREAD_READ: &str = "thread/read";
51    pub const THREAD_INJECT_ITEMS: &str = "thread/inject_items";
52    pub const SKILLS_LIST: &str = "skills/list";
53    pub const HOOKS_LIST: &str = "hooks/list";
54    pub const MARKETPLACE_ADD: &str = "marketplace/add";
55    pub const MARKETPLACE_REMOVE: &str = "marketplace/remove";
56    pub const MARKETPLACE_UPGRADE: &str = "marketplace/upgrade";
57    pub const PLUGIN_LIST: &str = "plugin/list";
58    pub const PLUGIN_READ: &str = "plugin/read";
59    pub const PLUGIN_SKILL_READ: &str = "plugin/skill/read";
60    pub const PLUGIN_SHARE_SAVE: &str = "plugin/share/save";
61    pub const PLUGIN_SHARE_UPDATETARGETS: &str = "plugin/share/updateTargets";
62    pub const PLUGIN_SHARE_LIST: &str = "plugin/share/list";
63    pub const PLUGIN_SHARE_CHECKOUT: &str = "plugin/share/checkout";
64    pub const PLUGIN_SHARE_DELETE: &str = "plugin/share/delete";
65    pub const APP_LIST: &str = "app/list";
66    pub const FS_READFILE: &str = "fs/readFile";
67    pub const FS_WRITEFILE: &str = "fs/writeFile";
68    pub const FS_CREATEDIRECTORY: &str = "fs/createDirectory";
69    pub const FS_GETMETADATA: &str = "fs/getMetadata";
70    pub const FS_READDIRECTORY: &str = "fs/readDirectory";
71    pub const FS_REMOVE: &str = "fs/remove";
72    pub const FS_COPY: &str = "fs/copy";
73    pub const FS_WATCH: &str = "fs/watch";
74    pub const FS_UNWATCH: &str = "fs/unwatch";
75    pub const SKILLS_CONFIG_WRITE: &str = "skills/config/write";
76    pub const PLUGIN_INSTALL: &str = "plugin/install";
77    pub const PLUGIN_UNINSTALL: &str = "plugin/uninstall";
78    pub const REVIEW_START: &str = "review/start";
79    pub const MODEL_LIST: &str = "model/list";
80    pub const MODELPROVIDER_CAPABILITIES_READ: &str = "modelProvider/capabilities/read";
81    pub const EXPERIMENTALFEATURE_LIST: &str = "experimentalFeature/list";
82    pub const EXPERIMENTALFEATURE_ENABLEMENT_SET: &str = "experimentalFeature/enablement/set";
83    pub const MCPSERVER_OAUTH_LOGIN: &str = "mcpServer/oauth/login";
84    pub const CONFIG_MCPSERVER_RELOAD: &str = "config/mcpServer/reload";
85    pub const MCPSERVERSTATUS_LIST: &str = "mcpServerStatus/list";
86    pub const MCPSERVER_RESOURCE_READ: &str = "mcpServer/resource/read";
87    pub const MCPSERVER_TOOL_CALL: &str = "mcpServer/tool/call";
88    pub const WINDOWSSANDBOX_SETUPSTART: &str = "windowsSandbox/setupStart";
89    pub const WINDOWSSANDBOX_READINESS: &str = "windowsSandbox/readiness";
90    pub const ACCOUNT_LOGIN_START: &str = "account/login/start";
91    pub const ACCOUNT_LOGIN_CANCEL: &str = "account/login/cancel";
92    pub const ACCOUNT_LOGOUT: &str = "account/logout";
93    pub const ACCOUNT_RATELIMITS_READ: &str = "account/rateLimits/read";
94    pub const ACCOUNT_SENDADDCREDITSNUDGEEMAIL: &str = "account/sendAddCreditsNudgeEmail";
95    pub const FEEDBACK_UPLOAD: &str = "feedback/upload";
96    pub const COMMAND_EXEC: &str = "command/exec";
97    pub const COMMAND_EXEC_WRITE: &str = "command/exec/write";
98    pub const COMMAND_EXEC_TERMINATE: &str = "command/exec/terminate";
99    pub const COMMAND_EXEC_RESIZE: &str = "command/exec/resize";
100    pub const CONFIG_READ: &str = "config/read";
101    pub const EXTERNALAGENTCONFIG_DETECT: &str = "externalAgentConfig/detect";
102    pub const EXTERNALAGENTCONFIG_IMPORT: &str = "externalAgentConfig/import";
103    pub const CONFIG_VALUE_WRITE: &str = "config/value/write";
104    pub const CONFIG_BATCHWRITE: &str = "config/batchWrite";
105    pub const CONFIGREQUIREMENTS_READ: &str = "configRequirements/read";
106    pub const ACCOUNT_READ: &str = "account/read";
107    pub const FUZZYFILESEARCH: &str = "fuzzyFileSearch";
108    pub const ACCOUNT_USAGE_READ: &str = "account/usage/read";
109    pub const PERMISSION_PROFILE_LIST: &str = "permissionProfile/list";
110    pub const PLUGIN_INSTALLED: &str = "plugin/installed";
111    pub const SKILLS_EXTRA_ROOTS_SET: &str = "skills/extraRoots/set";
112    pub const THREAD_GOAL_GET: &str = "thread/goal/get";
113    pub const THREAD_GOAL_SET: &str = "thread/goal/set";
114    pub const THREAD_GOAL_CLEAR: &str = "thread/goal/clear";
115    pub const ACCOUNT_RATELIMITRESETCREDIT_CONSUME: &str = "account/rateLimitResetCredit/consume";
116    pub const ACCOUNT_WORKSPACEMESSAGES_READ: &str = "account/workspaceMessages/read";
117    pub const EXTERNALAGENTCONFIG_IMPORT_READHISTORIES: &str =
118        "externalAgentConfig/import/readHistories";
119
120    // Server → client notifications
121    pub const THREAD_STARTED: &str = "thread/started";
122    pub const THREAD_STATUS_CHANGED: &str = "thread/status/changed";
123    pub const THREAD_TOKEN_USAGE_UPDATED: &str = "thread/tokenUsage/updated";
124    pub const TURN_STARTED: &str = "turn/started";
125    pub const TURN_COMPLETED: &str = "turn/completed";
126    pub const ITEM_STARTED: &str = "item/started";
127    pub const ITEM_COMPLETED: &str = "item/completed";
128    pub const AGENT_MESSAGE_DELTA: &str = "item/agentMessage/delta";
129    pub const CMD_OUTPUT_DELTA: &str = "item/commandExecution/outputDelta";
130    pub const FILE_CHANGE_OUTPUT_DELTA: &str = "item/fileChange/outputDelta";
131    pub const REASONING_DELTA: &str = "item/reasoning/summaryTextDelta";
132    pub const ERROR: &str = "error";
133    pub const ACCOUNT_RATE_LIMITS_UPDATED: &str = "account/rateLimits/updated";
134    pub const MCP_SERVER_STARTUP_STATUS_UPDATED: &str = "mcpServer/startupStatus/updated";
135    pub const MCP_SERVER_OAUTH_LOGIN_COMPLETED: &str = "mcpServer/oauthLogin/completed";
136    pub const REMOTE_CONTROL_STATUS_CHANGED: &str = "remoteControl/status/changed";
137    pub const FILE_CHANGE_PATCH_UPDATED: &str = "item/fileChange/patchUpdated";
138    pub const PLAN_DELTA: &str = "item/plan/delta";
139    pub const TURN_PLAN_UPDATED: &str = "turn/plan/updated";
140    pub const TURN_DIFF_UPDATED: &str = "turn/diff/updated";
141    pub const REASONING_SUMMARY_PART_ADDED: &str = "item/reasoning/summaryPartAdded";
142    pub const REASONING_TEXT_DELTA: &str = "item/reasoning/textDelta";
143    pub const ACCOUNT_LOGIN_COMPLETED: &str = "account/login/completed";
144    pub const DEPRECATION_NOTICE: &str = "deprecationNotice";
145    pub const GUARDIAN_WARNING: &str = "guardianWarning";
146    pub const WARNING: &str = "warning";
147    pub const THREAD_ARCHIVED: &str = "thread/archived";
148    pub const THREAD_CLOSED: &str = "thread/closed";
149    pub const THREAD_DELETED: &str = "thread/deleted";
150    pub const THREAD_UNARCHIVED: &str = "thread/unarchived";
151    pub const THREAD_GOAL_CLEARED: &str = "thread/goal/cleared";
152    pub const THREAD_NAME_UPDATED: &str = "thread/name/updated";
153    pub const SKILLS_CHANGED: &str = "skills/changed";
154    pub const FS_CHANGED: &str = "fs/changed";
155    pub const CONFIG_WARNING: &str = "configWarning";
156    pub const ACCOUNT_UPDATED: &str = "account/updated";
157    pub const APP_LIST_UPDATED: &str = "app/list/updated";
158    pub const COMMAND_EXEC_OUTPUT_DELTA: &str = "command/exec/outputDelta";
159    pub const EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED: &str = "externalAgentConfig/import/completed";
160    pub const FUZZY_FILE_SEARCH_SESSION_COMPLETED: &str = "fuzzyFileSearch/sessionCompleted";
161    pub const FUZZY_FILE_SEARCH_SESSION_UPDATED: &str = "fuzzyFileSearch/sessionUpdated";
162    pub const HOOK_COMPLETED: &str = "hook/completed";
163    pub const HOOK_STARTED: &str = "hook/started";
164    pub const ITEM_AUTO_APPROVAL_REVIEW_COMPLETED: &str = "item/autoApprovalReview/completed";
165    pub const ITEM_AUTO_APPROVAL_REVIEW_STARTED: &str = "item/autoApprovalReview/started";
166    pub const ITEM_COMMAND_EXEC_TERMINAL_INTERACTION: &str =
167        "item/commandExecution/terminalInteraction";
168    pub const ITEM_MCP_TOOL_CALL_PROGRESS: &str = "item/mcpToolCall/progress";
169    pub const MODEL_REROUTED: &str = "model/rerouted";
170    pub const MODEL_VERIFICATION: &str = "model/verification";
171    pub const PROCESS_EXITED: &str = "process/exited";
172    pub const PROCESS_OUTPUT_DELTA: &str = "process/outputDelta";
173    pub const SERVER_REQUEST_RESOLVED: &str = "serverRequest/resolved";
174    pub const THREAD_COMPACTED: &str = "thread/compacted";
175    pub const THREAD_GOAL_UPDATED: &str = "thread/goal/updated";
176    pub const THREAD_REALTIME_CLOSED: &str = "thread/realtime/closed";
177    pub const THREAD_REALTIME_ERROR: &str = "thread/realtime/error";
178    pub const THREAD_REALTIME_ITEM_ADDED: &str = "thread/realtime/itemAdded";
179    pub const THREAD_REALTIME_OUTPUT_AUDIO_DELTA: &str = "thread/realtime/outputAudio/delta";
180    pub const THREAD_REALTIME_SDP: &str = "thread/realtime/sdp";
181    pub const THREAD_REALTIME_STARTED: &str = "thread/realtime/started";
182    pub const THREAD_REALTIME_TRANSCRIPT_DELTA: &str = "thread/realtime/transcript/delta";
183    pub const THREAD_REALTIME_TRANSCRIPT_DONE: &str = "thread/realtime/transcript/done";
184    pub const WINDOWS_WORLD_WRITABLE_WARNING: &str = "windows/worldWritableWarning";
185    pub const WINDOWS_SANDBOX_SETUP_COMPLETED: &str = "windowsSandbox/setupCompleted";
186    pub const THREAD_SETTINGS_UPDATED: &str = "thread/settings/updated";
187    pub const TURN_MODERATION_METADATA: &str = "turn/moderationMetadata";
188    pub const EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS: &str = "externalAgentConfig/import/progress";
189    pub const MODEL_SAFETY_BUFFERING_UPDATED: &str = "model/safetyBuffering/updated";
190    pub const THREAD_ENVIRONMENT_CONNECTED: &str = "thread/environment/connected";
191    pub const THREAD_ENVIRONMENT_DISCONNECTED: &str = "thread/environment/disconnected";
192
193    // Server → client requests (approval flow, v2 envelope)
194    pub const CMD_EXEC_APPROVAL: &str = "item/commandExecution/requestApproval";
195    pub const FILE_CHANGE_APPROVAL: &str = "item/fileChange/requestApproval";
196    pub const TOOL_REQUEST_USER_INPUT: &str = "item/tool/requestUserInput";
197    pub const MCP_SERVER_ELICITATION_REQUEST: &str = "mcpServer/elicitation/request";
198    pub const PERMISSIONS_REQUEST_APPROVAL: &str = "item/permissions/requestApproval";
199    pub const ITEM_TOOL_CALL: &str = "item/tool/call";
200    pub const CHATGPT_AUTH_TOKENS_REFRESH: &str = "account/chatgptAuthTokens/refresh";
201    pub const ATTESTATION_GENERATE: &str = "attestation/generate";
202    pub const APPLY_PATCH_APPROVAL: &str = "applyPatchApproval";
203    pub const EXEC_COMMAND_APPROVAL: &str = "execCommandApproval";
204}
205
206// ──────────────────────────────────────────────────────────────────────────
207// Ergonomic constructors over the generated wire types.
208//
209// The types themselves are code-generated from the upstream schema; these
210// hand-written impls live here so they survive regeneration. They cover two
211// pain points for downstream consumers:
212//
213//   * `Default` for the all-optional client request params, so callers don't
214//     have to spell out every `None` field or construct via `from_value`.
215//   * `accept` / `decline` / `approved` / `denied` constructors for the
216//     approval-response payloads, so callers don't hand-roll `serde_json`
217//     objects and can't typo the wire `decision` string.
218// ──────────────────────────────────────────────────────────────────────────
219
220macro_rules! default_from_empty_object {
221    ($($ty:ident),+ $(,)?) => {
222        $(
223            impl Default for $ty {
224                fn default() -> Self {
225                    // Every field is `#[serde(default)]`, so an empty object
226                    // yields the fully-unset params. Deserializing (rather than
227                    // listing fields) keeps this correct as the upstream schema
228                    // adds optional fields, and mirrors the construction idiom
229                    // shown in the crate docs.
230                    serde_json::from_value(serde_json::Value::Object(Default::default()))
231                        .expect(concat!(
232                            stringify!($ty),
233                            ": every field is serde-default, so `{}` must deserialize"
234                        ))
235                }
236            }
237        )+
238    };
239}
240
241default_from_empty_object!(
242    ThreadStartParams,
243    TurnStartParams,
244    ThreadResumeParams,
245    ThreadForkParams,
246);
247
248impl FileChangeRequestApprovalResponse {
249    /// Approve this file-change request (`{"decision":"accept"}`).
250    pub fn accept() -> Self {
251        Self {
252            decision: FileChangeApprovalDecision::Accept,
253        }
254    }
255
256    /// Approve this and future file changes for the session.
257    pub fn accept_for_session() -> Self {
258        Self {
259            decision: FileChangeApprovalDecision::AcceptForSession,
260        }
261    }
262
263    /// Decline this file-change request (`{"decision":"decline"}`).
264    pub fn decline() -> Self {
265        Self {
266            decision: FileChangeApprovalDecision::Decline,
267        }
268    }
269
270    /// Cancel the turn in response to this request.
271    pub fn cancel() -> Self {
272        Self {
273            decision: FileChangeApprovalDecision::Cancel,
274        }
275    }
276}
277
278impl CommandExecutionRequestApprovalResponse {
279    /// Approve this command execution (`{"decision":"accept"}`).
280    pub fn accept() -> Self {
281        Self {
282            decision: CommandExecutionApprovalDecision::Accept,
283        }
284    }
285
286    /// Approve this and future command executions for the session.
287    pub fn accept_for_session() -> Self {
288        Self {
289            decision: CommandExecutionApprovalDecision::AcceptForSession,
290        }
291    }
292
293    /// Decline this command execution (`{"decision":"decline"}`).
294    pub fn decline() -> Self {
295        Self {
296            decision: CommandExecutionApprovalDecision::Decline,
297        }
298    }
299
300    /// Cancel the turn in response to this request.
301    pub fn cancel() -> Self {
302        Self {
303            decision: CommandExecutionApprovalDecision::Cancel,
304        }
305    }
306}
307
308impl ExecCommandApprovalResponse {
309    /// Approve the exec command (`{"decision":"approved"}`).
310    pub fn approved() -> Self {
311        Self {
312            decision: ReviewDecision::Approved,
313        }
314    }
315
316    /// Approve the exec command for the rest of the session.
317    pub fn approved_for_session() -> Self {
318        Self {
319            decision: ReviewDecision::ApprovedForSession,
320        }
321    }
322
323    /// Deny the exec command (`{"decision":"denied"}`).
324    pub fn denied() -> Self {
325        Self {
326            decision: ReviewDecision::Denied,
327        }
328    }
329
330    /// Abort the turn in response to the request.
331    pub fn abort() -> Self {
332        Self {
333            decision: ReviewDecision::Abort,
334        }
335    }
336}
337
338impl ApplyPatchApprovalResponse {
339    /// Approve the patch (`{"decision":"approved"}`).
340    pub fn approved() -> Self {
341        Self {
342            decision: ReviewDecision::Approved,
343        }
344    }
345
346    /// Approve this and future patches for the session.
347    pub fn approved_for_session() -> Self {
348        Self {
349            decision: ReviewDecision::ApprovedForSession,
350        }
351    }
352
353    /// Deny the patch (`{"decision":"denied"}`).
354    pub fn denied() -> Self {
355        Self {
356            decision: ReviewDecision::Denied,
357        }
358    }
359
360    /// Abort the turn in response to the request.
361    pub fn abort() -> Self {
362        Self {
363            decision: ReviewDecision::Abort,
364        }
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    #[test]
373    fn thread_start_params_default_is_empty_object() {
374        let p = ThreadStartParams::default();
375        assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!({}));
376    }
377
378    #[test]
379    fn turn_start_params_default_round_trips() {
380        let p = TurnStartParams::default();
381        let v = serde_json::to_value(&p).unwrap();
382        // thread_id + input are required-but-defaulted; everything else omits.
383        assert_eq!(v["threadId"], "");
384        assert_eq!(v["input"], serde_json::json!([]));
385    }
386
387    #[test]
388    fn thread_resume_and_fork_params_default() {
389        let _ = ThreadResumeParams::default();
390        let _ = ThreadForkParams::default();
391    }
392
393    #[test]
394    fn file_change_approval_response_wire_shape() {
395        assert_eq!(
396            serde_json::to_value(FileChangeRequestApprovalResponse::accept()).unwrap(),
397            serde_json::json!({"decision": "accept"})
398        );
399        assert_eq!(
400            serde_json::to_value(FileChangeRequestApprovalResponse::decline()).unwrap(),
401            serde_json::json!({"decision": "decline"})
402        );
403    }
404
405    #[test]
406    fn command_execution_approval_response_wire_shape() {
407        assert_eq!(
408            serde_json::to_value(CommandExecutionRequestApprovalResponse::accept()).unwrap(),
409            serde_json::json!({"decision": "accept"})
410        );
411        assert_eq!(
412            serde_json::to_value(CommandExecutionRequestApprovalResponse::cancel()).unwrap(),
413            serde_json::json!({"decision": "cancel"})
414        );
415    }
416
417    #[test]
418    fn exec_and_apply_patch_approval_response_wire_shape() {
419        assert_eq!(
420            serde_json::to_value(ExecCommandApprovalResponse::approved()).unwrap(),
421            serde_json::json!({"decision": "approved"})
422        );
423        assert_eq!(
424            serde_json::to_value(ApplyPatchApprovalResponse::denied()).unwrap(),
425            serde_json::json!({"decision": "denied"})
426        );
427    }
428}