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