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