Skip to main content

codex_codes/
messages.rs

1//! Typed dispatch for app-server notifications and server-to-client requests.
2//!
3//! The Codex app-server speaks JSON-RPC where every message carries a
4//! `method` discriminant alongside a free-form `params` blob. This module
5//! lifts that loose envelope into closed enums — [`Notification`] for
6//! server-initiated notifications and [`ServerRequest`] for server-initiated
7//! requests (the approval flow). Each variant wraps a typed param struct
8//! from [`crate::protocol`].
9//!
10//! The pattern mirrors the [`ContentBlock`] dispatch in the sibling
11//! `claude-codes` crate: hand-written [`Serialize`]/[`Deserialize`] impls
12//! inspect the discriminant, route known cases through `serde_json::from_value`
13//! into the typed struct, and route unknown methods into an `Unknown`
14//! variant — preserving the raw payload for forward compatibility with
15//! future codex versions.
16//!
17//! ## Typing contract
18//!
19//! - Unknown methods route to [`Notification::Unknown`] / [`ServerRequest::Unknown`]
20//!   without error. Encountering one in production typically means the
21//!   installed Codex CLI is newer than the bindings.
22//! - Known methods whose payload fails to deserialize **do** cause an error.
23//!   If you see one, the typed binding in [`crate::protocol`] is out of
24//!   sync with the wire format and needs to be updated.
25
26use crate::error::{Error, ParseError};
27use crate::jsonrpc::{JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, RequestId};
28use crate::protocol::{
29    methods, AccountLoginCompletedNotification, AccountRateLimitsUpdatedNotification,
30    AccountUpdatedNotification, AgentMessageDeltaNotification, AppListUpdatedNotification,
31    AuthRecoveryNotification, CommandExecOutputDeltaNotification,
32    CommandExecutionOutputDeltaNotification, CommandExecutionRequestApprovalParams,
33    ConfigWarningNotification, ContextCompactedNotification, DeprecationNoticeNotification,
34    EnvironmentConnectionNotification, ErrorNotification,
35    ExternalAgentConfigImportCompletedNotification, ExternalAgentConfigImportProgressNotification,
36    FileChangeOutputDeltaNotification, FileChangePatchUpdatedNotification,
37    FileChangeRequestApprovalParams, FsChangedNotification,
38    FuzzyFileSearchSessionCompletedNotification, FuzzyFileSearchSessionUpdatedNotification,
39    GatewayOAuthChangedNotification, GuardianWarningNotification, HookCompletedNotification,
40    HookStartedNotification, ItemCompletedNotification,
41    ItemGuardianApprovalReviewCompletedNotification, ItemGuardianApprovalReviewStartedNotification,
42    ItemStartedNotification, McpServerEventStreamNotification,
43    McpServerOauthLoginCompletedNotification, McpServerStatusUpdatedNotification,
44    McpToolCallProgressNotification, ModelReroutedNotification,
45    ModelSafetyBufferingUpdatedNotification, ModelVerificationNotification, PlanDeltaNotification,
46    ProcessExitedNotification, ProcessOutputDeltaNotification, ProjectChangedNotification,
47    ReasoningSummaryPartAddedNotification, ReasoningSummaryTextDeltaNotification,
48    ReasoningTextDeltaNotification, RemoteControlStatusChangedNotification,
49    ServerRequestResolvedNotification, SkillsChangedNotification, StrictReviewRequiredNotification,
50    TerminalInteractionNotification, ThreadArchivedNotification,
51    ThreadAttachmentUpdatedNotification, ThreadClosedNotification, ThreadDeletedNotification,
52    ThreadGoalClearedNotification, ThreadGoalUpdatedNotification, ThreadNameUpdatedNotification,
53    ThreadPredictionUpdatedNotification, ThreadProjectUpdatedNotification,
54    ThreadQueueChangedNotification, ThreadRealtimeClosedNotification,
55    ThreadRealtimeErrorNotification, ThreadRealtimeItemAddedNotification,
56    ThreadRealtimeItemCompletedNotification, ThreadRealtimeItemStartedNotification,
57    ThreadRealtimeItemTranscriptDeltaNotification, ThreadRealtimeOutputAudioDeltaNotification,
58    ThreadRealtimeSdpNotification, ThreadRealtimeStartedNotification,
59    ThreadRealtimeTranscriptDeltaNotification, ThreadRealtimeTranscriptDoneNotification,
60    ThreadRevertedNotification, ThreadSettingsUpdatedNotification, ThreadStartedNotification,
61    ThreadStatusChangedNotification, ThreadTokenUsageUpdatedNotification,
62    ThreadUnarchivedNotification, TurnCompletedNotification, TurnDiffUpdatedNotification,
63    TurnModerationMetadataNotification, TurnPlanUpdatedNotification, TurnStartedNotification,
64    WarningNotification, WindowsSandboxSetupCompletedNotification,
65    WindowsWorldWritableWarningNotification,
66};
67use serde::{Deserialize, Deserializer, Serialize, Serializer};
68use serde_json::Value;
69
70/// A server-to-client notification.
71///
72/// Each variant maps to a single `method` string on the wire. The `Unknown`
73/// variant captures methods this crate version doesn't model yet, preserving
74/// the raw payload for inspection.
75#[derive(Debug, Clone)]
76#[allow(clippy::large_enum_variant)] // transient wire values, not stored in bulk
77pub enum Notification {
78    /// `thread/started`
79    ThreadStarted(ThreadStartedNotification),
80    /// `thread/status/changed`
81    ThreadStatusChanged(ThreadStatusChangedNotification),
82    /// `thread/tokenUsage/updated`
83    ThreadTokenUsageUpdated(ThreadTokenUsageUpdatedNotification),
84    /// `turn/started`
85    TurnStarted(TurnStartedNotification),
86    /// `turn/completed`
87    TurnCompleted(TurnCompletedNotification),
88    /// `item/started`
89    ItemStarted(ItemStartedNotification),
90    /// `item/completed`
91    ItemCompleted(ItemCompletedNotification),
92    /// `item/agentMessage/delta`
93    AgentMessageDelta(AgentMessageDeltaNotification),
94    /// `item/commandExecution/outputDelta`
95    CmdOutputDelta(CommandExecutionOutputDeltaNotification),
96    /// `item/fileChange/outputDelta`
97    FileChangeOutputDelta(FileChangeOutputDeltaNotification),
98    /// `item/reasoning/summaryTextDelta`
99    ReasoningDelta(ReasoningSummaryTextDeltaNotification),
100    /// `error`
101    Error(ErrorNotification),
102    /// `account/rateLimits/updated`
103    AccountRateLimitsUpdated(AccountRateLimitsUpdatedNotification),
104    /// `mcpServer/startupStatus/updated`
105    McpServerStartupStatusUpdated(McpServerStatusUpdatedNotification),
106    /// `remoteControl/status/changed`
107    RemoteControlStatusChanged(RemoteControlStatusChangedNotification),
108    /// `mcpServer/oauthLogin/completed`
109    McpServerOauthLoginCompleted(McpServerOauthLoginCompletedNotification),
110    /// `item/fileChange/patchUpdated`
111    FileChangePatchUpdated(FileChangePatchUpdatedNotification),
112    /// `item/plan/delta` (EXPERIMENTAL)
113    PlanDelta(PlanDeltaNotification),
114    /// `turn/plan/updated`
115    TurnPlanUpdated(TurnPlanUpdatedNotification),
116    /// `turn/diff/updated`
117    TurnDiffUpdated(TurnDiffUpdatedNotification),
118    /// `item/reasoning/summaryPartAdded`
119    ReasoningSummaryPartAdded(ReasoningSummaryPartAddedNotification),
120    /// `item/reasoning/textDelta`
121    ReasoningTextDelta(ReasoningTextDeltaNotification),
122    /// `account/login/completed`
123    AccountLoginCompleted(AccountLoginCompletedNotification),
124    /// `deprecationNotice`
125    DeprecationNotice(DeprecationNoticeNotification),
126    /// `guardianWarning`
127    GuardianWarning(GuardianWarningNotification),
128    /// `warning`
129    Warning(WarningNotification),
130    /// `thread/archived`
131    ThreadArchived(ThreadArchivedNotification),
132    /// `thread/closed`
133    ThreadClosed(ThreadClosedNotification),
134    /// `thread/deleted`
135    ThreadDeleted(ThreadDeletedNotification),
136    /// `thread/unarchived`
137    ThreadUnarchived(ThreadUnarchivedNotification),
138    /// `thread/goal/cleared`
139    ThreadGoalCleared(ThreadGoalClearedNotification),
140    /// `thread/name/updated`
141    ThreadNameUpdated(ThreadNameUpdatedNotification),
142    /// `thread/attachment/updated`
143    ThreadAttachmentUpdated(ThreadAttachmentUpdatedNotification),
144    /// `skills/changed`
145    SkillsChanged(SkillsChangedNotification),
146    /// `fs/changed`
147    FsChanged(FsChangedNotification),
148    /// `configWarning`
149    ConfigWarning(ConfigWarningNotification),
150    /// `account/updated`
151    AccountUpdated(AccountUpdatedNotification),
152    /// `account/gatewayOAuth/changed`
153    GatewayOAuthChanged(GatewayOAuthChangedNotification),
154    /// `app/list/updated`
155    AppListUpdated(AppListUpdatedNotification),
156    /// `command/exec/outputDelta`
157    CommandExecOutputDelta(CommandExecOutputDeltaNotification),
158    /// `externalAgentConfig/import/completed`
159    ExternalAgentConfigImportCompleted(ExternalAgentConfigImportCompletedNotification),
160    /// `fuzzyFileSearch/sessionCompleted`
161    FuzzyFileSearchSessionCompleted(FuzzyFileSearchSessionCompletedNotification),
162    /// `fuzzyFileSearch/sessionUpdated`
163    FuzzyFileSearchSessionUpdated(FuzzyFileSearchSessionUpdatedNotification),
164    /// `hook/completed`
165    HookCompleted(HookCompletedNotification),
166    /// `hook/started`
167    HookStarted(HookStartedNotification),
168    /// `item/autoApprovalReview/completed`
169    ItemGuardianApprovalReviewCompleted(ItemGuardianApprovalReviewCompletedNotification),
170    /// `item/autoApprovalReview/started`
171    ItemGuardianApprovalReviewStarted(ItemGuardianApprovalReviewStartedNotification),
172    /// `item/commandExecution/terminalInteraction`
173    TerminalInteraction(TerminalInteractionNotification),
174    /// `item/mcpToolCall/progress`
175    McpToolCallProgress(McpToolCallProgressNotification),
176    /// `model/rerouted`
177    ModelRerouted(ModelReroutedNotification),
178    /// `model/verification`
179    ModelVerification(ModelVerificationNotification),
180    /// `process/exited`
181    ProcessExited(ProcessExitedNotification),
182    /// `process/outputDelta`
183    ProcessOutputDelta(ProcessOutputDeltaNotification),
184    /// `serverRequest/resolved`
185    ServerRequestResolved(ServerRequestResolvedNotification),
186    /// `thread/compacted`
187    ContextCompacted(ContextCompactedNotification),
188    /// `thread/goal/updated`
189    ThreadGoalUpdated(ThreadGoalUpdatedNotification),
190    /// `thread/realtime/closed`
191    ThreadRealtimeClosed(ThreadRealtimeClosedNotification),
192    /// `thread/realtime/error`
193    ThreadRealtimeError(ThreadRealtimeErrorNotification),
194    /// `thread/realtime/itemAdded`
195    ThreadRealtimeItemAdded(ThreadRealtimeItemAddedNotification),
196    /// `thread/realtime/outputAudio/delta`
197    ThreadRealtimeOutputAudioDelta(ThreadRealtimeOutputAudioDeltaNotification),
198    /// `thread/realtime/sdp`
199    ThreadRealtimeSdp(ThreadRealtimeSdpNotification),
200    /// `thread/realtime/started`
201    ThreadRealtimeStarted(ThreadRealtimeStartedNotification),
202    /// `thread/realtime/transcript/delta`
203    ThreadRealtimeTranscriptDelta(ThreadRealtimeTranscriptDeltaNotification),
204    /// `thread/realtime/transcript/done`
205    ThreadRealtimeTranscriptDone(ThreadRealtimeTranscriptDoneNotification),
206    /// `windows/worldWritableWarning`
207    WindowsWorldWritableWarning(WindowsWorldWritableWarningNotification),
208    /// `windowsSandbox/setupCompleted`
209    WindowsSandboxSetupCompleted(WindowsSandboxSetupCompletedNotification),
210    /// `thread/settings/updated`
211    ThreadSettingsUpdated(ThreadSettingsUpdatedNotification),
212    /// `turn/moderationMetadata`
213    TurnModerationMetadata(TurnModerationMetadataNotification),
214    /// `externalAgentConfig/import/progress`
215    ExternalAgentConfigImportProgress(ExternalAgentConfigImportProgressNotification),
216    /// `model/safetyBuffering/updated`
217    ModelSafetyBufferingUpdated(ModelSafetyBufferingUpdatedNotification),
218    /// `thread/environment/connected`
219    ThreadEnvironmentConnected(EnvironmentConnectionNotification),
220    /// `thread/environment/disconnected`
221    ThreadEnvironmentDisconnected(EnvironmentConnectionNotification),
222    /// `autoApprovalReview/strictReviewRequired` (0.147)
223    StrictReviewRequired(StrictReviewRequiredNotification),
224    /// `project/changed` (0.147)
225    ProjectChanged(ProjectChangedNotification),
226    /// `thread/project/updated` (0.147)
227    ThreadProjectUpdated(ThreadProjectUpdatedNotification),
228    /// `thread/queue/changed` (0.147)
229    ThreadQueueChanged(ThreadQueueChangedNotification),
230    /// `thread/reverted` (0.147)
231    ThreadReverted(ThreadRevertedNotification),
232    /// `mcpServer/event/stream/notification` (0.148 upstream)
233    McpServerEventStream(McpServerEventStreamNotification),
234    /// `thread/realtime/item/started` (0.148 upstream, experimental)
235    ThreadRealtimeItemStarted(ThreadRealtimeItemStartedNotification),
236    /// `thread/realtime/item/completed` (0.148 upstream, experimental)
237    ThreadRealtimeItemCompleted(ThreadRealtimeItemCompletedNotification),
238    /// `thread/realtime/item/transcript/delta` (0.148 upstream, experimental)
239    ThreadRealtimeItemTranscriptDelta(ThreadRealtimeItemTranscriptDeltaNotification),
240    /// `modelProvider/authRecoveryStarted` (0.148 upstream)
241    ModelProviderAuthRecoveryStarted(AuthRecoveryNotification),
242    /// `modelProvider/authRecoveryCompleted` (0.148 upstream)
243    ModelProviderAuthRecoveryCompleted(AuthRecoveryNotification),
244    /// `thread/prediction/updated` (0.159 upstream, experimental)
245    ThreadPredictionUpdated(ThreadPredictionUpdatedNotification),
246    /// A method this crate version does not yet model. The raw params are
247    /// preserved for caller inspection. Encountering this typically means
248    /// the installed codex CLI is newer than the bindings.
249    Unknown {
250        method: String,
251        params: Option<Value>,
252    },
253}
254
255impl Notification {
256    /// Return the wire `method` string for this notification.
257    pub fn method(&self) -> &str {
258        match self {
259            Self::ThreadStarted(_) => methods::THREAD_STARTED,
260            Self::StrictReviewRequired(_) => methods::STRICT_REVIEW_REQUIRED,
261            Self::ProjectChanged(_) => methods::PROJECT_CHANGED,
262            Self::ThreadProjectUpdated(_) => methods::THREAD_PROJECT_UPDATED,
263            Self::ThreadQueueChanged(_) => methods::THREAD_QUEUE_CHANGED,
264            Self::ThreadReverted(_) => methods::THREAD_REVERTED,
265            Self::ThreadPredictionUpdated(_) => methods::THREAD_PREDICTION_UPDATED,
266            Self::McpServerEventStream(_) => methods::MCP_SERVER_EVENT_STREAM,
267            Self::ThreadRealtimeItemStarted(_) => methods::THREAD_REALTIME_ITEM_STARTED,
268            Self::ThreadRealtimeItemCompleted(_) => methods::THREAD_REALTIME_ITEM_COMPLETED,
269            Self::ThreadRealtimeItemTranscriptDelta(_) => {
270                methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA
271            }
272            Self::ModelProviderAuthRecoveryStarted(_) => {
273                methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED
274            }
275            Self::ModelProviderAuthRecoveryCompleted(_) => {
276                methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED
277            }
278            Self::ThreadStatusChanged(_) => methods::THREAD_STATUS_CHANGED,
279            Self::ThreadTokenUsageUpdated(_) => methods::THREAD_TOKEN_USAGE_UPDATED,
280            Self::TurnStarted(_) => methods::TURN_STARTED,
281            Self::TurnCompleted(_) => methods::TURN_COMPLETED,
282            Self::ItemStarted(_) => methods::ITEM_STARTED,
283            Self::ItemCompleted(_) => methods::ITEM_COMPLETED,
284            Self::AgentMessageDelta(_) => methods::AGENT_MESSAGE_DELTA,
285            Self::CmdOutputDelta(_) => methods::CMD_OUTPUT_DELTA,
286            Self::FileChangeOutputDelta(_) => methods::FILE_CHANGE_OUTPUT_DELTA,
287            Self::ReasoningDelta(_) => methods::REASONING_DELTA,
288            Self::Error(_) => methods::ERROR,
289            Self::AccountRateLimitsUpdated(_) => methods::ACCOUNT_RATE_LIMITS_UPDATED,
290            Self::McpServerStartupStatusUpdated(_) => methods::MCP_SERVER_STARTUP_STATUS_UPDATED,
291            Self::RemoteControlStatusChanged(_) => methods::REMOTE_CONTROL_STATUS_CHANGED,
292            Self::McpServerOauthLoginCompleted(_) => methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED,
293            Self::FileChangePatchUpdated(_) => methods::FILE_CHANGE_PATCH_UPDATED,
294            Self::PlanDelta(_) => methods::PLAN_DELTA,
295            Self::TurnPlanUpdated(_) => methods::TURN_PLAN_UPDATED,
296            Self::TurnDiffUpdated(_) => methods::TURN_DIFF_UPDATED,
297            Self::ReasoningSummaryPartAdded(_) => methods::REASONING_SUMMARY_PART_ADDED,
298            Self::ReasoningTextDelta(_) => methods::REASONING_TEXT_DELTA,
299            Self::AccountLoginCompleted(_) => methods::ACCOUNT_LOGIN_COMPLETED,
300            Self::DeprecationNotice(_) => methods::DEPRECATION_NOTICE,
301            Self::GuardianWarning(_) => methods::GUARDIAN_WARNING,
302            Self::Warning(_) => methods::WARNING,
303            Self::ThreadArchived(_) => methods::THREAD_ARCHIVED,
304            Self::ThreadClosed(_) => methods::THREAD_CLOSED,
305            Self::ThreadDeleted(_) => methods::THREAD_DELETED,
306            Self::ThreadUnarchived(_) => methods::THREAD_UNARCHIVED,
307            Self::ThreadGoalCleared(_) => methods::THREAD_GOAL_CLEARED,
308            Self::ThreadNameUpdated(_) => methods::THREAD_NAME_UPDATED,
309            Self::ThreadAttachmentUpdated(_) => methods::THREAD_ATTACHMENT_UPDATED,
310            Self::SkillsChanged(_) => methods::SKILLS_CHANGED,
311            Self::FsChanged(_) => methods::FS_CHANGED,
312            Self::ConfigWarning(_) => methods::CONFIG_WARNING,
313            Self::AccountUpdated(_) => methods::ACCOUNT_UPDATED,
314            Self::GatewayOAuthChanged(_) => methods::ACCOUNT_GATEWAY_OAUTH_CHANGED,
315            Self::AppListUpdated(_) => methods::APP_LIST_UPDATED,
316            Self::CommandExecOutputDelta(_) => methods::COMMAND_EXEC_OUTPUT_DELTA,
317            Self::ExternalAgentConfigImportCompleted(_) => {
318                methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED
319            }
320            Self::FuzzyFileSearchSessionCompleted(_) => {
321                methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED
322            }
323            Self::FuzzyFileSearchSessionUpdated(_) => methods::FUZZY_FILE_SEARCH_SESSION_UPDATED,
324            Self::HookCompleted(_) => methods::HOOK_COMPLETED,
325            Self::HookStarted(_) => methods::HOOK_STARTED,
326            Self::ItemGuardianApprovalReviewCompleted(_) => {
327                methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED
328            }
329            Self::ItemGuardianApprovalReviewStarted(_) => {
330                methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED
331            }
332            Self::TerminalInteraction(_) => methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION,
333            Self::McpToolCallProgress(_) => methods::ITEM_MCP_TOOL_CALL_PROGRESS,
334            Self::ModelRerouted(_) => methods::MODEL_REROUTED,
335            Self::ModelVerification(_) => methods::MODEL_VERIFICATION,
336            Self::ProcessExited(_) => methods::PROCESS_EXITED,
337            Self::ProcessOutputDelta(_) => methods::PROCESS_OUTPUT_DELTA,
338            Self::ServerRequestResolved(_) => methods::SERVER_REQUEST_RESOLVED,
339            Self::ContextCompacted(_) => methods::THREAD_COMPACTED,
340            Self::ThreadGoalUpdated(_) => methods::THREAD_GOAL_UPDATED,
341            Self::ThreadRealtimeClosed(_) => methods::THREAD_REALTIME_CLOSED,
342            Self::ThreadRealtimeError(_) => methods::THREAD_REALTIME_ERROR,
343            Self::ThreadRealtimeItemAdded(_) => methods::THREAD_REALTIME_ITEM_ADDED,
344            Self::ThreadRealtimeOutputAudioDelta(_) => methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA,
345            Self::ThreadRealtimeSdp(_) => methods::THREAD_REALTIME_SDP,
346            Self::ThreadRealtimeStarted(_) => methods::THREAD_REALTIME_STARTED,
347            Self::ThreadRealtimeTranscriptDelta(_) => methods::THREAD_REALTIME_TRANSCRIPT_DELTA,
348            Self::ThreadRealtimeTranscriptDone(_) => methods::THREAD_REALTIME_TRANSCRIPT_DONE,
349            Self::WindowsWorldWritableWarning(_) => methods::WINDOWS_WORLD_WRITABLE_WARNING,
350            Self::WindowsSandboxSetupCompleted(_) => methods::WINDOWS_SANDBOX_SETUP_COMPLETED,
351            Self::ThreadSettingsUpdated(_) => methods::THREAD_SETTINGS_UPDATED,
352            Self::TurnModerationMetadata(_) => methods::TURN_MODERATION_METADATA,
353            Self::ExternalAgentConfigImportProgress(_) => {
354                methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS
355            }
356            Self::ModelSafetyBufferingUpdated(_) => methods::MODEL_SAFETY_BUFFERING_UPDATED,
357            Self::ThreadEnvironmentConnected(_) => methods::THREAD_ENVIRONMENT_CONNECTED,
358            Self::ThreadEnvironmentDisconnected(_) => methods::THREAD_ENVIRONMENT_DISCONNECTED,
359            Self::Unknown { method, .. } => method,
360        }
361    }
362
363    /// `true` if this notification's method isn't modeled by the crate.
364    pub fn is_unknown(&self) -> bool {
365        matches!(self, Self::Unknown { .. })
366    }
367
368    /// Return the turn id this notification is scoped to, if it carries one.
369    ///
370    /// Reads the typed `turnId` field (or `turn.id` for the turn-lifecycle
371    /// notifications) directly, so callers don't have to round-trip through
372    /// [`into_envelope`](Self::into_envelope) and poke `serde_json::Value`
373    /// fields. Returns `None` for notifications that aren't turn-scoped, and
374    /// treats an empty id the server omitted as absent.
375    ///
376    /// The turn id from `turn/started` is what
377    /// [`turn/interrupt`](crate::AsyncClient::turn_interrupt) needs to cancel
378    /// the active turn.
379    pub fn turn_id(&self) -> Option<&str> {
380        let id = match self {
381            Self::TurnStarted(n) => n.turn.id.as_str(),
382            Self::TurnCompleted(n) => n.turn.id.as_str(),
383            Self::AgentMessageDelta(n) => n.turn_id.as_str(),
384            Self::CmdOutputDelta(n) => n.turn_id.as_str(),
385            Self::FileChangeOutputDelta(n) => n.turn_id.as_str(),
386            Self::ReasoningDelta(n) => n.turn_id.as_str(),
387            Self::Error(n) => n.turn_id.as_str(),
388            Self::FileChangePatchUpdated(n) => n.turn_id.as_str(),
389            Self::PlanDelta(n) => n.turn_id.as_str(),
390            Self::TurnPlanUpdated(n) => n.turn_id.as_str(),
391            Self::TurnDiffUpdated(n) => n.turn_id.as_str(),
392            Self::TurnModerationMetadata(n) => n.turn_id.as_str(),
393            Self::ReasoningSummaryPartAdded(n) => n.turn_id.as_str(),
394            Self::ReasoningTextDelta(n) => n.turn_id.as_str(),
395            Self::ItemStarted(n) => n.turn_id.as_str(),
396            Self::ItemCompleted(n) => n.turn_id.as_str(),
397            Self::ContextCompacted(n) => n.turn_id.as_str(),
398            Self::McpToolCallProgress(n) => n.turn_id.as_str(),
399            Self::ModelRerouted(n) => n.turn_id.as_str(),
400            Self::ModelVerification(n) => n.turn_id.as_str(),
401            Self::ModelSafetyBufferingUpdated(n) => n.turn_id.as_str(),
402            Self::TerminalInteraction(n) => n.turn_id.as_str(),
403            Self::ThreadTokenUsageUpdated(n) => n.turn_id.as_str(),
404            Self::ItemGuardianApprovalReviewStarted(n) => n.turn_id.as_str(),
405            Self::ItemGuardianApprovalReviewCompleted(n) => n.turn_id.as_str(),
406            _ => return None,
407        };
408        (!id.is_empty()).then_some(id)
409    }
410
411    /// Return the typed [`ThreadItem`](crate::protocol::ThreadItem) this
412    /// notification carries, for `item/started` and `item/completed`.
413    ///
414    /// Lets downstream event adapters read the item's typed fields instead of
415    /// reserializing it back into `serde_json::Value`.
416    pub fn thread_item(&self) -> Option<&crate::protocol::ThreadItem> {
417        match self {
418            Self::ItemStarted(n) => Some(&n.item),
419            Self::ItemCompleted(n) => Some(&n.item),
420            _ => None,
421        }
422    }
423
424    /// Construct a [`Notification`] from a `method` + `params` envelope.
425    ///
426    /// Returns an error if `method` is recognized but `params` doesn't
427    /// deserialize into the typed struct. Unknown methods route to
428    /// [`Notification::Unknown`] without error.
429    pub fn from_envelope(method: &str, params: Option<Value>) -> Result<Self, serde_json::Error> {
430        let params_value = params.clone().unwrap_or(Value::Null);
431        match method {
432            methods::THREAD_STARTED => {
433                serde_json::from_value(params_value).map(Self::ThreadStarted)
434            }
435            methods::STRICT_REVIEW_REQUIRED => {
436                serde_json::from_value(params_value).map(Self::StrictReviewRequired)
437            }
438            methods::PROJECT_CHANGED => {
439                serde_json::from_value(params_value).map(Self::ProjectChanged)
440            }
441            methods::THREAD_PROJECT_UPDATED => {
442                serde_json::from_value(params_value).map(Self::ThreadProjectUpdated)
443            }
444            methods::THREAD_QUEUE_CHANGED => {
445                serde_json::from_value(params_value).map(Self::ThreadQueueChanged)
446            }
447            methods::THREAD_REVERTED => {
448                serde_json::from_value(params_value).map(Self::ThreadReverted)
449            }
450            methods::THREAD_PREDICTION_UPDATED => {
451                serde_json::from_value(params_value).map(Self::ThreadPredictionUpdated)
452            }
453            methods::MCP_SERVER_EVENT_STREAM => {
454                serde_json::from_value(params_value).map(Self::McpServerEventStream)
455            }
456            methods::THREAD_REALTIME_ITEM_STARTED => {
457                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemStarted)
458            }
459            methods::THREAD_REALTIME_ITEM_COMPLETED => {
460                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemCompleted)
461            }
462            methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA => {
463                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemTranscriptDelta)
464            }
465            methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED => {
466                serde_json::from_value(params_value).map(Self::ModelProviderAuthRecoveryStarted)
467            }
468            methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED => {
469                serde_json::from_value(params_value).map(Self::ModelProviderAuthRecoveryCompleted)
470            }
471            methods::THREAD_STATUS_CHANGED => {
472                serde_json::from_value(params_value).map(Self::ThreadStatusChanged)
473            }
474            methods::THREAD_TOKEN_USAGE_UPDATED => {
475                serde_json::from_value(params_value).map(Self::ThreadTokenUsageUpdated)
476            }
477            methods::TURN_STARTED => serde_json::from_value(params_value).map(Self::TurnStarted),
478            methods::TURN_COMPLETED => {
479                serde_json::from_value(params_value).map(Self::TurnCompleted)
480            }
481            methods::ITEM_STARTED => serde_json::from_value(params_value).map(Self::ItemStarted),
482            methods::ITEM_COMPLETED => {
483                serde_json::from_value(params_value).map(Self::ItemCompleted)
484            }
485            methods::AGENT_MESSAGE_DELTA => {
486                serde_json::from_value(params_value).map(Self::AgentMessageDelta)
487            }
488            methods::CMD_OUTPUT_DELTA => {
489                serde_json::from_value(params_value).map(Self::CmdOutputDelta)
490            }
491            methods::FILE_CHANGE_OUTPUT_DELTA => {
492                serde_json::from_value(params_value).map(Self::FileChangeOutputDelta)
493            }
494            methods::REASONING_DELTA => {
495                serde_json::from_value(params_value).map(Self::ReasoningDelta)
496            }
497            methods::ERROR => serde_json::from_value(params_value).map(Self::Error),
498            methods::ACCOUNT_RATE_LIMITS_UPDATED => {
499                serde_json::from_value(params_value).map(Self::AccountRateLimitsUpdated)
500            }
501            methods::MCP_SERVER_STARTUP_STATUS_UPDATED => {
502                serde_json::from_value(params_value).map(Self::McpServerStartupStatusUpdated)
503            }
504            methods::REMOTE_CONTROL_STATUS_CHANGED => {
505                serde_json::from_value(params_value).map(Self::RemoteControlStatusChanged)
506            }
507            methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED => {
508                serde_json::from_value(params_value).map(Self::McpServerOauthLoginCompleted)
509            }
510            methods::FILE_CHANGE_PATCH_UPDATED => {
511                serde_json::from_value(params_value).map(Self::FileChangePatchUpdated)
512            }
513            methods::PLAN_DELTA => serde_json::from_value(params_value).map(Self::PlanDelta),
514            methods::TURN_PLAN_UPDATED => {
515                serde_json::from_value(params_value).map(Self::TurnPlanUpdated)
516            }
517            methods::TURN_DIFF_UPDATED => {
518                serde_json::from_value(params_value).map(Self::TurnDiffUpdated)
519            }
520            methods::REASONING_SUMMARY_PART_ADDED => {
521                serde_json::from_value(params_value).map(Self::ReasoningSummaryPartAdded)
522            }
523            methods::REASONING_TEXT_DELTA => {
524                serde_json::from_value(params_value).map(Self::ReasoningTextDelta)
525            }
526            methods::ACCOUNT_LOGIN_COMPLETED => {
527                serde_json::from_value(params_value).map(Self::AccountLoginCompleted)
528            }
529            methods::DEPRECATION_NOTICE => {
530                serde_json::from_value(params_value).map(Self::DeprecationNotice)
531            }
532            methods::GUARDIAN_WARNING => {
533                serde_json::from_value(params_value).map(Self::GuardianWarning)
534            }
535            methods::WARNING => serde_json::from_value(params_value).map(Self::Warning),
536            methods::THREAD_ARCHIVED => {
537                serde_json::from_value(params_value).map(Self::ThreadArchived)
538            }
539            methods::THREAD_CLOSED => serde_json::from_value(params_value).map(Self::ThreadClosed),
540            methods::THREAD_DELETED => {
541                serde_json::from_value(params_value).map(Self::ThreadDeleted)
542            }
543            methods::THREAD_UNARCHIVED => {
544                serde_json::from_value(params_value).map(Self::ThreadUnarchived)
545            }
546            methods::THREAD_GOAL_CLEARED => {
547                serde_json::from_value(params_value).map(Self::ThreadGoalCleared)
548            }
549            methods::THREAD_NAME_UPDATED => {
550                serde_json::from_value(params_value).map(Self::ThreadNameUpdated)
551            }
552            methods::THREAD_ATTACHMENT_UPDATED => {
553                serde_json::from_value(params_value).map(Self::ThreadAttachmentUpdated)
554            }
555            methods::SKILLS_CHANGED => {
556                serde_json::from_value(params_value).map(Self::SkillsChanged)
557            }
558            methods::FS_CHANGED => serde_json::from_value(params_value).map(Self::FsChanged),
559            methods::CONFIG_WARNING => {
560                serde_json::from_value(params_value).map(Self::ConfigWarning)
561            }
562            methods::ACCOUNT_UPDATED => {
563                serde_json::from_value(params_value).map(Self::AccountUpdated)
564            }
565            methods::ACCOUNT_GATEWAY_OAUTH_CHANGED => {
566                serde_json::from_value(params_value).map(Self::GatewayOAuthChanged)
567            }
568            methods::APP_LIST_UPDATED => {
569                serde_json::from_value(params_value).map(Self::AppListUpdated)
570            }
571            methods::COMMAND_EXEC_OUTPUT_DELTA => {
572                serde_json::from_value(params_value).map(Self::CommandExecOutputDelta)
573            }
574            methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED => {
575                serde_json::from_value(params_value).map(Self::ExternalAgentConfigImportCompleted)
576            }
577            methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED => {
578                serde_json::from_value(params_value).map(Self::FuzzyFileSearchSessionCompleted)
579            }
580            methods::FUZZY_FILE_SEARCH_SESSION_UPDATED => {
581                serde_json::from_value(params_value).map(Self::FuzzyFileSearchSessionUpdated)
582            }
583            methods::HOOK_COMPLETED => {
584                serde_json::from_value(params_value).map(Self::HookCompleted)
585            }
586            methods::HOOK_STARTED => serde_json::from_value(params_value).map(Self::HookStarted),
587            methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED => {
588                serde_json::from_value(params_value).map(Self::ItemGuardianApprovalReviewCompleted)
589            }
590            methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED => {
591                serde_json::from_value(params_value).map(Self::ItemGuardianApprovalReviewStarted)
592            }
593            methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION => {
594                serde_json::from_value(params_value).map(Self::TerminalInteraction)
595            }
596            methods::ITEM_MCP_TOOL_CALL_PROGRESS => {
597                serde_json::from_value(params_value).map(Self::McpToolCallProgress)
598            }
599            methods::MODEL_REROUTED => {
600                serde_json::from_value(params_value).map(Self::ModelRerouted)
601            }
602            methods::MODEL_VERIFICATION => {
603                serde_json::from_value(params_value).map(Self::ModelVerification)
604            }
605            methods::PROCESS_EXITED => {
606                serde_json::from_value(params_value).map(Self::ProcessExited)
607            }
608            methods::PROCESS_OUTPUT_DELTA => {
609                serde_json::from_value(params_value).map(Self::ProcessOutputDelta)
610            }
611            methods::SERVER_REQUEST_RESOLVED => {
612                serde_json::from_value(params_value).map(Self::ServerRequestResolved)
613            }
614            methods::THREAD_COMPACTED => {
615                serde_json::from_value(params_value).map(Self::ContextCompacted)
616            }
617            methods::THREAD_GOAL_UPDATED => {
618                serde_json::from_value(params_value).map(Self::ThreadGoalUpdated)
619            }
620            methods::THREAD_REALTIME_CLOSED => {
621                serde_json::from_value(params_value).map(Self::ThreadRealtimeClosed)
622            }
623            methods::THREAD_REALTIME_ERROR => {
624                serde_json::from_value(params_value).map(Self::ThreadRealtimeError)
625            }
626            methods::THREAD_REALTIME_ITEM_ADDED => {
627                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemAdded)
628            }
629            methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA => {
630                serde_json::from_value(params_value).map(Self::ThreadRealtimeOutputAudioDelta)
631            }
632            methods::THREAD_REALTIME_SDP => {
633                serde_json::from_value(params_value).map(Self::ThreadRealtimeSdp)
634            }
635            methods::THREAD_REALTIME_STARTED => {
636                serde_json::from_value(params_value).map(Self::ThreadRealtimeStarted)
637            }
638            methods::THREAD_REALTIME_TRANSCRIPT_DELTA => {
639                serde_json::from_value(params_value).map(Self::ThreadRealtimeTranscriptDelta)
640            }
641            methods::THREAD_REALTIME_TRANSCRIPT_DONE => {
642                serde_json::from_value(params_value).map(Self::ThreadRealtimeTranscriptDone)
643            }
644            methods::WINDOWS_WORLD_WRITABLE_WARNING => {
645                serde_json::from_value(params_value).map(Self::WindowsWorldWritableWarning)
646            }
647            methods::WINDOWS_SANDBOX_SETUP_COMPLETED => {
648                serde_json::from_value(params_value).map(Self::WindowsSandboxSetupCompleted)
649            }
650            methods::THREAD_SETTINGS_UPDATED => {
651                serde_json::from_value(params_value).map(Self::ThreadSettingsUpdated)
652            }
653            methods::TURN_MODERATION_METADATA => {
654                serde_json::from_value(params_value).map(Self::TurnModerationMetadata)
655            }
656            methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS => {
657                serde_json::from_value(params_value).map(Self::ExternalAgentConfigImportProgress)
658            }
659            methods::MODEL_SAFETY_BUFFERING_UPDATED => {
660                serde_json::from_value(params_value).map(Self::ModelSafetyBufferingUpdated)
661            }
662            methods::THREAD_ENVIRONMENT_CONNECTED => {
663                serde_json::from_value(params_value).map(Self::ThreadEnvironmentConnected)
664            }
665            methods::THREAD_ENVIRONMENT_DISCONNECTED => {
666                serde_json::from_value(params_value).map(Self::ThreadEnvironmentDisconnected)
667            }
668            _ => Ok(Self::Unknown {
669                method: method.to_string(),
670                params,
671            }),
672        }
673    }
674
675    /// Decompose this notification back into a `(method, params)` pair.
676    pub fn into_envelope(self) -> Result<(String, Option<Value>), serde_json::Error> {
677        fn pack<T: Serialize>(
678            method: &str,
679            v: &T,
680        ) -> Result<(String, Option<Value>), serde_json::Error> {
681            Ok((method.to_string(), Some(serde_json::to_value(v)?)))
682        }
683        match &self {
684            Self::ThreadStarted(v) => pack(methods::THREAD_STARTED, v),
685            Self::StrictReviewRequired(v) => pack(methods::STRICT_REVIEW_REQUIRED, v),
686            Self::ProjectChanged(v) => pack(methods::PROJECT_CHANGED, v),
687            Self::ThreadProjectUpdated(v) => pack(methods::THREAD_PROJECT_UPDATED, v),
688            Self::ThreadQueueChanged(v) => pack(methods::THREAD_QUEUE_CHANGED, v),
689            Self::ThreadReverted(v) => pack(methods::THREAD_REVERTED, v),
690            Self::ThreadPredictionUpdated(v) => pack(methods::THREAD_PREDICTION_UPDATED, v),
691            Self::McpServerEventStream(v) => pack(methods::MCP_SERVER_EVENT_STREAM, v),
692            Self::ThreadRealtimeItemStarted(v) => pack(methods::THREAD_REALTIME_ITEM_STARTED, v),
693            Self::ThreadRealtimeItemCompleted(v) => {
694                pack(methods::THREAD_REALTIME_ITEM_COMPLETED, v)
695            }
696            Self::ThreadRealtimeItemTranscriptDelta(v) => {
697                pack(methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA, v)
698            }
699            Self::ModelProviderAuthRecoveryStarted(v) => {
700                pack(methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED, v)
701            }
702            Self::ModelProviderAuthRecoveryCompleted(v) => {
703                pack(methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED, v)
704            }
705            Self::ThreadStatusChanged(v) => pack(methods::THREAD_STATUS_CHANGED, v),
706            Self::ThreadTokenUsageUpdated(v) => pack(methods::THREAD_TOKEN_USAGE_UPDATED, v),
707            Self::TurnStarted(v) => pack(methods::TURN_STARTED, v),
708            Self::TurnCompleted(v) => pack(methods::TURN_COMPLETED, v),
709            Self::ItemStarted(v) => pack(methods::ITEM_STARTED, v),
710            Self::ItemCompleted(v) => pack(methods::ITEM_COMPLETED, v),
711            Self::AgentMessageDelta(v) => pack(methods::AGENT_MESSAGE_DELTA, v),
712            Self::CmdOutputDelta(v) => pack(methods::CMD_OUTPUT_DELTA, v),
713            Self::FileChangeOutputDelta(v) => pack(methods::FILE_CHANGE_OUTPUT_DELTA, v),
714            Self::ReasoningDelta(v) => pack(methods::REASONING_DELTA, v),
715            Self::Error(v) => pack(methods::ERROR, v),
716            Self::AccountRateLimitsUpdated(v) => pack(methods::ACCOUNT_RATE_LIMITS_UPDATED, v),
717            Self::McpServerStartupStatusUpdated(v) => {
718                pack(methods::MCP_SERVER_STARTUP_STATUS_UPDATED, v)
719            }
720            Self::RemoteControlStatusChanged(v) => pack(methods::REMOTE_CONTROL_STATUS_CHANGED, v),
721            Self::McpServerOauthLoginCompleted(v) => {
722                pack(methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED, v)
723            }
724            Self::FileChangePatchUpdated(v) => pack(methods::FILE_CHANGE_PATCH_UPDATED, v),
725            Self::PlanDelta(v) => pack(methods::PLAN_DELTA, v),
726            Self::TurnPlanUpdated(v) => pack(methods::TURN_PLAN_UPDATED, v),
727            Self::TurnDiffUpdated(v) => pack(methods::TURN_DIFF_UPDATED, v),
728            Self::ReasoningSummaryPartAdded(v) => pack(methods::REASONING_SUMMARY_PART_ADDED, v),
729            Self::ReasoningTextDelta(v) => pack(methods::REASONING_TEXT_DELTA, v),
730            Self::AccountLoginCompleted(v) => pack(methods::ACCOUNT_LOGIN_COMPLETED, v),
731            Self::DeprecationNotice(v) => pack(methods::DEPRECATION_NOTICE, v),
732            Self::GuardianWarning(v) => pack(methods::GUARDIAN_WARNING, v),
733            Self::Warning(v) => pack(methods::WARNING, v),
734            Self::ThreadArchived(v) => pack(methods::THREAD_ARCHIVED, v),
735            Self::ThreadClosed(v) => pack(methods::THREAD_CLOSED, v),
736            Self::ThreadDeleted(v) => pack(methods::THREAD_DELETED, v),
737            Self::ThreadUnarchived(v) => pack(methods::THREAD_UNARCHIVED, v),
738            Self::ThreadGoalCleared(v) => pack(methods::THREAD_GOAL_CLEARED, v),
739            Self::ThreadNameUpdated(v) => pack(methods::THREAD_NAME_UPDATED, v),
740            Self::ThreadAttachmentUpdated(v) => pack(methods::THREAD_ATTACHMENT_UPDATED, v),
741            Self::SkillsChanged(v) => pack(methods::SKILLS_CHANGED, v),
742            Self::FsChanged(v) => pack(methods::FS_CHANGED, v),
743            Self::ConfigWarning(v) => pack(methods::CONFIG_WARNING, v),
744            Self::AccountUpdated(v) => pack(methods::ACCOUNT_UPDATED, v),
745            Self::GatewayOAuthChanged(v) => pack(methods::ACCOUNT_GATEWAY_OAUTH_CHANGED, v),
746            Self::AppListUpdated(v) => pack(methods::APP_LIST_UPDATED, v),
747            Self::CommandExecOutputDelta(v) => pack(methods::COMMAND_EXEC_OUTPUT_DELTA, v),
748            Self::ExternalAgentConfigImportCompleted(v) => {
749                pack(methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED, v)
750            }
751            Self::FuzzyFileSearchSessionCompleted(v) => {
752                pack(methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED, v)
753            }
754            Self::FuzzyFileSearchSessionUpdated(v) => {
755                pack(methods::FUZZY_FILE_SEARCH_SESSION_UPDATED, v)
756            }
757            Self::HookCompleted(v) => pack(methods::HOOK_COMPLETED, v),
758            Self::HookStarted(v) => pack(methods::HOOK_STARTED, v),
759            Self::ItemGuardianApprovalReviewCompleted(v) => {
760                pack(methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED, v)
761            }
762            Self::ItemGuardianApprovalReviewStarted(v) => {
763                pack(methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED, v)
764            }
765            Self::TerminalInteraction(v) => {
766                pack(methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION, v)
767            }
768            Self::McpToolCallProgress(v) => pack(methods::ITEM_MCP_TOOL_CALL_PROGRESS, v),
769            Self::ModelRerouted(v) => pack(methods::MODEL_REROUTED, v),
770            Self::ModelVerification(v) => pack(methods::MODEL_VERIFICATION, v),
771            Self::ProcessExited(v) => pack(methods::PROCESS_EXITED, v),
772            Self::ProcessOutputDelta(v) => pack(methods::PROCESS_OUTPUT_DELTA, v),
773            Self::ServerRequestResolved(v) => pack(methods::SERVER_REQUEST_RESOLVED, v),
774            Self::ContextCompacted(v) => pack(methods::THREAD_COMPACTED, v),
775            Self::ThreadGoalUpdated(v) => pack(methods::THREAD_GOAL_UPDATED, v),
776            Self::ThreadRealtimeClosed(v) => pack(methods::THREAD_REALTIME_CLOSED, v),
777            Self::ThreadRealtimeError(v) => pack(methods::THREAD_REALTIME_ERROR, v),
778            Self::ThreadRealtimeItemAdded(v) => pack(methods::THREAD_REALTIME_ITEM_ADDED, v),
779            Self::ThreadRealtimeOutputAudioDelta(v) => {
780                pack(methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA, v)
781            }
782            Self::ThreadRealtimeSdp(v) => pack(methods::THREAD_REALTIME_SDP, v),
783            Self::ThreadRealtimeStarted(v) => pack(methods::THREAD_REALTIME_STARTED, v),
784            Self::ThreadRealtimeTranscriptDelta(v) => {
785                pack(methods::THREAD_REALTIME_TRANSCRIPT_DELTA, v)
786            }
787            Self::ThreadRealtimeTranscriptDone(v) => {
788                pack(methods::THREAD_REALTIME_TRANSCRIPT_DONE, v)
789            }
790            Self::WindowsWorldWritableWarning(v) => {
791                pack(methods::WINDOWS_WORLD_WRITABLE_WARNING, v)
792            }
793            Self::WindowsSandboxSetupCompleted(v) => {
794                pack(methods::WINDOWS_SANDBOX_SETUP_COMPLETED, v)
795            }
796            Self::ThreadSettingsUpdated(v) => pack(methods::THREAD_SETTINGS_UPDATED, v),
797            Self::TurnModerationMetadata(v) => pack(methods::TURN_MODERATION_METADATA, v),
798            Self::ExternalAgentConfigImportProgress(v) => {
799                pack(methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS, v)
800            }
801            Self::ModelSafetyBufferingUpdated(v) => {
802                pack(methods::MODEL_SAFETY_BUFFERING_UPDATED, v)
803            }
804            Self::ThreadEnvironmentConnected(v) => pack(methods::THREAD_ENVIRONMENT_CONNECTED, v),
805            Self::ThreadEnvironmentDisconnected(v) => {
806                pack(methods::THREAD_ENVIRONMENT_DISCONNECTED, v)
807            }
808            Self::Unknown { method, params } => Ok((method.clone(), params.clone())),
809        }
810    }
811}
812
813impl Serialize for Notification {
814    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
815        let (method, params) = self
816            .clone()
817            .into_envelope()
818            .map_err(serde::ser::Error::custom)?;
819        let mut env = serde_json::Map::new();
820        env.insert("method".to_string(), Value::String(method));
821        if let Some(p) = params {
822            env.insert("params".to_string(), p);
823        }
824        Value::Object(env).serialize(serializer)
825    }
826}
827
828impl<'de> Deserialize<'de> for Notification {
829    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
830        let value = Value::deserialize(deserializer)?;
831        let method = value
832            .get("method")
833            .and_then(|v| v.as_str())
834            .ok_or_else(|| serde::de::Error::missing_field("method"))?
835            .to_string();
836        let params = value.get("params").cloned();
837        Self::from_envelope(&method, params).map_err(serde::de::Error::custom)
838    }
839}
840
841/// A server-to-client request that requires a response (approval flow).
842///
843/// The wire envelope carries an `id` for response correlation; that `id` is
844/// held alongside this enum in [`ServerMessage::Request`] rather than embedded
845/// inside the variant, since responding doesn't depend on which approval-type
846/// was requested.
847#[derive(Debug, Clone)]
848pub enum ServerRequest {
849    /// `item/commandExecution/requestApproval`
850    CmdExecApproval(CommandExecutionRequestApprovalParams),
851    /// `item/fileChange/requestApproval`
852    FileChangeApproval(FileChangeRequestApprovalParams),
853    /// `item/tool/requestUserInput`
854    ToolRequestUserInput(crate::protocol::ToolRequestUserInputParams),
855    /// `mcpServer/elicitation/request`
856    McpServerElicitationRequest(crate::protocol::McpServerElicitationRequestParams),
857    /// `item/permissions/requestApproval`
858    PermissionsRequestApproval(crate::protocol::PermissionsRequestApprovalParams),
859    /// `item/tool/call`
860    ItemToolCall(crate::protocol::DynamicToolCallParams),
861    /// `account/chatgptAuthTokens/refresh`
862    ChatgptAuthTokensRefresh(crate::protocol::ChatgptAuthTokensRefreshParams),
863    /// `attestation/generate`
864    AttestationGenerate(crate::protocol::AttestationGenerateParams),
865    /// `applyPatchApproval`
866    ApplyPatchApproval(crate::protocol::ApplyPatchApprovalParams),
867    /// `execCommandApproval`
868    ExecCommandApproval(crate::protocol::ExecCommandApprovalParams),
869    /// A request method this crate version does not yet model.
870    Unknown {
871        method: String,
872        params: Option<Value>,
873    },
874}
875
876impl ServerRequest {
877    /// Return the wire `method` string for this request.
878    pub fn method(&self) -> &str {
879        match self {
880            Self::CmdExecApproval(_) => methods::CMD_EXEC_APPROVAL,
881            Self::FileChangeApproval(_) => methods::FILE_CHANGE_APPROVAL,
882            Self::ToolRequestUserInput(_) => methods::TOOL_REQUEST_USER_INPUT,
883            Self::McpServerElicitationRequest(_) => methods::MCP_SERVER_ELICITATION_REQUEST,
884            Self::PermissionsRequestApproval(_) => methods::PERMISSIONS_REQUEST_APPROVAL,
885            Self::ItemToolCall(_) => methods::ITEM_TOOL_CALL,
886            Self::ChatgptAuthTokensRefresh(_) => methods::CHATGPT_AUTH_TOKENS_REFRESH,
887            Self::AttestationGenerate(_) => methods::ATTESTATION_GENERATE,
888            Self::ApplyPatchApproval(_) => methods::APPLY_PATCH_APPROVAL,
889            Self::ExecCommandApproval(_) => methods::EXEC_COMMAND_APPROVAL,
890            Self::Unknown { method, .. } => method,
891        }
892    }
893
894    /// `true` if this request's method isn't modeled by the crate.
895    pub fn is_unknown(&self) -> bool {
896        matches!(self, Self::Unknown { .. })
897    }
898
899    /// Construct a [`ServerRequest`] from a `method` + `params` envelope.
900    pub fn from_envelope(method: &str, params: Option<Value>) -> Result<Self, serde_json::Error> {
901        let params_value = params.clone().unwrap_or(Value::Null);
902        match method {
903            methods::CMD_EXEC_APPROVAL => {
904                serde_json::from_value(params_value).map(Self::CmdExecApproval)
905            }
906            methods::FILE_CHANGE_APPROVAL => {
907                serde_json::from_value(params_value).map(Self::FileChangeApproval)
908            }
909            methods::TOOL_REQUEST_USER_INPUT => {
910                serde_json::from_value(params_value).map(Self::ToolRequestUserInput)
911            }
912            methods::MCP_SERVER_ELICITATION_REQUEST => {
913                serde_json::from_value(params_value).map(Self::McpServerElicitationRequest)
914            }
915            methods::PERMISSIONS_REQUEST_APPROVAL => {
916                serde_json::from_value(params_value).map(Self::PermissionsRequestApproval)
917            }
918            methods::ITEM_TOOL_CALL => serde_json::from_value(params_value).map(Self::ItemToolCall),
919            methods::CHATGPT_AUTH_TOKENS_REFRESH => {
920                serde_json::from_value(params_value).map(Self::ChatgptAuthTokensRefresh)
921            }
922            methods::ATTESTATION_GENERATE => {
923                serde_json::from_value(params_value).map(Self::AttestationGenerate)
924            }
925            methods::APPLY_PATCH_APPROVAL => {
926                serde_json::from_value(params_value).map(Self::ApplyPatchApproval)
927            }
928            methods::EXEC_COMMAND_APPROVAL => {
929                serde_json::from_value(params_value).map(Self::ExecCommandApproval)
930            }
931            _ => Ok(Self::Unknown {
932                method: method.to_string(),
933                params,
934            }),
935        }
936    }
937}
938
939/// A message coming from the app-server.
940///
941/// Replaces the previous loose `{ method, params }` shape with typed enums.
942/// Match on the outer variant first to distinguish notifications (no response)
943/// from requests (need [`crate::AsyncClient::respond`] /
944/// [`crate::SyncClient::respond`]).
945/// Keep variants unboxed so pattern matches and constructors stay ergonomic;
946/// the size skew comes from the generated notification payloads.
947#[allow(clippy::large_enum_variant)]
948#[derive(Debug, Clone)]
949pub enum ServerMessage {
950    /// A notification — no response required.
951    Notification(Notification),
952    /// A request — call `respond(id, ...)` on the client with the matching id.
953    Request {
954        id: RequestId,
955        request: ServerRequest,
956    },
957}
958
959impl ServerMessage {
960    /// `true` if this message is an unmodeled method (notification or request).
961    pub fn is_unknown(&self) -> bool {
962        match self {
963            Self::Notification(n) => n.is_unknown(),
964            Self::Request { request, .. } => request.is_unknown(),
965        }
966    }
967
968    /// Parse a raw app-server frame (one JSON-RPC line) into a [`ServerMessage`].
969    ///
970    /// This is the same parse path the [`AsyncClient`](crate::AsyncClient) and
971    /// [`SyncClient`](crate::SyncClient) run on incoming lines, exposed for
972    /// replay, recovery, and test fixtures that need to decode a captured frame
973    /// without a live client.
974    ///
975    /// A frame is a [`ServerMessage`] only if it is a server-initiated
976    /// notification or request. A JSON-RPC *response* / *error* (a reply to a
977    /// client request) is not a server message and returns
978    /// [`Error::Protocol`](crate::Error::Protocol). Unknown methods decode to
979    /// the `Unknown` variants rather than erroring; a modeled method whose
980    /// `params` don't fit returns [`Error::Deserialization`](crate::Error::Deserialization)
981    /// carrying the raw frame.
982    pub fn from_json_str(s: &str) -> Result<Self, Error> {
983        let msg: JsonRpcMessage = serde_json::from_str(s)
984            .map_err(|e| Error::Deserialization(ParseError::from_line(s, e)))?;
985        Self::from_jsonrpc(msg)
986    }
987
988    /// Parse a [`serde_json::Value`] frame into a [`ServerMessage`].
989    ///
990    /// See [`from_json_str`](Self::from_json_str) for the parsing contract.
991    pub fn from_value(value: Value) -> Result<Self, Error> {
992        let msg: JsonRpcMessage = serde_json::from_value(value.clone())
993            .map_err(|e| Error::Deserialization(ParseError::from_line(value.to_string(), e)))?;
994        Self::from_jsonrpc(msg)
995    }
996
997    fn from_jsonrpc(msg: JsonRpcMessage) -> Result<Self, Error> {
998        match msg {
999            JsonRpcMessage::Notification(JsonRpcNotification { method, params }) => {
1000                Notification::from_envelope(&method, params.clone())
1001                    .map(ServerMessage::Notification)
1002                    .map_err(|e| Error::Deserialization(ParseError::from_envelope(method, params, e)))
1003            }
1004            JsonRpcMessage::Request(JsonRpcRequest { id, method, params }) => {
1005                ServerRequest::from_envelope(&method, params.clone())
1006                    .map(|request| ServerMessage::Request { id, request })
1007                    .map_err(|e| Error::Deserialization(ParseError::from_envelope(method, params, e)))
1008            }
1009            JsonRpcMessage::Response(resp) => Err(Error::Protocol(format!(
1010                "frame is a JSON-RPC response (id={}), not a server-initiated message",
1011                resp.id
1012            ))),
1013            JsonRpcMessage::Error(err) => Err(Error::Protocol(format!(
1014                "frame is a JSON-RPC error response (id={}, code={}), not a server-initiated message",
1015                err.id, err.error.code
1016            ))),
1017        }
1018    }
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023    use super::*;
1024
1025    #[test]
1026    fn test_notification_unknown_method_routes_to_unknown_variant() {
1027        let n = Notification::from_envelope("foo/bar", Some(serde_json::json!({"x": 1})))
1028            .expect("unknown methods do not error");
1029        match n {
1030            Notification::Unknown { method, params } => {
1031                assert_eq!(method, "foo/bar");
1032                assert_eq!(params, Some(serde_json::json!({"x": 1})));
1033            }
1034            other => panic!("expected Unknown, got {:?}", other),
1035        }
1036    }
1037
1038    #[test]
1039    fn test_notification_known_method_with_bad_params_errors() {
1040        // thread/started expects a `thread` field — wrong shape should error.
1041        let err = Notification::from_envelope("thread/started", Some(serde_json::json!({})));
1042        assert!(err.is_err());
1043    }
1044
1045    #[test]
1046    fn test_notification_round_trip_envelope() {
1047        let wire = serde_json::json!({
1048            "method": "item/agentMessage/delta",
1049            "params": {"threadId": "t1", "turnId": "u1", "itemId": "i1", "delta": "hi"},
1050        });
1051        let n: Notification = serde_json::from_value(wire.clone()).unwrap();
1052        assert!(matches!(n, Notification::AgentMessageDelta(_)));
1053        let back = serde_json::to_value(&n).unwrap();
1054        assert_eq!(back, wire);
1055    }
1056
1057    #[test]
1058    fn test_codex_error_info_other_accepts_unknown_codes() {
1059        use crate::protocol_generated::types::CodexErrorInfo;
1060
1061        // Known codes still decode to their typed variants, tagged or not.
1062        assert_eq!(
1063            serde_json::from_value::<CodexErrorInfo>(serde_json::json!("contextWindowExceeded"))
1064                .unwrap(),
1065            CodexErrorInfo::ContextWindowExceeded
1066        );
1067        assert_eq!(
1068            serde_json::from_value::<CodexErrorInfo>(
1069                serde_json::json!({"httpConnectionFailed": {"httpStatusCode": 502}})
1070            )
1071            .unwrap(),
1072            CodexErrorInfo::HttpConnectionFailed {
1073                http_status_code: Some(502)
1074            }
1075        );
1076
1077        // Unknown strings and objects fall through to `Other` instead of erroring.
1078        for unknown in [
1079            serde_json::json!("other"),
1080            serde_json::json!("bioPolicy"),
1081            serde_json::json!({"someFutureVariant": {"detail": 1}}),
1082        ] {
1083            assert_eq!(
1084                serde_json::from_value::<CodexErrorInfo>(unknown).unwrap(),
1085                CodexErrorInfo::Other
1086            );
1087        }
1088        assert!(serde_json::from_value::<CodexErrorInfo>(serde_json::json!(42)).is_err());
1089        assert!(serde_json::from_value::<CodexErrorInfo>(serde_json::Value::Null).is_err());
1090
1091        // `Other` always serializes back to the canonical string.
1092        assert_eq!(
1093            serde_json::to_value(CodexErrorInfo::Other).unwrap(),
1094            serde_json::json!("other")
1095        );
1096    }
1097
1098    #[test]
1099    fn test_thread_goal_params_round_trip_origin() {
1100        use crate::protocol_generated::types::{
1101            ThreadGoalClearParams, ThreadGoalMutationOrigin, ThreadGoalSetParams,
1102        };
1103
1104        let set = ThreadGoalSetParams {
1105            thread_id: "t1".into(),
1106            objective: Some("ship it".into()),
1107            origin: Some(ThreadGoalMutationOrigin::User),
1108            ..Default::default()
1109        };
1110        assert_eq!(
1111            serde_json::to_value(&set).unwrap(),
1112            serde_json::json!({"threadId": "t1", "objective": "ship it", "origin": "user"})
1113        );
1114
1115        let clear: ThreadGoalClearParams =
1116            serde_json::from_value(serde_json::json!({"threadId": "t1", "origin": "automatic"}))
1117                .unwrap();
1118        assert_eq!(clear.origin, Some(ThreadGoalMutationOrigin::Automatic));
1119
1120        // Older callers omit `origin`; it must stay optional and absent on the wire.
1121        let bare: ThreadGoalClearParams =
1122            serde_json::from_value(serde_json::json!({"threadId": "t1"})).unwrap();
1123        assert_eq!(bare.origin, None);
1124        assert_eq!(
1125            serde_json::to_value(&bare).unwrap(),
1126            serde_json::json!({"threadId": "t1"})
1127        );
1128    }
1129
1130    #[test]
1131    fn test_thread_prediction_updated_round_trips_both_results() {
1132        use crate::protocol_generated::types::ThreadPredictionResult;
1133
1134        for (result, expected) in [
1135            (
1136                serde_json::json!({"type": "completed", "text": "next prompt"}),
1137                ThreadPredictionResult::Completed {
1138                    text: Some("next prompt".into()),
1139                },
1140            ),
1141            (
1142                serde_json::json!({"type": "completed"}),
1143                ThreadPredictionResult::Completed { text: None },
1144            ),
1145            (
1146                serde_json::json!({"type": "failed"}),
1147                ThreadPredictionResult::Failed,
1148            ),
1149        ] {
1150            let wire = serde_json::json!({
1151                "method": "thread/prediction/updated",
1152                "params": {"result": result, "sourceTurnId": "u1", "threadId": "t1"},
1153            });
1154            let n: Notification = serde_json::from_value(wire.clone()).unwrap();
1155            let Notification::ThreadPredictionUpdated(p) = &n else {
1156                panic!("expected ThreadPredictionUpdated, got {:?}", n);
1157            };
1158            assert_eq!(p.result, expected);
1159            assert_eq!(p.source_turn_id, "u1");
1160            assert_eq!(serde_json::to_value(&n).unwrap(), wire);
1161        }
1162    }
1163
1164    #[test]
1165    fn test_turn_id_from_turn_started() {
1166        // turn/started carries the id under `turn.id`.
1167        let wire = serde_json::json!({
1168            "method": "turn/started",
1169            "params": {"threadId": "t1", "turn": {"id": "turn_42", "status": "inProgress"}},
1170        });
1171        let n: Notification = serde_json::from_value(wire).unwrap();
1172        assert!(matches!(n, Notification::TurnStarted(_)));
1173        assert_eq!(n.turn_id(), Some("turn_42"));
1174    }
1175
1176    #[test]
1177    fn test_turn_id_from_delta_field() {
1178        // Streaming notifications carry a flat `turnId`.
1179        let wire = serde_json::json!({
1180            "method": "item/agentMessage/delta",
1181            "params": {"threadId": "t1", "turnId": "turn_7", "itemId": "i1", "delta": "hi"},
1182        });
1183        let n: Notification = serde_json::from_value(wire).unwrap();
1184        assert_eq!(n.turn_id(), Some("turn_7"));
1185    }
1186
1187    #[test]
1188    fn test_turn_id_none_for_non_turn_notification() {
1189        let n = Notification::from_envelope(
1190            "thread/deleted",
1191            Some(serde_json::json!({"threadId": "t1"})),
1192        )
1193        .unwrap();
1194        assert_eq!(n.turn_id(), None);
1195    }
1196
1197    #[test]
1198    fn test_thread_item_accessor() {
1199        let wire = serde_json::json!({
1200            "method": "item/started",
1201            "params": {
1202                "threadId": "t1",
1203                "turnId": "turn_1",
1204                "startedAtMs": 0,
1205                "item": {"type": "agentMessage", "id": "i1", "text": "hi"},
1206            },
1207        });
1208        let n: Notification = serde_json::from_value(wire).unwrap();
1209        assert!(n.thread_item().is_some());
1210        // A non-item notification has no thread item.
1211        let other = Notification::from_envelope(
1212            "thread/deleted",
1213            Some(serde_json::json!({"threadId": "t1"})),
1214        )
1215        .unwrap();
1216        assert!(other.thread_item().is_none());
1217    }
1218
1219    #[test]
1220    fn test_server_message_from_json_str_notification() {
1221        let line = r#"{"method":"turn/started","params":{"threadId":"t1","turn":{"id":"turn_9","status":"inProgress"}}}"#;
1222        let msg = ServerMessage::from_json_str(line).expect("parses a notification frame");
1223        match msg {
1224            ServerMessage::Notification(n) => assert_eq!(n.turn_id(), Some("turn_9")),
1225            other => panic!("expected Notification, got {other:?}"),
1226        }
1227    }
1228
1229    #[test]
1230    fn test_server_message_from_value_request() {
1231        let frame = serde_json::json!({
1232            "id": 7,
1233            "method": "execCommandApproval",
1234            "params": {
1235                "callId": "c1",
1236                "command": ["ls"],
1237                "conversationId": "th_1",
1238                "cwd": "/tmp",
1239                "parsedCmd": [],
1240            },
1241        });
1242        let msg = ServerMessage::from_value(frame).expect("parses a request frame");
1243        match msg {
1244            ServerMessage::Request { id, request } => {
1245                assert_eq!(id, RequestId::Integer(7));
1246                assert!(matches!(request, ServerRequest::ExecCommandApproval(_)));
1247            }
1248            other => panic!("expected Request, got {other:?}"),
1249        }
1250    }
1251
1252    #[test]
1253    fn test_server_message_from_json_str_rejects_response() {
1254        // A response to a client request is not a server-initiated message.
1255        let line = r#"{"id":1,"result":{"threadId":"th_abc"}}"#;
1256        let err = ServerMessage::from_json_str(line).unwrap_err();
1257        assert!(matches!(err, Error::Protocol(_)), "got: {err:?}");
1258    }
1259
1260    #[test]
1261    fn test_server_message_from_json_str_unknown_method_ok() {
1262        let line = r#"{"method":"some/future/notification","params":{"x":1}}"#;
1263        let msg = ServerMessage::from_json_str(line).unwrap();
1264        assert!(msg.is_unknown());
1265    }
1266}