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