Skip to main content

codex_codes/
messages.rs

1//! Typed dispatch for app-server notifications and server-to-client requests.
2//!
3//! The Codex app-server speaks JSON-RPC where every message carries a
4//! `method` discriminant alongside a free-form `params` blob. This module
5//! lifts that loose envelope into closed enums — [`Notification`] for
6//! server-initiated notifications and [`ServerRequest`] for server-initiated
7//! requests (the approval flow). Each variant wraps a typed param struct
8//! from [`crate::protocol`].
9//!
10//! The pattern mirrors the [`ContentBlock`] dispatch in the sibling
11//! `claude-codes` crate: hand-written [`Serialize`]/[`Deserialize`] impls
12//! inspect the discriminant, route known cases through `serde_json::from_value`
13//! into the typed struct, and route unknown methods into an `Unknown`
14//! variant — preserving the raw payload for forward compatibility with
15//! future codex versions.
16//!
17//! ## Typing contract
18//!
19//! - Unknown methods route to [`Notification::Unknown`] / [`ServerRequest::Unknown`]
20//!   without error. Encountering one in production typically means the
21//!   installed Codex CLI is newer than the bindings.
22//! - Known methods whose payload fails to deserialize **do** cause an error.
23//!   If you see one, the typed binding in [`crate::protocol`] is out of
24//!   sync with the wire format and needs to be updated.
25
26use crate::error::{Error, ParseError};
27use crate::jsonrpc::{JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, RequestId};
28use crate::protocol::{
29    methods, AccountLoginCompletedNotification, AccountRateLimitsUpdatedNotification,
30    AccountUpdatedNotification, AgentMessageDeltaNotification, AppListUpdatedNotification,
31    AuthRecoveryNotification, CommandExecOutputDeltaNotification,
32    CommandExecutionOutputDeltaNotification, CommandExecutionRequestApprovalParams,
33    ConfigWarningNotification, ContextCompactedNotification, DeprecationNoticeNotification,
34    EnvironmentConnectionNotification, ErrorNotification,
35    ExternalAgentConfigImportCompletedNotification, ExternalAgentConfigImportProgressNotification,
36    FileChangeOutputDeltaNotification, FileChangePatchUpdatedNotification,
37    FileChangeRequestApprovalParams, FsChangedNotification,
38    FuzzyFileSearchSessionCompletedNotification, FuzzyFileSearchSessionUpdatedNotification,
39    GatewayOAuthChangedNotification, GuardianWarningNotification, HookCompletedNotification,
40    HookStartedNotification, ItemCompletedNotification,
41    ItemGuardianApprovalReviewCompletedNotification, ItemGuardianApprovalReviewStartedNotification,
42    ItemStartedNotification, McpServerEventStreamNotification,
43    McpServerOauthLoginCompletedNotification, McpServerStatusUpdatedNotification,
44    McpToolCallProgressNotification, ModelReroutedNotification,
45    ModelSafetyBufferingUpdatedNotification, ModelVerificationNotification, PlanDeltaNotification,
46    ProcessExitedNotification, ProcessOutputDeltaNotification, ProjectChangedNotification,
47    ReasoningSummaryPartAddedNotification, ReasoningSummaryTextDeltaNotification,
48    ReasoningTextDeltaNotification, RemoteControlStatusChangedNotification,
49    ServerRequestResolvedNotification, SkillsChangedNotification, StrictReviewRequiredNotification,
50    TerminalInteractionNotification, ThreadArchivedNotification,
51    ThreadAttachmentUpdatedNotification, ThreadClosedNotification, ThreadDeletedNotification,
52    ThreadGoalClearedNotification, ThreadGoalUpdatedNotification, ThreadNameUpdatedNotification,
53    ThreadPredictionUpdatedNotification, ThreadProjectUpdatedNotification,
54    ThreadQueueChangedNotification, ThreadReadStateChangedNotification,
55    ThreadRealtimeClosedNotification, ThreadRealtimeErrorNotification,
56    ThreadRealtimeItemAddedNotification, ThreadRealtimeItemCompletedNotification,
57    ThreadRealtimeItemStartedNotification, ThreadRealtimeItemTranscriptDeltaNotification,
58    ThreadRealtimeOutputAudioDeltaNotification, ThreadRealtimeSdpNotification,
59    ThreadRealtimeStartedNotification, ThreadRealtimeTranscriptDeltaNotification,
60    ThreadRealtimeTranscriptDoneNotification, ThreadRevertedNotification,
61    ThreadSearchPartialNotification, ThreadSectionChangedNotification,
62    ThreadSettingsUpdatedNotification, ThreadStartedNotification, ThreadStatusChangedNotification,
63    ThreadTokenUsageUpdatedNotification, ThreadUnarchivedNotification, TurnCompletedNotification,
64    TurnDiffUpdatedNotification, TurnModerationMetadataNotification, TurnPlanUpdatedNotification,
65    TurnStartedNotification, WarningNotification, WindowsSandboxSetupCompletedNotification,
66    WindowsWorldWritableWarningNotification,
67};
68use serde::{Deserialize, Deserializer, Serialize, Serializer};
69use serde_json::Value;
70
71/// A server-to-client notification.
72///
73/// Each variant maps to a single `method` string on the wire. The `Unknown`
74/// variant captures methods this crate version doesn't model yet, preserving
75/// the raw payload for inspection.
76#[derive(Debug, Clone)]
77#[allow(clippy::large_enum_variant)] // transient wire values, not stored in bulk
78pub enum Notification {
79    /// `thread/started`
80    ThreadStarted(ThreadStartedNotification),
81    /// `thread/status/changed`
82    ThreadStatusChanged(ThreadStatusChangedNotification),
83    /// `thread/readState/changed` — experimental upstream; durable local
84    /// read receipt for a thread changed.
85    ThreadReadStateChanged(ThreadReadStateChangedNotification),
86    /// `thread/section/changed` — a thread moved into, within, or out of a
87    /// section; broadcast to every connected client.
88    ThreadSectionChanged(ThreadSectionChangedNotification),
89    /// `thread/tokenUsage/updated`
90    ThreadTokenUsageUpdated(ThreadTokenUsageUpdatedNotification),
91    /// `turn/started`
92    TurnStarted(TurnStartedNotification),
93    /// `turn/completed`
94    TurnCompleted(TurnCompletedNotification),
95    /// `item/started`
96    ItemStarted(ItemStartedNotification),
97    /// `item/completed`
98    ItemCompleted(ItemCompletedNotification),
99    /// `item/agentMessage/delta`
100    AgentMessageDelta(AgentMessageDeltaNotification),
101    /// `item/commandExecution/outputDelta`
102    CmdOutputDelta(CommandExecutionOutputDeltaNotification),
103    /// `item/fileChange/outputDelta`
104    FileChangeOutputDelta(FileChangeOutputDeltaNotification),
105    /// `item/reasoning/summaryTextDelta`
106    ReasoningDelta(ReasoningSummaryTextDeltaNotification),
107    /// `error`
108    Error(ErrorNotification),
109    /// `account/rateLimits/updated`
110    AccountRateLimitsUpdated(AccountRateLimitsUpdatedNotification),
111    /// `mcpServer/startupStatus/updated`
112    McpServerStartupStatusUpdated(McpServerStatusUpdatedNotification),
113    /// `remoteControl/status/changed`
114    RemoteControlStatusChanged(RemoteControlStatusChangedNotification),
115    /// `mcpServer/oauthLogin/completed`
116    McpServerOauthLoginCompleted(McpServerOauthLoginCompletedNotification),
117    /// `item/fileChange/patchUpdated`
118    FileChangePatchUpdated(FileChangePatchUpdatedNotification),
119    /// `item/plan/delta` (EXPERIMENTAL)
120    PlanDelta(PlanDeltaNotification),
121    /// `turn/plan/updated`
122    TurnPlanUpdated(TurnPlanUpdatedNotification),
123    /// `turn/diff/updated`
124    TurnDiffUpdated(TurnDiffUpdatedNotification),
125    /// `item/reasoning/summaryPartAdded`
126    ReasoningSummaryPartAdded(ReasoningSummaryPartAddedNotification),
127    /// `item/reasoning/textDelta`
128    ReasoningTextDelta(ReasoningTextDeltaNotification),
129    /// `account/login/completed`
130    AccountLoginCompleted(AccountLoginCompletedNotification),
131    /// `deprecationNotice`
132    DeprecationNotice(DeprecationNoticeNotification),
133    /// `guardianWarning`
134    GuardianWarning(GuardianWarningNotification),
135    /// `warning`
136    Warning(WarningNotification),
137    /// `thread/archived`
138    ThreadArchived(ThreadArchivedNotification),
139    /// `thread/closed`
140    ThreadClosed(ThreadClosedNotification),
141    /// `thread/deleted`
142    ThreadDeleted(ThreadDeletedNotification),
143    /// `thread/unarchived`
144    ThreadUnarchived(ThreadUnarchivedNotification),
145    /// `thread/goal/cleared`
146    ThreadGoalCleared(ThreadGoalClearedNotification),
147    /// `thread/name/updated`
148    ThreadNameUpdated(ThreadNameUpdatedNotification),
149    /// `thread/attachment/updated`
150    ThreadAttachmentUpdated(ThreadAttachmentUpdatedNotification),
151    /// `skills/changed`
152    SkillsChanged(SkillsChangedNotification),
153    /// `fs/changed`
154    FsChanged(FsChangedNotification),
155    /// `configWarning`
156    ConfigWarning(ConfigWarningNotification),
157    /// `account/updated`
158    AccountUpdated(AccountUpdatedNotification),
159    /// `account/gatewayOAuth/changed`
160    GatewayOAuthChanged(GatewayOAuthChangedNotification),
161    /// `app/list/updated`
162    AppListUpdated(AppListUpdatedNotification),
163    /// `command/exec/outputDelta`
164    CommandExecOutputDelta(CommandExecOutputDeltaNotification),
165    /// `externalAgentConfig/import/completed`
166    ExternalAgentConfigImportCompleted(ExternalAgentConfigImportCompletedNotification),
167    /// `fuzzyFileSearch/sessionCompleted`
168    FuzzyFileSearchSessionCompleted(FuzzyFileSearchSessionCompletedNotification),
169    /// `fuzzyFileSearch/sessionUpdated`
170    FuzzyFileSearchSessionUpdated(FuzzyFileSearchSessionUpdatedNotification),
171    /// `hook/completed`
172    HookCompleted(HookCompletedNotification),
173    /// `hook/started`
174    HookStarted(HookStartedNotification),
175    /// `item/autoApprovalReview/completed`
176    ItemGuardianApprovalReviewCompleted(ItemGuardianApprovalReviewCompletedNotification),
177    /// `item/autoApprovalReview/started`
178    ItemGuardianApprovalReviewStarted(ItemGuardianApprovalReviewStartedNotification),
179    /// `item/commandExecution/terminalInteraction`
180    TerminalInteraction(TerminalInteractionNotification),
181    /// `item/mcpToolCall/progress`
182    McpToolCallProgress(McpToolCallProgressNotification),
183    /// `model/rerouted`
184    ModelRerouted(ModelReroutedNotification),
185    /// `model/verification`
186    ModelVerification(ModelVerificationNotification),
187    /// `process/exited`
188    ProcessExited(ProcessExitedNotification),
189    /// `process/outputDelta`
190    ProcessOutputDelta(ProcessOutputDeltaNotification),
191    /// `serverRequest/resolved`
192    ServerRequestResolved(ServerRequestResolvedNotification),
193    /// `thread/search/partial` (experimental)
194    ThreadSearchPartial(ThreadSearchPartialNotification),
195    /// `thread/compacted`
196    ContextCompacted(ContextCompactedNotification),
197    /// `thread/goal/updated`
198    ThreadGoalUpdated(ThreadGoalUpdatedNotification),
199    /// `thread/realtime/closed`
200    ThreadRealtimeClosed(ThreadRealtimeClosedNotification),
201    /// `thread/realtime/error`
202    ThreadRealtimeError(ThreadRealtimeErrorNotification),
203    /// `thread/realtime/itemAdded`
204    ThreadRealtimeItemAdded(ThreadRealtimeItemAddedNotification),
205    /// `thread/realtime/outputAudio/delta`
206    ThreadRealtimeOutputAudioDelta(ThreadRealtimeOutputAudioDeltaNotification),
207    /// `thread/realtime/sdp`
208    ThreadRealtimeSdp(ThreadRealtimeSdpNotification),
209    /// `thread/realtime/started`
210    ThreadRealtimeStarted(ThreadRealtimeStartedNotification),
211    /// `thread/realtime/transcript/delta`
212    ThreadRealtimeTranscriptDelta(ThreadRealtimeTranscriptDeltaNotification),
213    /// `thread/realtime/transcript/done`
214    ThreadRealtimeTranscriptDone(ThreadRealtimeTranscriptDoneNotification),
215    /// `windows/worldWritableWarning`
216    WindowsWorldWritableWarning(WindowsWorldWritableWarningNotification),
217    /// `windowsSandbox/setupCompleted`
218    WindowsSandboxSetupCompleted(WindowsSandboxSetupCompletedNotification),
219    /// `thread/settings/updated`
220    ThreadSettingsUpdated(ThreadSettingsUpdatedNotification),
221    /// `turn/moderationMetadata`
222    TurnModerationMetadata(TurnModerationMetadataNotification),
223    /// `externalAgentConfig/import/progress`
224    ExternalAgentConfigImportProgress(ExternalAgentConfigImportProgressNotification),
225    /// `model/safetyBuffering/updated`
226    ModelSafetyBufferingUpdated(ModelSafetyBufferingUpdatedNotification),
227    /// `thread/environment/connected`
228    ThreadEnvironmentConnected(EnvironmentConnectionNotification),
229    /// `thread/environment/disconnected`
230    ThreadEnvironmentDisconnected(EnvironmentConnectionNotification),
231    /// `autoApprovalReview/strictReviewRequired` (0.147)
232    StrictReviewRequired(StrictReviewRequiredNotification),
233    /// `project/changed` (0.147)
234    ProjectChanged(ProjectChangedNotification),
235    /// `thread/project/updated` (0.147)
236    ThreadProjectUpdated(ThreadProjectUpdatedNotification),
237    /// `thread/queue/changed` (0.147)
238    ThreadQueueChanged(ThreadQueueChangedNotification),
239    /// `thread/reverted` (0.147)
240    ThreadReverted(ThreadRevertedNotification),
241    /// `mcpServer/event/stream/notification` (0.148 upstream)
242    McpServerEventStream(McpServerEventStreamNotification),
243    /// `thread/realtime/item/started` (0.148 upstream, experimental)
244    ThreadRealtimeItemStarted(ThreadRealtimeItemStartedNotification),
245    /// `thread/realtime/item/completed` (0.148 upstream, experimental)
246    ThreadRealtimeItemCompleted(ThreadRealtimeItemCompletedNotification),
247    /// `thread/realtime/item/transcript/delta` (0.148 upstream, experimental)
248    ThreadRealtimeItemTranscriptDelta(ThreadRealtimeItemTranscriptDeltaNotification),
249    /// `modelProvider/authRecoveryStarted` (0.148 upstream)
250    ModelProviderAuthRecoveryStarted(AuthRecoveryNotification),
251    /// `modelProvider/authRecoveryCompleted` (0.148 upstream)
252    ModelProviderAuthRecoveryCompleted(AuthRecoveryNotification),
253    /// `thread/prediction/updated` (0.159 upstream, experimental)
254    ThreadPredictionUpdated(ThreadPredictionUpdatedNotification),
255    /// A method this crate version does not yet model. The raw params are
256    /// preserved for caller inspection. Encountering this typically means
257    /// the installed codex CLI is newer than the bindings.
258    Unknown {
259        method: String,
260        params: Option<Value>,
261    },
262}
263
264impl Notification {
265    /// Return the wire `method` string for this notification.
266    pub fn method(&self) -> &str {
267        match self {
268            Self::ThreadStarted(_) => methods::THREAD_STARTED,
269            Self::StrictReviewRequired(_) => methods::STRICT_REVIEW_REQUIRED,
270            Self::ProjectChanged(_) => methods::PROJECT_CHANGED,
271            Self::ThreadProjectUpdated(_) => methods::THREAD_PROJECT_UPDATED,
272            Self::ThreadQueueChanged(_) => methods::THREAD_QUEUE_CHANGED,
273            Self::ThreadReverted(_) => methods::THREAD_REVERTED,
274            Self::ThreadPredictionUpdated(_) => methods::THREAD_PREDICTION_UPDATED,
275            Self::McpServerEventStream(_) => methods::MCP_SERVER_EVENT_STREAM,
276            Self::ThreadRealtimeItemStarted(_) => methods::THREAD_REALTIME_ITEM_STARTED,
277            Self::ThreadRealtimeItemCompleted(_) => methods::THREAD_REALTIME_ITEM_COMPLETED,
278            Self::ThreadRealtimeItemTranscriptDelta(_) => {
279                methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA
280            }
281            Self::ModelProviderAuthRecoveryStarted(_) => {
282                methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED
283            }
284            Self::ModelProviderAuthRecoveryCompleted(_) => {
285                methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED
286            }
287            Self::ThreadStatusChanged(_) => methods::THREAD_STATUS_CHANGED,
288            Self::ThreadReadStateChanged(_) => methods::THREAD_READ_STATE_CHANGED,
289            Self::ThreadSectionChanged(_) => methods::THREAD_SECTION_CHANGED,
290            Self::ThreadTokenUsageUpdated(_) => methods::THREAD_TOKEN_USAGE_UPDATED,
291            Self::TurnStarted(_) => methods::TURN_STARTED,
292            Self::TurnCompleted(_) => methods::TURN_COMPLETED,
293            Self::ItemStarted(_) => methods::ITEM_STARTED,
294            Self::ItemCompleted(_) => methods::ITEM_COMPLETED,
295            Self::AgentMessageDelta(_) => methods::AGENT_MESSAGE_DELTA,
296            Self::CmdOutputDelta(_) => methods::CMD_OUTPUT_DELTA,
297            Self::FileChangeOutputDelta(_) => methods::FILE_CHANGE_OUTPUT_DELTA,
298            Self::ReasoningDelta(_) => methods::REASONING_DELTA,
299            Self::Error(_) => methods::ERROR,
300            Self::AccountRateLimitsUpdated(_) => methods::ACCOUNT_RATE_LIMITS_UPDATED,
301            Self::McpServerStartupStatusUpdated(_) => methods::MCP_SERVER_STARTUP_STATUS_UPDATED,
302            Self::RemoteControlStatusChanged(_) => methods::REMOTE_CONTROL_STATUS_CHANGED,
303            Self::McpServerOauthLoginCompleted(_) => methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED,
304            Self::FileChangePatchUpdated(_) => methods::FILE_CHANGE_PATCH_UPDATED,
305            Self::PlanDelta(_) => methods::PLAN_DELTA,
306            Self::TurnPlanUpdated(_) => methods::TURN_PLAN_UPDATED,
307            Self::TurnDiffUpdated(_) => methods::TURN_DIFF_UPDATED,
308            Self::ReasoningSummaryPartAdded(_) => methods::REASONING_SUMMARY_PART_ADDED,
309            Self::ReasoningTextDelta(_) => methods::REASONING_TEXT_DELTA,
310            Self::AccountLoginCompleted(_) => methods::ACCOUNT_LOGIN_COMPLETED,
311            Self::DeprecationNotice(_) => methods::DEPRECATION_NOTICE,
312            Self::GuardianWarning(_) => methods::GUARDIAN_WARNING,
313            Self::Warning(_) => methods::WARNING,
314            Self::ThreadArchived(_) => methods::THREAD_ARCHIVED,
315            Self::ThreadClosed(_) => methods::THREAD_CLOSED,
316            Self::ThreadDeleted(_) => methods::THREAD_DELETED,
317            Self::ThreadUnarchived(_) => methods::THREAD_UNARCHIVED,
318            Self::ThreadGoalCleared(_) => methods::THREAD_GOAL_CLEARED,
319            Self::ThreadNameUpdated(_) => methods::THREAD_NAME_UPDATED,
320            Self::ThreadAttachmentUpdated(_) => methods::THREAD_ATTACHMENT_UPDATED,
321            Self::SkillsChanged(_) => methods::SKILLS_CHANGED,
322            Self::FsChanged(_) => methods::FS_CHANGED,
323            Self::ConfigWarning(_) => methods::CONFIG_WARNING,
324            Self::AccountUpdated(_) => methods::ACCOUNT_UPDATED,
325            Self::GatewayOAuthChanged(_) => methods::ACCOUNT_GATEWAY_OAUTH_CHANGED,
326            Self::AppListUpdated(_) => methods::APP_LIST_UPDATED,
327            Self::CommandExecOutputDelta(_) => methods::COMMAND_EXEC_OUTPUT_DELTA,
328            Self::ExternalAgentConfigImportCompleted(_) => {
329                methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED
330            }
331            Self::FuzzyFileSearchSessionCompleted(_) => {
332                methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED
333            }
334            Self::FuzzyFileSearchSessionUpdated(_) => methods::FUZZY_FILE_SEARCH_SESSION_UPDATED,
335            Self::HookCompleted(_) => methods::HOOK_COMPLETED,
336            Self::HookStarted(_) => methods::HOOK_STARTED,
337            Self::ItemGuardianApprovalReviewCompleted(_) => {
338                methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED
339            }
340            Self::ItemGuardianApprovalReviewStarted(_) => {
341                methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED
342            }
343            Self::TerminalInteraction(_) => methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION,
344            Self::McpToolCallProgress(_) => methods::ITEM_MCP_TOOL_CALL_PROGRESS,
345            Self::ModelRerouted(_) => methods::MODEL_REROUTED,
346            Self::ModelVerification(_) => methods::MODEL_VERIFICATION,
347            Self::ProcessExited(_) => methods::PROCESS_EXITED,
348            Self::ProcessOutputDelta(_) => methods::PROCESS_OUTPUT_DELTA,
349            Self::ServerRequestResolved(_) => methods::SERVER_REQUEST_RESOLVED,
350            Self::ThreadSearchPartial(_) => methods::THREAD_SEARCH_PARTIAL,
351            Self::ContextCompacted(_) => methods::THREAD_COMPACTED,
352            Self::ThreadGoalUpdated(_) => methods::THREAD_GOAL_UPDATED,
353            Self::ThreadRealtimeClosed(_) => methods::THREAD_REALTIME_CLOSED,
354            Self::ThreadRealtimeError(_) => methods::THREAD_REALTIME_ERROR,
355            Self::ThreadRealtimeItemAdded(_) => methods::THREAD_REALTIME_ITEM_ADDED,
356            Self::ThreadRealtimeOutputAudioDelta(_) => methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA,
357            Self::ThreadRealtimeSdp(_) => methods::THREAD_REALTIME_SDP,
358            Self::ThreadRealtimeStarted(_) => methods::THREAD_REALTIME_STARTED,
359            Self::ThreadRealtimeTranscriptDelta(_) => methods::THREAD_REALTIME_TRANSCRIPT_DELTA,
360            Self::ThreadRealtimeTranscriptDone(_) => methods::THREAD_REALTIME_TRANSCRIPT_DONE,
361            Self::WindowsWorldWritableWarning(_) => methods::WINDOWS_WORLD_WRITABLE_WARNING,
362            Self::WindowsSandboxSetupCompleted(_) => methods::WINDOWS_SANDBOX_SETUP_COMPLETED,
363            Self::ThreadSettingsUpdated(_) => methods::THREAD_SETTINGS_UPDATED,
364            Self::TurnModerationMetadata(_) => methods::TURN_MODERATION_METADATA,
365            Self::ExternalAgentConfigImportProgress(_) => {
366                methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS
367            }
368            Self::ModelSafetyBufferingUpdated(_) => methods::MODEL_SAFETY_BUFFERING_UPDATED,
369            Self::ThreadEnvironmentConnected(_) => methods::THREAD_ENVIRONMENT_CONNECTED,
370            Self::ThreadEnvironmentDisconnected(_) => methods::THREAD_ENVIRONMENT_DISCONNECTED,
371            Self::Unknown { method, .. } => method,
372        }
373    }
374
375    /// `true` if this notification's method isn't modeled by the crate.
376    pub fn is_unknown(&self) -> bool {
377        matches!(self, Self::Unknown { .. })
378    }
379
380    /// Return the turn id this notification is scoped to, if it carries one.
381    ///
382    /// Reads the typed `turnId` field (or `turn.id` for the turn-lifecycle
383    /// notifications) directly, so callers don't have to round-trip through
384    /// [`into_envelope`](Self::into_envelope) and poke `serde_json::Value`
385    /// fields. Returns `None` for notifications that aren't turn-scoped, and
386    /// treats an empty id the server omitted as absent.
387    ///
388    /// The turn id from `turn/started` is what
389    /// [`turn/interrupt`](crate::AsyncClient::turn_interrupt) needs to cancel
390    /// the active turn.
391    pub fn turn_id(&self) -> Option<&str> {
392        let id = match self {
393            Self::TurnStarted(n) => n.turn.id.as_str(),
394            Self::TurnCompleted(n) => n.turn.id.as_str(),
395            Self::AgentMessageDelta(n) => n.turn_id.as_str(),
396            Self::CmdOutputDelta(n) => n.turn_id.as_str(),
397            Self::FileChangeOutputDelta(n) => n.turn_id.as_str(),
398            Self::ReasoningDelta(n) => n.turn_id.as_str(),
399            Self::Error(n) => n.turn_id.as_str(),
400            Self::FileChangePatchUpdated(n) => n.turn_id.as_str(),
401            Self::PlanDelta(n) => n.turn_id.as_str(),
402            Self::TurnPlanUpdated(n) => n.turn_id.as_str(),
403            Self::TurnDiffUpdated(n) => n.turn_id.as_str(),
404            Self::TurnModerationMetadata(n) => n.turn_id.as_str(),
405            Self::ReasoningSummaryPartAdded(n) => n.turn_id.as_str(),
406            Self::ReasoningTextDelta(n) => n.turn_id.as_str(),
407            Self::ItemStarted(n) => n.turn_id.as_str(),
408            Self::ItemCompleted(n) => n.turn_id.as_str(),
409            Self::ContextCompacted(n) => n.turn_id.as_str(),
410            Self::McpToolCallProgress(n) => n.turn_id.as_str(),
411            Self::ModelRerouted(n) => n.turn_id.as_str(),
412            Self::ModelVerification(n) => n.turn_id.as_str(),
413            Self::ModelSafetyBufferingUpdated(n) => n.turn_id.as_str(),
414            Self::TerminalInteraction(n) => n.turn_id.as_str(),
415            Self::ThreadTokenUsageUpdated(n) => n.turn_id.as_str(),
416            Self::ItemGuardianApprovalReviewStarted(n) => n.turn_id.as_str(),
417            Self::ItemGuardianApprovalReviewCompleted(n) => n.turn_id.as_str(),
418            _ => return None,
419        };
420        (!id.is_empty()).then_some(id)
421    }
422
423    /// Return the typed [`ThreadItem`](crate::protocol::ThreadItem) this
424    /// notification carries, for `item/started` and `item/completed`.
425    ///
426    /// Lets downstream event adapters read the item's typed fields instead of
427    /// reserializing it back into `serde_json::Value`.
428    pub fn thread_item(&self) -> Option<&crate::protocol::ThreadItem> {
429        match self {
430            Self::ItemStarted(n) => Some(&n.item),
431            Self::ItemCompleted(n) => Some(&n.item),
432            _ => None,
433        }
434    }
435
436    /// Construct a [`Notification`] from a `method` + `params` envelope.
437    ///
438    /// Returns an error if `method` is recognized but `params` doesn't
439    /// deserialize into the typed struct. Unknown methods route to
440    /// [`Notification::Unknown`] without error.
441    pub fn from_envelope(method: &str, params: Option<Value>) -> Result<Self, serde_json::Error> {
442        let params_value = params.clone().unwrap_or(Value::Null);
443        match method {
444            methods::THREAD_STARTED => {
445                serde_json::from_value(params_value).map(Self::ThreadStarted)
446            }
447            methods::STRICT_REVIEW_REQUIRED => {
448                serde_json::from_value(params_value).map(Self::StrictReviewRequired)
449            }
450            methods::PROJECT_CHANGED => {
451                serde_json::from_value(params_value).map(Self::ProjectChanged)
452            }
453            methods::THREAD_PROJECT_UPDATED => {
454                serde_json::from_value(params_value).map(Self::ThreadProjectUpdated)
455            }
456            methods::THREAD_QUEUE_CHANGED => {
457                serde_json::from_value(params_value).map(Self::ThreadQueueChanged)
458            }
459            methods::THREAD_REVERTED => {
460                serde_json::from_value(params_value).map(Self::ThreadReverted)
461            }
462            methods::THREAD_PREDICTION_UPDATED => {
463                serde_json::from_value(params_value).map(Self::ThreadPredictionUpdated)
464            }
465            methods::MCP_SERVER_EVENT_STREAM => {
466                serde_json::from_value(params_value).map(Self::McpServerEventStream)
467            }
468            methods::THREAD_REALTIME_ITEM_STARTED => {
469                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemStarted)
470            }
471            methods::THREAD_REALTIME_ITEM_COMPLETED => {
472                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemCompleted)
473            }
474            methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA => {
475                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemTranscriptDelta)
476            }
477            methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED => {
478                serde_json::from_value(params_value).map(Self::ModelProviderAuthRecoveryStarted)
479            }
480            methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED => {
481                serde_json::from_value(params_value).map(Self::ModelProviderAuthRecoveryCompleted)
482            }
483            methods::THREAD_STATUS_CHANGED => {
484                serde_json::from_value(params_value).map(Self::ThreadStatusChanged)
485            }
486            methods::THREAD_READ_STATE_CHANGED => {
487                serde_json::from_value(params_value).map(Self::ThreadReadStateChanged)
488            }
489            methods::THREAD_SECTION_CHANGED => {
490                serde_json::from_value(params_value).map(Self::ThreadSectionChanged)
491            }
492            methods::THREAD_TOKEN_USAGE_UPDATED => {
493                serde_json::from_value(params_value).map(Self::ThreadTokenUsageUpdated)
494            }
495            methods::TURN_STARTED => serde_json::from_value(params_value).map(Self::TurnStarted),
496            methods::TURN_COMPLETED => {
497                serde_json::from_value(params_value).map(Self::TurnCompleted)
498            }
499            methods::ITEM_STARTED => serde_json::from_value(params_value).map(Self::ItemStarted),
500            methods::ITEM_COMPLETED => {
501                serde_json::from_value(params_value).map(Self::ItemCompleted)
502            }
503            methods::AGENT_MESSAGE_DELTA => {
504                serde_json::from_value(params_value).map(Self::AgentMessageDelta)
505            }
506            methods::CMD_OUTPUT_DELTA => {
507                serde_json::from_value(params_value).map(Self::CmdOutputDelta)
508            }
509            methods::FILE_CHANGE_OUTPUT_DELTA => {
510                serde_json::from_value(params_value).map(Self::FileChangeOutputDelta)
511            }
512            methods::REASONING_DELTA => {
513                serde_json::from_value(params_value).map(Self::ReasoningDelta)
514            }
515            methods::ERROR => serde_json::from_value(params_value).map(Self::Error),
516            methods::ACCOUNT_RATE_LIMITS_UPDATED => {
517                serde_json::from_value(params_value).map(Self::AccountRateLimitsUpdated)
518            }
519            methods::MCP_SERVER_STARTUP_STATUS_UPDATED => {
520                serde_json::from_value(params_value).map(Self::McpServerStartupStatusUpdated)
521            }
522            methods::REMOTE_CONTROL_STATUS_CHANGED => {
523                serde_json::from_value(params_value).map(Self::RemoteControlStatusChanged)
524            }
525            methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED => {
526                serde_json::from_value(params_value).map(Self::McpServerOauthLoginCompleted)
527            }
528            methods::FILE_CHANGE_PATCH_UPDATED => {
529                serde_json::from_value(params_value).map(Self::FileChangePatchUpdated)
530            }
531            methods::PLAN_DELTA => serde_json::from_value(params_value).map(Self::PlanDelta),
532            methods::TURN_PLAN_UPDATED => {
533                serde_json::from_value(params_value).map(Self::TurnPlanUpdated)
534            }
535            methods::TURN_DIFF_UPDATED => {
536                serde_json::from_value(params_value).map(Self::TurnDiffUpdated)
537            }
538            methods::REASONING_SUMMARY_PART_ADDED => {
539                serde_json::from_value(params_value).map(Self::ReasoningSummaryPartAdded)
540            }
541            methods::REASONING_TEXT_DELTA => {
542                serde_json::from_value(params_value).map(Self::ReasoningTextDelta)
543            }
544            methods::ACCOUNT_LOGIN_COMPLETED => {
545                serde_json::from_value(params_value).map(Self::AccountLoginCompleted)
546            }
547            methods::DEPRECATION_NOTICE => {
548                serde_json::from_value(params_value).map(Self::DeprecationNotice)
549            }
550            methods::GUARDIAN_WARNING => {
551                serde_json::from_value(params_value).map(Self::GuardianWarning)
552            }
553            methods::WARNING => serde_json::from_value(params_value).map(Self::Warning),
554            methods::THREAD_ARCHIVED => {
555                serde_json::from_value(params_value).map(Self::ThreadArchived)
556            }
557            methods::THREAD_CLOSED => serde_json::from_value(params_value).map(Self::ThreadClosed),
558            methods::THREAD_DELETED => {
559                serde_json::from_value(params_value).map(Self::ThreadDeleted)
560            }
561            methods::THREAD_UNARCHIVED => {
562                serde_json::from_value(params_value).map(Self::ThreadUnarchived)
563            }
564            methods::THREAD_GOAL_CLEARED => {
565                serde_json::from_value(params_value).map(Self::ThreadGoalCleared)
566            }
567            methods::THREAD_NAME_UPDATED => {
568                serde_json::from_value(params_value).map(Self::ThreadNameUpdated)
569            }
570            methods::THREAD_ATTACHMENT_UPDATED => {
571                serde_json::from_value(params_value).map(Self::ThreadAttachmentUpdated)
572            }
573            methods::SKILLS_CHANGED => {
574                serde_json::from_value(params_value).map(Self::SkillsChanged)
575            }
576            methods::FS_CHANGED => serde_json::from_value(params_value).map(Self::FsChanged),
577            methods::CONFIG_WARNING => {
578                serde_json::from_value(params_value).map(Self::ConfigWarning)
579            }
580            methods::ACCOUNT_UPDATED => {
581                serde_json::from_value(params_value).map(Self::AccountUpdated)
582            }
583            methods::ACCOUNT_GATEWAY_OAUTH_CHANGED => {
584                serde_json::from_value(params_value).map(Self::GatewayOAuthChanged)
585            }
586            methods::APP_LIST_UPDATED => {
587                serde_json::from_value(params_value).map(Self::AppListUpdated)
588            }
589            methods::COMMAND_EXEC_OUTPUT_DELTA => {
590                serde_json::from_value(params_value).map(Self::CommandExecOutputDelta)
591            }
592            methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED => {
593                serde_json::from_value(params_value).map(Self::ExternalAgentConfigImportCompleted)
594            }
595            methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED => {
596                serde_json::from_value(params_value).map(Self::FuzzyFileSearchSessionCompleted)
597            }
598            methods::FUZZY_FILE_SEARCH_SESSION_UPDATED => {
599                serde_json::from_value(params_value).map(Self::FuzzyFileSearchSessionUpdated)
600            }
601            methods::HOOK_COMPLETED => {
602                serde_json::from_value(params_value).map(Self::HookCompleted)
603            }
604            methods::HOOK_STARTED => serde_json::from_value(params_value).map(Self::HookStarted),
605            methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED => {
606                serde_json::from_value(params_value).map(Self::ItemGuardianApprovalReviewCompleted)
607            }
608            methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED => {
609                serde_json::from_value(params_value).map(Self::ItemGuardianApprovalReviewStarted)
610            }
611            methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION => {
612                serde_json::from_value(params_value).map(Self::TerminalInteraction)
613            }
614            methods::ITEM_MCP_TOOL_CALL_PROGRESS => {
615                serde_json::from_value(params_value).map(Self::McpToolCallProgress)
616            }
617            methods::MODEL_REROUTED => {
618                serde_json::from_value(params_value).map(Self::ModelRerouted)
619            }
620            methods::MODEL_VERIFICATION => {
621                serde_json::from_value(params_value).map(Self::ModelVerification)
622            }
623            methods::PROCESS_EXITED => {
624                serde_json::from_value(params_value).map(Self::ProcessExited)
625            }
626            methods::PROCESS_OUTPUT_DELTA => {
627                serde_json::from_value(params_value).map(Self::ProcessOutputDelta)
628            }
629            methods::SERVER_REQUEST_RESOLVED => {
630                serde_json::from_value(params_value).map(Self::ServerRequestResolved)
631            }
632            methods::THREAD_SEARCH_PARTIAL => {
633                serde_json::from_value(params_value).map(Self::ThreadSearchPartial)
634            }
635            methods::THREAD_COMPACTED => {
636                serde_json::from_value(params_value).map(Self::ContextCompacted)
637            }
638            methods::THREAD_GOAL_UPDATED => {
639                serde_json::from_value(params_value).map(Self::ThreadGoalUpdated)
640            }
641            methods::THREAD_REALTIME_CLOSED => {
642                serde_json::from_value(params_value).map(Self::ThreadRealtimeClosed)
643            }
644            methods::THREAD_REALTIME_ERROR => {
645                serde_json::from_value(params_value).map(Self::ThreadRealtimeError)
646            }
647            methods::THREAD_REALTIME_ITEM_ADDED => {
648                serde_json::from_value(params_value).map(Self::ThreadRealtimeItemAdded)
649            }
650            methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA => {
651                serde_json::from_value(params_value).map(Self::ThreadRealtimeOutputAudioDelta)
652            }
653            methods::THREAD_REALTIME_SDP => {
654                serde_json::from_value(params_value).map(Self::ThreadRealtimeSdp)
655            }
656            methods::THREAD_REALTIME_STARTED => {
657                serde_json::from_value(params_value).map(Self::ThreadRealtimeStarted)
658            }
659            methods::THREAD_REALTIME_TRANSCRIPT_DELTA => {
660                serde_json::from_value(params_value).map(Self::ThreadRealtimeTranscriptDelta)
661            }
662            methods::THREAD_REALTIME_TRANSCRIPT_DONE => {
663                serde_json::from_value(params_value).map(Self::ThreadRealtimeTranscriptDone)
664            }
665            methods::WINDOWS_WORLD_WRITABLE_WARNING => {
666                serde_json::from_value(params_value).map(Self::WindowsWorldWritableWarning)
667            }
668            methods::WINDOWS_SANDBOX_SETUP_COMPLETED => {
669                serde_json::from_value(params_value).map(Self::WindowsSandboxSetupCompleted)
670            }
671            methods::THREAD_SETTINGS_UPDATED => {
672                serde_json::from_value(params_value).map(Self::ThreadSettingsUpdated)
673            }
674            methods::TURN_MODERATION_METADATA => {
675                serde_json::from_value(params_value).map(Self::TurnModerationMetadata)
676            }
677            methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS => {
678                serde_json::from_value(params_value).map(Self::ExternalAgentConfigImportProgress)
679            }
680            methods::MODEL_SAFETY_BUFFERING_UPDATED => {
681                serde_json::from_value(params_value).map(Self::ModelSafetyBufferingUpdated)
682            }
683            methods::THREAD_ENVIRONMENT_CONNECTED => {
684                serde_json::from_value(params_value).map(Self::ThreadEnvironmentConnected)
685            }
686            methods::THREAD_ENVIRONMENT_DISCONNECTED => {
687                serde_json::from_value(params_value).map(Self::ThreadEnvironmentDisconnected)
688            }
689            _ => Ok(Self::Unknown {
690                method: method.to_string(),
691                params,
692            }),
693        }
694    }
695
696    /// Decompose this notification back into a `(method, params)` pair.
697    pub fn into_envelope(self) -> Result<(String, Option<Value>), serde_json::Error> {
698        fn pack<T: Serialize>(
699            method: &str,
700            v: &T,
701        ) -> Result<(String, Option<Value>), serde_json::Error> {
702            Ok((method.to_string(), Some(serde_json::to_value(v)?)))
703        }
704        match &self {
705            Self::ThreadStarted(v) => pack(methods::THREAD_STARTED, v),
706            Self::StrictReviewRequired(v) => pack(methods::STRICT_REVIEW_REQUIRED, v),
707            Self::ProjectChanged(v) => pack(methods::PROJECT_CHANGED, v),
708            Self::ThreadProjectUpdated(v) => pack(methods::THREAD_PROJECT_UPDATED, v),
709            Self::ThreadQueueChanged(v) => pack(methods::THREAD_QUEUE_CHANGED, v),
710            Self::ThreadReverted(v) => pack(methods::THREAD_REVERTED, v),
711            Self::ThreadPredictionUpdated(v) => pack(methods::THREAD_PREDICTION_UPDATED, v),
712            Self::McpServerEventStream(v) => pack(methods::MCP_SERVER_EVENT_STREAM, v),
713            Self::ThreadRealtimeItemStarted(v) => pack(methods::THREAD_REALTIME_ITEM_STARTED, v),
714            Self::ThreadRealtimeItemCompleted(v) => {
715                pack(methods::THREAD_REALTIME_ITEM_COMPLETED, v)
716            }
717            Self::ThreadRealtimeItemTranscriptDelta(v) => {
718                pack(methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA, v)
719            }
720            Self::ModelProviderAuthRecoveryStarted(v) => {
721                pack(methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED, v)
722            }
723            Self::ModelProviderAuthRecoveryCompleted(v) => {
724                pack(methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED, v)
725            }
726            Self::ThreadStatusChanged(v) => pack(methods::THREAD_STATUS_CHANGED, v),
727            Self::ThreadReadStateChanged(v) => pack(methods::THREAD_READ_STATE_CHANGED, v),
728            Self::ThreadSectionChanged(v) => pack(methods::THREAD_SECTION_CHANGED, v),
729            Self::ThreadTokenUsageUpdated(v) => pack(methods::THREAD_TOKEN_USAGE_UPDATED, v),
730            Self::TurnStarted(v) => pack(methods::TURN_STARTED, v),
731            Self::TurnCompleted(v) => pack(methods::TURN_COMPLETED, v),
732            Self::ItemStarted(v) => pack(methods::ITEM_STARTED, v),
733            Self::ItemCompleted(v) => pack(methods::ITEM_COMPLETED, v),
734            Self::AgentMessageDelta(v) => pack(methods::AGENT_MESSAGE_DELTA, v),
735            Self::CmdOutputDelta(v) => pack(methods::CMD_OUTPUT_DELTA, v),
736            Self::FileChangeOutputDelta(v) => pack(methods::FILE_CHANGE_OUTPUT_DELTA, v),
737            Self::ReasoningDelta(v) => pack(methods::REASONING_DELTA, v),
738            Self::Error(v) => pack(methods::ERROR, v),
739            Self::AccountRateLimitsUpdated(v) => pack(methods::ACCOUNT_RATE_LIMITS_UPDATED, v),
740            Self::McpServerStartupStatusUpdated(v) => {
741                pack(methods::MCP_SERVER_STARTUP_STATUS_UPDATED, v)
742            }
743            Self::RemoteControlStatusChanged(v) => pack(methods::REMOTE_CONTROL_STATUS_CHANGED, v),
744            Self::McpServerOauthLoginCompleted(v) => {
745                pack(methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED, v)
746            }
747            Self::FileChangePatchUpdated(v) => pack(methods::FILE_CHANGE_PATCH_UPDATED, v),
748            Self::PlanDelta(v) => pack(methods::PLAN_DELTA, v),
749            Self::TurnPlanUpdated(v) => pack(methods::TURN_PLAN_UPDATED, v),
750            Self::TurnDiffUpdated(v) => pack(methods::TURN_DIFF_UPDATED, v),
751            Self::ReasoningSummaryPartAdded(v) => pack(methods::REASONING_SUMMARY_PART_ADDED, v),
752            Self::ReasoningTextDelta(v) => pack(methods::REASONING_TEXT_DELTA, v),
753            Self::AccountLoginCompleted(v) => pack(methods::ACCOUNT_LOGIN_COMPLETED, v),
754            Self::DeprecationNotice(v) => pack(methods::DEPRECATION_NOTICE, v),
755            Self::GuardianWarning(v) => pack(methods::GUARDIAN_WARNING, v),
756            Self::Warning(v) => pack(methods::WARNING, v),
757            Self::ThreadArchived(v) => pack(methods::THREAD_ARCHIVED, v),
758            Self::ThreadClosed(v) => pack(methods::THREAD_CLOSED, v),
759            Self::ThreadDeleted(v) => pack(methods::THREAD_DELETED, v),
760            Self::ThreadUnarchived(v) => pack(methods::THREAD_UNARCHIVED, v),
761            Self::ThreadGoalCleared(v) => pack(methods::THREAD_GOAL_CLEARED, v),
762            Self::ThreadNameUpdated(v) => pack(methods::THREAD_NAME_UPDATED, v),
763            Self::ThreadAttachmentUpdated(v) => pack(methods::THREAD_ATTACHMENT_UPDATED, v),
764            Self::SkillsChanged(v) => pack(methods::SKILLS_CHANGED, v),
765            Self::FsChanged(v) => pack(methods::FS_CHANGED, v),
766            Self::ConfigWarning(v) => pack(methods::CONFIG_WARNING, v),
767            Self::AccountUpdated(v) => pack(methods::ACCOUNT_UPDATED, v),
768            Self::GatewayOAuthChanged(v) => pack(methods::ACCOUNT_GATEWAY_OAUTH_CHANGED, v),
769            Self::AppListUpdated(v) => pack(methods::APP_LIST_UPDATED, v),
770            Self::CommandExecOutputDelta(v) => pack(methods::COMMAND_EXEC_OUTPUT_DELTA, v),
771            Self::ExternalAgentConfigImportCompleted(v) => {
772                pack(methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED, v)
773            }
774            Self::FuzzyFileSearchSessionCompleted(v) => {
775                pack(methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED, v)
776            }
777            Self::FuzzyFileSearchSessionUpdated(v) => {
778                pack(methods::FUZZY_FILE_SEARCH_SESSION_UPDATED, v)
779            }
780            Self::HookCompleted(v) => pack(methods::HOOK_COMPLETED, v),
781            Self::HookStarted(v) => pack(methods::HOOK_STARTED, v),
782            Self::ItemGuardianApprovalReviewCompleted(v) => {
783                pack(methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED, v)
784            }
785            Self::ItemGuardianApprovalReviewStarted(v) => {
786                pack(methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED, v)
787            }
788            Self::TerminalInteraction(v) => {
789                pack(methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION, v)
790            }
791            Self::McpToolCallProgress(v) => pack(methods::ITEM_MCP_TOOL_CALL_PROGRESS, v),
792            Self::ModelRerouted(v) => pack(methods::MODEL_REROUTED, v),
793            Self::ModelVerification(v) => pack(methods::MODEL_VERIFICATION, v),
794            Self::ProcessExited(v) => pack(methods::PROCESS_EXITED, v),
795            Self::ProcessOutputDelta(v) => pack(methods::PROCESS_OUTPUT_DELTA, v),
796            Self::ServerRequestResolved(v) => pack(methods::SERVER_REQUEST_RESOLVED, v),
797            Self::ThreadSearchPartial(v) => pack(methods::THREAD_SEARCH_PARTIAL, v),
798            Self::ContextCompacted(v) => pack(methods::THREAD_COMPACTED, v),
799            Self::ThreadGoalUpdated(v) => pack(methods::THREAD_GOAL_UPDATED, v),
800            Self::ThreadRealtimeClosed(v) => pack(methods::THREAD_REALTIME_CLOSED, v),
801            Self::ThreadRealtimeError(v) => pack(methods::THREAD_REALTIME_ERROR, v),
802            Self::ThreadRealtimeItemAdded(v) => pack(methods::THREAD_REALTIME_ITEM_ADDED, v),
803            Self::ThreadRealtimeOutputAudioDelta(v) => {
804                pack(methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA, v)
805            }
806            Self::ThreadRealtimeSdp(v) => pack(methods::THREAD_REALTIME_SDP, v),
807            Self::ThreadRealtimeStarted(v) => pack(methods::THREAD_REALTIME_STARTED, v),
808            Self::ThreadRealtimeTranscriptDelta(v) => {
809                pack(methods::THREAD_REALTIME_TRANSCRIPT_DELTA, v)
810            }
811            Self::ThreadRealtimeTranscriptDone(v) => {
812                pack(methods::THREAD_REALTIME_TRANSCRIPT_DONE, v)
813            }
814            Self::WindowsWorldWritableWarning(v) => {
815                pack(methods::WINDOWS_WORLD_WRITABLE_WARNING, v)
816            }
817            Self::WindowsSandboxSetupCompleted(v) => {
818                pack(methods::WINDOWS_SANDBOX_SETUP_COMPLETED, v)
819            }
820            Self::ThreadSettingsUpdated(v) => pack(methods::THREAD_SETTINGS_UPDATED, v),
821            Self::TurnModerationMetadata(v) => pack(methods::TURN_MODERATION_METADATA, v),
822            Self::ExternalAgentConfigImportProgress(v) => {
823                pack(methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS, v)
824            }
825            Self::ModelSafetyBufferingUpdated(v) => {
826                pack(methods::MODEL_SAFETY_BUFFERING_UPDATED, v)
827            }
828            Self::ThreadEnvironmentConnected(v) => pack(methods::THREAD_ENVIRONMENT_CONNECTED, v),
829            Self::ThreadEnvironmentDisconnected(v) => {
830                pack(methods::THREAD_ENVIRONMENT_DISCONNECTED, v)
831            }
832            Self::Unknown { method, params } => Ok((method.clone(), params.clone())),
833        }
834    }
835}
836
837impl Serialize for Notification {
838    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
839        let (method, params) = self
840            .clone()
841            .into_envelope()
842            .map_err(serde::ser::Error::custom)?;
843        let mut env = serde_json::Map::new();
844        env.insert("method".to_string(), Value::String(method));
845        if let Some(p) = params {
846            env.insert("params".to_string(), p);
847        }
848        Value::Object(env).serialize(serializer)
849    }
850}
851
852impl<'de> Deserialize<'de> for Notification {
853    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
854        let value = Value::deserialize(deserializer)?;
855        let method = value
856            .get("method")
857            .and_then(|v| v.as_str())
858            .ok_or_else(|| serde::de::Error::missing_field("method"))?
859            .to_string();
860        let params = value.get("params").cloned();
861        Self::from_envelope(&method, params).map_err(serde::de::Error::custom)
862    }
863}
864
865/// A server-to-client request that requires a response (approval flow).
866///
867/// The wire envelope carries an `id` for response correlation; that `id` is
868/// held alongside this enum in [`ServerMessage::Request`] rather than embedded
869/// inside the variant, since responding doesn't depend on which approval-type
870/// was requested.
871#[derive(Debug, Clone)]
872pub enum ServerRequest {
873    /// `item/commandExecution/requestApproval`
874    CmdExecApproval(CommandExecutionRequestApprovalParams),
875    /// `item/fileChange/requestApproval`
876    FileChangeApproval(FileChangeRequestApprovalParams),
877    /// `item/tool/requestUserInput`
878    ToolRequestUserInput(crate::protocol::ToolRequestUserInputParams),
879    /// `mcpServer/elicitation/request`
880    McpServerElicitationRequest(crate::protocol::McpServerElicitationRequestParams),
881    /// `item/permissions/requestApproval`
882    PermissionsRequestApproval(crate::protocol::PermissionsRequestApprovalParams),
883    /// `item/tool/call`
884    ItemToolCall(crate::protocol::DynamicToolCallParams),
885    /// `account/chatgptAuthTokens/refresh`
886    ChatgptAuthTokensRefresh(crate::protocol::ChatgptAuthTokensRefreshParams),
887    /// `attestation/generate`
888    AttestationGenerate(crate::protocol::AttestationGenerateParams),
889    /// `applyPatchApproval`
890    ApplyPatchApproval(crate::protocol::ApplyPatchApprovalParams),
891    /// `execCommandApproval`
892    ExecCommandApproval(crate::protocol::ExecCommandApprovalParams),
893    /// A request method this crate version does not yet model.
894    Unknown {
895        method: String,
896        params: Option<Value>,
897    },
898}
899
900impl ServerRequest {
901    /// Return the wire `method` string for this request.
902    pub fn method(&self) -> &str {
903        match self {
904            Self::CmdExecApproval(_) => methods::CMD_EXEC_APPROVAL,
905            Self::FileChangeApproval(_) => methods::FILE_CHANGE_APPROVAL,
906            Self::ToolRequestUserInput(_) => methods::TOOL_REQUEST_USER_INPUT,
907            Self::McpServerElicitationRequest(_) => methods::MCP_SERVER_ELICITATION_REQUEST,
908            Self::PermissionsRequestApproval(_) => methods::PERMISSIONS_REQUEST_APPROVAL,
909            Self::ItemToolCall(_) => methods::ITEM_TOOL_CALL,
910            Self::ChatgptAuthTokensRefresh(_) => methods::CHATGPT_AUTH_TOKENS_REFRESH,
911            Self::AttestationGenerate(_) => methods::ATTESTATION_GENERATE,
912            Self::ApplyPatchApproval(_) => methods::APPLY_PATCH_APPROVAL,
913            Self::ExecCommandApproval(_) => methods::EXEC_COMMAND_APPROVAL,
914            Self::Unknown { method, .. } => method,
915        }
916    }
917
918    /// `true` if this request's method isn't modeled by the crate.
919    pub fn is_unknown(&self) -> bool {
920        matches!(self, Self::Unknown { .. })
921    }
922
923    /// Construct a [`ServerRequest`] from a `method` + `params` envelope.
924    pub fn from_envelope(method: &str, params: Option<Value>) -> Result<Self, serde_json::Error> {
925        let params_value = params.clone().unwrap_or(Value::Null);
926        match method {
927            methods::CMD_EXEC_APPROVAL => {
928                serde_json::from_value(params_value).map(Self::CmdExecApproval)
929            }
930            methods::FILE_CHANGE_APPROVAL => {
931                serde_json::from_value(params_value).map(Self::FileChangeApproval)
932            }
933            methods::TOOL_REQUEST_USER_INPUT => {
934                serde_json::from_value(params_value).map(Self::ToolRequestUserInput)
935            }
936            methods::MCP_SERVER_ELICITATION_REQUEST => {
937                serde_json::from_value(params_value).map(Self::McpServerElicitationRequest)
938            }
939            methods::PERMISSIONS_REQUEST_APPROVAL => {
940                serde_json::from_value(params_value).map(Self::PermissionsRequestApproval)
941            }
942            methods::ITEM_TOOL_CALL => serde_json::from_value(params_value).map(Self::ItemToolCall),
943            methods::CHATGPT_AUTH_TOKENS_REFRESH => {
944                serde_json::from_value(params_value).map(Self::ChatgptAuthTokensRefresh)
945            }
946            methods::ATTESTATION_GENERATE => {
947                serde_json::from_value(params_value).map(Self::AttestationGenerate)
948            }
949            methods::APPLY_PATCH_APPROVAL => {
950                serde_json::from_value(params_value).map(Self::ApplyPatchApproval)
951            }
952            methods::EXEC_COMMAND_APPROVAL => {
953                serde_json::from_value(params_value).map(Self::ExecCommandApproval)
954            }
955            _ => Ok(Self::Unknown {
956                method: method.to_string(),
957                params,
958            }),
959        }
960    }
961}
962
963/// A message coming from the app-server.
964///
965/// Replaces the previous loose `{ method, params }` shape with typed enums.
966/// Match on the outer variant first to distinguish notifications (no response)
967/// from requests (need [`crate::AsyncClient::respond`] /
968/// [`crate::SyncClient::respond`]).
969/// Keep variants unboxed so pattern matches and constructors stay ergonomic;
970/// the size skew comes from the generated notification payloads.
971#[allow(clippy::large_enum_variant)]
972#[derive(Debug, Clone)]
973pub enum ServerMessage {
974    /// A notification — no response required.
975    Notification(Notification),
976    /// A request — call `respond(id, ...)` on the client with the matching id.
977    Request {
978        id: RequestId,
979        request: ServerRequest,
980    },
981}
982
983impl ServerMessage {
984    /// `true` if this message is an unmodeled method (notification or request).
985    pub fn is_unknown(&self) -> bool {
986        match self {
987            Self::Notification(n) => n.is_unknown(),
988            Self::Request { request, .. } => request.is_unknown(),
989        }
990    }
991
992    /// Parse a raw app-server frame (one JSON-RPC line) into a [`ServerMessage`].
993    ///
994    /// This is the same parse path the [`AsyncClient`](crate::AsyncClient) and
995    /// [`SyncClient`](crate::SyncClient) run on incoming lines, exposed for
996    /// replay, recovery, and test fixtures that need to decode a captured frame
997    /// without a live client.
998    ///
999    /// A frame is a [`ServerMessage`] only if it is a server-initiated
1000    /// notification or request. A JSON-RPC *response* / *error* (a reply to a
1001    /// client request) is not a server message and returns
1002    /// [`Error::Protocol`](crate::Error::Protocol). Unknown methods decode to
1003    /// the `Unknown` variants rather than erroring; a modeled method whose
1004    /// `params` don't fit returns [`Error::Deserialization`](crate::Error::Deserialization)
1005    /// carrying the raw frame.
1006    pub fn from_json_str(s: &str) -> Result<Self, Error> {
1007        let msg: JsonRpcMessage = serde_json::from_str(s)
1008            .map_err(|e| Error::Deserialization(ParseError::from_line(s, e)))?;
1009        Self::from_jsonrpc(msg)
1010    }
1011
1012    /// Parse a [`serde_json::Value`] frame into a [`ServerMessage`].
1013    ///
1014    /// See [`from_json_str`](Self::from_json_str) for the parsing contract.
1015    pub fn from_value(value: Value) -> Result<Self, Error> {
1016        let msg: JsonRpcMessage = serde_json::from_value(value.clone())
1017            .map_err(|e| Error::Deserialization(ParseError::from_line(value.to_string(), e)))?;
1018        Self::from_jsonrpc(msg)
1019    }
1020
1021    fn from_jsonrpc(msg: JsonRpcMessage) -> Result<Self, Error> {
1022        match msg {
1023            JsonRpcMessage::Notification(JsonRpcNotification { method, params }) => {
1024                Notification::from_envelope(&method, params.clone())
1025                    .map(ServerMessage::Notification)
1026                    .map_err(|e| Error::Deserialization(ParseError::from_envelope(method, params, e)))
1027            }
1028            JsonRpcMessage::Request(JsonRpcRequest { id, method, params }) => {
1029                ServerRequest::from_envelope(&method, params.clone())
1030                    .map(|request| ServerMessage::Request { id, request })
1031                    .map_err(|e| Error::Deserialization(ParseError::from_envelope(method, params, e)))
1032            }
1033            JsonRpcMessage::Response(resp) => Err(Error::Protocol(format!(
1034                "frame is a JSON-RPC response (id={}), not a server-initiated message",
1035                resp.id
1036            ))),
1037            JsonRpcMessage::Error(err) => Err(Error::Protocol(format!(
1038                "frame is a JSON-RPC error response (id={}, code={}), not a server-initiated message",
1039                err.id, err.error.code
1040            ))),
1041        }
1042    }
1043}
1044
1045#[cfg(test)]
1046mod tests {
1047    use super::*;
1048
1049    #[test]
1050    fn test_notification_unknown_method_routes_to_unknown_variant() {
1051        let n = Notification::from_envelope("foo/bar", Some(serde_json::json!({"x": 1})))
1052            .expect("unknown methods do not error");
1053        match n {
1054            Notification::Unknown { method, params } => {
1055                assert_eq!(method, "foo/bar");
1056                assert_eq!(params, Some(serde_json::json!({"x": 1})));
1057            }
1058            other => panic!("expected Unknown, got {:?}", other),
1059        }
1060    }
1061
1062    #[test]
1063    fn test_notification_known_method_with_bad_params_errors() {
1064        // thread/started expects a `thread` field — wrong shape should error.
1065        let err = Notification::from_envelope("thread/started", Some(serde_json::json!({})));
1066        assert!(err.is_err());
1067    }
1068
1069    #[test]
1070    fn test_notification_round_trip_envelope() {
1071        let wire = serde_json::json!({
1072            "method": "item/agentMessage/delta",
1073            "params": {"threadId": "t1", "turnId": "u1", "itemId": "i1", "delta": "hi"},
1074        });
1075        let n: Notification = serde_json::from_value(wire.clone()).unwrap();
1076        assert!(matches!(n, Notification::AgentMessageDelta(_)));
1077        let back = serde_json::to_value(&n).unwrap();
1078        assert_eq!(back, wire);
1079    }
1080
1081    #[test]
1082    fn test_model_provider_error_round_trips_from_jsonrpc_error_data() {
1083        use crate::protocol_generated::types::ModelProviderError;
1084
1085        let wire = serde_json::json!({
1086            "code": -32600,
1087            "message": "thread was created with a different model provider",
1088            "data": {
1089                "type": "modelProviderMismatch",
1090                "modelProvider": "old-provider",
1091                "currentModelProvider": "current-provider",
1092            },
1093        });
1094        let err: crate::JsonRpcErrorData = serde_json::from_value(wire.clone()).unwrap();
1095        let data: ModelProviderError = serde_json::from_value(err.data.unwrap()).unwrap();
1096        assert_eq!(
1097            data,
1098            ModelProviderError::ModelProviderMismatch {
1099                model_provider: "old-provider".to_string(),
1100                current_model_provider: "current-provider".to_string(),
1101            }
1102        );
1103        assert_eq!(serde_json::to_value(&data).unwrap(), wire["data"]);
1104
1105        for (wire, expected) in [
1106            (
1107                serde_json::json!({
1108                    "type": "modelProviderNotConfigured",
1109                    "modelProvider": "old-provider",
1110                }),
1111                ModelProviderError::ModelProviderNotConfigured {
1112                    model_provider: "old-provider".to_string(),
1113                },
1114            ),
1115            (
1116                serde_json::json!({
1117                    "type": "modelProviderPolicyConflict",
1118                    "modelProvider": "old-provider",
1119                    "requiredModelProvider": "required-provider",
1120                }),
1121                ModelProviderError::ModelProviderPolicyConflict {
1122                    model_provider: "old-provider".to_string(),
1123                    required_model_provider: "required-provider".to_string(),
1124                },
1125            ),
1126        ] {
1127            assert_eq!(
1128                serde_json::from_value::<ModelProviderError>(wire.clone()).unwrap(),
1129                expected
1130            );
1131            assert_eq!(serde_json::to_value(&expected).unwrap(), wire);
1132        }
1133    }
1134
1135    #[test]
1136    fn test_model_provider_list_response_round_trips() {
1137        use crate::protocol_generated::types::{
1138            GatewayAuth, ModelProviderListResponse, ProviderSettings,
1139        };
1140
1141        let wire = serde_json::json!({
1142            "data": [
1143                {"id": "openai", "name": "OpenAI", "canEdit": false,
1144                 "baseUrl": null, "settings": {"type": "openai"}},
1145                {"id": "gw", "name": "Gateway", "canEdit": true,
1146                 "baseUrl": "https://gw.example",
1147                 "settings": {"type": "customGateway",
1148                              "auth": {"mode": "environmentVariable", "envKey": "GW_KEY"}}},
1149                {"id": "ext", "name": "External", "canEdit": true, "baseUrl": null,
1150                 "settings": {"type": "customGateway",
1151                              "auth": {"mode": "externallyConfigured", "envKey": null}}},
1152                {"id": "br", "name": "Bedrock", "canEdit": true, "baseUrl": null,
1153                 "settings": {"type": "bedrock", "profile": "dev", "region": null}},
1154                {"id": "vx", "name": "Vertex", "canEdit": false, "baseUrl": null,
1155                 "settings": {"type": "gcp", "projectId": "p", "location": null,
1156                              "credentialFile": "/creds.json"}},
1157            ],
1158            "defaultProviderId": "openai",
1159            "canChangeDefault": true,
1160        });
1161        let resp: ModelProviderListResponse = serde_json::from_value(wire.clone()).unwrap();
1162        assert_eq!(resp.default_provider_id, "openai");
1163        assert!(resp.can_change_default);
1164        assert_eq!(resp.data[0].settings, ProviderSettings::OpenAi);
1165        assert_eq!(
1166            resp.data[1].settings,
1167            ProviderSettings::CustomGateway {
1168                auth: GatewayAuth::EnvironmentVariable {
1169                    env_key: "GW_KEY".to_string()
1170                }
1171            }
1172        );
1173        assert_eq!(
1174            resp.data[4].settings,
1175            ProviderSettings::Gcp {
1176                project_id: Some("p".to_string()),
1177                location: None,
1178                credential_file: Some("/creds.json".to_string()),
1179            }
1180        );
1181        assert_eq!(serde_json::to_value(&resp).unwrap(), wire);
1182
1183        let none: GatewayAuth =
1184            serde_json::from_value(serde_json::json!({"mode": "none"})).unwrap();
1185        assert_eq!(none, GatewayAuth::None);
1186    }
1187
1188    #[test]
1189    fn test_model_provider_config_write_patch_round_trips() {
1190        use crate::protocol_generated::types::{
1191            BedrockProviderId, GcpProviderId, ModelProviderConfigWriteParams, ProviderSettingsPatch,
1192        };
1193
1194        // Omitted preserves, explicit null clears, a value sets.
1195        let wire = serde_json::json!({
1196            "settings": {"type": "bedrock", "providerId": "amazon-bedrock-runtime",
1197                         "region": null}
1198        });
1199        let params: ModelProviderConfigWriteParams = serde_json::from_value(wire.clone()).unwrap();
1200        assert_eq!(
1201            params.settings,
1202            ProviderSettingsPatch::Bedrock {
1203                provider_id: BedrockProviderId::AmazonBedrockRuntime,
1204                profile: None,
1205                region: Some(None),
1206            }
1207        );
1208        assert_eq!(serde_json::to_value(&params).unwrap(), wire);
1209
1210        let gcp = ProviderSettingsPatch::Gcp {
1211            provider_id: GcpProviderId::Gcp,
1212            project_id: Some(Some("p".to_string())),
1213            location: None,
1214            credential_file: Some(None),
1215        };
1216        assert_eq!(
1217            serde_json::to_value(&gcp).unwrap(),
1218            serde_json::json!({"type": "gcp", "providerId": "gcp",
1219                               "projectId": "p", "credentialFile": null})
1220        );
1221
1222        let gateway: ProviderSettingsPatch = serde_json::from_value(serde_json::json!({
1223            "type": "customGateway", "name": "GW", "baseUrl": "https://gw.example",
1224            "envKey": null
1225        }))
1226        .unwrap();
1227        assert_eq!(
1228            gateway,
1229            ProviderSettingsPatch::CustomGateway {
1230                provider_id: None,
1231                name: Some("GW".to_string()),
1232                base_url: Some(Some("https://gw.example".to_string())),
1233                env_key: Some(None),
1234            }
1235        );
1236
1237        // The name can be omitted but not cleared.
1238        assert!(serde_json::from_value::<ProviderSettingsPatch>(
1239            serde_json::json!({"type": "customGateway", "name": null})
1240        )
1241        .is_err());
1242    }
1243
1244    #[test]
1245    fn test_login_account_bedrock_provider_id_round_trips() {
1246        use crate::protocol_generated::types::{BedrockProviderId, LoginAccountParams};
1247
1248        let wire = serde_json::json!({
1249            "type": "amazonBedrock", "apiKey": "k", "region": "us-east-1",
1250            "providerId": "amazon-bedrock-runtime"
1251        });
1252        let params: LoginAccountParams = serde_json::from_value(wire.clone()).unwrap();
1253        assert_eq!(
1254            params,
1255            LoginAccountParams::AmazonBedrock {
1256                api_key: "k".to_string(),
1257                provider_id: Some(BedrockProviderId::AmazonBedrockRuntime),
1258                region: "us-east-1".to_string(),
1259            }
1260        );
1261        assert_eq!(serde_json::to_value(&params).unwrap(), wire);
1262
1263        // Omitted defaults to Bedrock Mantle and stays omitted on the wire.
1264        let keys = LoginAccountParams::AmazonBedrockAccessKeys {
1265            access_key_id: "AKIA".to_string(),
1266            provider_id: None,
1267            region: "us-west-2".to_string(),
1268            secret_access_key: "s".to_string(),
1269            session_token: None,
1270        };
1271        assert_eq!(
1272            serde_json::to_value(&keys).unwrap(),
1273            serde_json::json!({"type": "amazonBedrockAccessKeys", "accessKeyId": "AKIA",
1274                               "region": "us-west-2", "secretAccessKey": "s"})
1275        );
1276    }
1277
1278    #[test]
1279    fn test_model_provider_default_set_round_trips() {
1280        use crate::protocol_generated::types::ModelProviderDefaultSetParams;
1281
1282        let wire = serde_json::json!({"providerId": "amazon-bedrock"});
1283        let params: ModelProviderDefaultSetParams = serde_json::from_value(wire.clone()).unwrap();
1284        assert_eq!(params.provider_id, "amazon-bedrock");
1285        assert_eq!(serde_json::to_value(&params).unwrap(), wire);
1286        assert!(
1287            serde_json::from_value::<ModelProviderDefaultSetParams>(serde_json::json!({})).is_err()
1288        );
1289    }
1290
1291    #[test]
1292    fn test_thread_list_included_thread_ids_round_trips() {
1293        use crate::protocol_generated::types::ThreadListParams;
1294
1295        let params = ThreadListParams {
1296            included_thread_ids: Some(vec!["t1".to_string()]),
1297            ..Default::default()
1298        };
1299        assert_eq!(
1300            serde_json::to_value(&params).unwrap(),
1301            serde_json::json!({"includedThreadIds": ["t1"]})
1302        );
1303        assert_eq!(
1304            serde_json::to_value(ThreadListParams::default()).unwrap(),
1305            serde_json::json!({})
1306        );
1307    }
1308
1309    #[test]
1310    fn test_thread_realtime_persisted_items_round_trip() {
1311        use crate::protocol_generated::types::{
1312            ThreadRealtimeCoverage, ThreadRealtimeEntry, ThreadRealtimeHandoffMode,
1313            ThreadRealtimeItem, ThreadRealtimeItemDetail, ThreadRealtimeOrder,
1314            ThreadRealtimeSessionInputReason, ThreadRealtimeTranscriptRole,
1315        };
1316
1317        let frame = serde_json::json!({
1318            "id": "f1", "realtimeSessionId": "voice", "observedAtMs": 1_700_000_000_000_i64,
1319            "type": "frame",
1320            "channels": {"voice_transcript": {"role": "user", "text": "hi"}}
1321        });
1322        let item: ThreadRealtimeItem = serde_json::from_value(frame.clone()).unwrap();
1323        assert_eq!(item.observed_at_ms, Some(1_700_000_000_000));
1324        match &item.detail {
1325            ThreadRealtimeItemDetail::Frame { channels } => {
1326                assert_eq!(
1327                    channels.voice_transcript.role,
1328                    ThreadRealtimeTranscriptRole::User
1329                );
1330                assert_eq!(channels.voice_transcript.text, "hi");
1331            }
1332            other => panic!("expected frame, got {other:?}"),
1333        }
1334        assert_eq!(serde_json::to_value(&item).unwrap(), frame);
1335
1336        // An undated live item keeps its wire shape (no observedAtMs key).
1337        let live = serde_json::json!({
1338            "id": "speech", "realtimeSessionId": "voice", "type": "transcriptSegment",
1339            "role": "assistant", "text": "hello"
1340        });
1341        let item: ThreadRealtimeItem = serde_json::from_value(live.clone()).unwrap();
1342        assert_eq!(item.observed_at_ms, None);
1343        assert_eq!(serde_json::to_value(&item).unwrap(), live);
1344
1345        let accepted = serde_json::json!({
1346            "id": "a1", "realtimeSessionId": "voice", "type": "turnInputAccepted",
1347            "handoff_id": "h1", "turn_id": "turn1", "mode": "steer",
1348            "source_event_ids": ["e1", "e2"], "input_item_id": "in1", "input": "do it"
1349        });
1350        let entry: ThreadRealtimeEntry = serde_json::from_value(serde_json::json!({
1351            "position": 7, "item": accepted.clone()
1352        }))
1353        .unwrap();
1354        assert_eq!(entry.position, 7);
1355        match &entry.item.detail {
1356            ThreadRealtimeItemDetail::TurnInputAccepted {
1357                mode,
1358                source_event_ids,
1359                ..
1360            } => {
1361                assert_eq!(*mode, ThreadRealtimeHandoffMode::Steer);
1362                assert_eq!(source_event_ids.len(), 2);
1363            }
1364            other => panic!("expected turnInputAccepted, got {other:?}"),
1365        }
1366        assert_eq!(serde_json::to_value(&entry.item).unwrap(), accepted);
1367
1368        let saved = serde_json::json!({
1369            "id": "s1", "realtimeSessionId": "voice", "type": "sessionInputSaved",
1370            "reason": "sessionEnd", "source_event_ids": [], "input_item_id": "in2",
1371            "input": "later"
1372        });
1373        let item: ThreadRealtimeItem = serde_json::from_value(saved.clone()).unwrap();
1374        assert!(matches!(
1375            item.detail,
1376            ThreadRealtimeItemDetail::SessionInputSaved {
1377                reason: ThreadRealtimeSessionInputReason::SessionEnd,
1378                ..
1379            }
1380        ));
1381        assert_eq!(serde_json::to_value(&item).unwrap(), saved);
1382
1383        let chunk = serde_json::json!({
1384            "id": "s2", "realtimeSessionId": "voice", "type": "sessionInputSaved",
1385            "reason": "chunk", "source_event_ids": ["e1"], "input_item_id": "in3",
1386            "input": "partial"
1387        });
1388        let item: ThreadRealtimeItem = serde_json::from_value(chunk.clone()).unwrap();
1389        assert!(matches!(
1390            item.detail,
1391            ThreadRealtimeItemDetail::SessionInputSaved {
1392                reason: ThreadRealtimeSessionInputReason::Chunk,
1393                ..
1394            }
1395        ));
1396        assert_eq!(serde_json::to_value(&item).unwrap(), chunk);
1397
1398        assert_eq!(
1399            ThreadRealtimeOrder::default(),
1400            ThreadRealtimeOrder::ObservedAt
1401        );
1402        assert_eq!(
1403            serde_json::to_value(ThreadRealtimeOrder::ObservedAt).unwrap(),
1404            "observedAt"
1405        );
1406        assert_eq!(
1407            serde_json::from_value::<ThreadRealtimeCoverage>(serde_json::json!("pending")).unwrap(),
1408            ThreadRealtimeCoverage::Pending
1409        );
1410    }
1411
1412    #[test]
1413    fn test_human_command_approval_request_decodes() {
1414        use crate::protocol_generated::types::CommandExecutionApprovalKind;
1415
1416        let msg = ServerMessage::from_value(serde_json::json!({
1417            "jsonrpc": "2.0",
1418            "id": 7,
1419            "method": "item/commandExecution/requestApproval",
1420            "params": {
1421                "threadId": "t1",
1422                "turnId": "u1",
1423                "itemId": "i1",
1424                "startedAtMs": 0,
1425                "kind": "humanCommand",
1426            },
1427        }))
1428        .unwrap();
1429        match msg {
1430            ServerMessage::Request {
1431                request: ServerRequest::CmdExecApproval(params),
1432                ..
1433            } => assert_eq!(
1434                params.kind,
1435                Some(CommandExecutionApprovalKind::HumanCommand)
1436            ),
1437            other => panic!("expected CmdExecApproval, got {:?}", other),
1438        }
1439    }
1440
1441    #[test]
1442    fn test_codex_error_info_other_accepts_unknown_codes() {
1443        use crate::protocol_generated::types::CodexErrorInfo;
1444
1445        // Known codes still decode to their typed variants, tagged or not.
1446        assert_eq!(
1447            serde_json::from_value::<CodexErrorInfo>(serde_json::json!("contextWindowExceeded"))
1448                .unwrap(),
1449            CodexErrorInfo::ContextWindowExceeded
1450        );
1451        assert_eq!(
1452            serde_json::from_value::<CodexErrorInfo>(serde_json::json!("modelNotFound")).unwrap(),
1453            CodexErrorInfo::ModelNotFound
1454        );
1455        assert_eq!(
1456            serde_json::from_value::<CodexErrorInfo>(serde_json::json!(
1457                "policyCapacityUnavailable"
1458            ))
1459            .unwrap(),
1460            CodexErrorInfo::PolicyCapacityUnavailable
1461        );
1462        assert_eq!(
1463            serde_json::from_value::<CodexErrorInfo>(serde_json::json!("inferenceHookDenied"))
1464                .unwrap(),
1465            CodexErrorInfo::InferenceHookDenied
1466        );
1467        assert_eq!(
1468            serde_json::from_value::<CodexErrorInfo>(serde_json::json!("bioPolicy")).unwrap(),
1469            CodexErrorInfo::BioPolicy
1470        );
1471        assert_eq!(
1472            serde_json::from_value::<CodexErrorInfo>(
1473                serde_json::json!({"httpConnectionFailed": {"httpStatusCode": 502}})
1474            )
1475            .unwrap(),
1476            CodexErrorInfo::HttpConnectionFailed {
1477                http_status_code: Some(502)
1478            }
1479        );
1480
1481        // Unknown strings and objects fall through to `Other` instead of erroring.
1482        for unknown in [
1483            serde_json::json!("other"),
1484            serde_json::json!("someFuturePolicy"),
1485            serde_json::json!({"someFutureVariant": {"detail": 1}}),
1486        ] {
1487            assert_eq!(
1488                serde_json::from_value::<CodexErrorInfo>(unknown).unwrap(),
1489                CodexErrorInfo::Other
1490            );
1491        }
1492        assert!(serde_json::from_value::<CodexErrorInfo>(serde_json::json!(42)).is_err());
1493        assert!(serde_json::from_value::<CodexErrorInfo>(serde_json::Value::Null).is_err());
1494
1495        // `Other` always serializes back to the canonical string.
1496        assert_eq!(
1497            serde_json::to_value(CodexErrorInfo::Other).unwrap(),
1498            serde_json::json!("other")
1499        );
1500    }
1501
1502    #[test]
1503    fn test_account_updated_reason_tolerates_unknown_values() {
1504        use crate::protocol_generated::types::AccountUpdateReason;
1505
1506        let n = Notification::from_envelope(
1507            methods::ACCOUNT_UPDATED,
1508            Some(serde_json::json!({"authMode": "chatgpt", "reason": "workspaceRoutingReady"})),
1509        )
1510        .unwrap();
1511        let Notification::AccountUpdated(updated) = &n else {
1512            panic!("expected AccountUpdated, got {n:?}");
1513        };
1514        assert_eq!(
1515            updated.reason,
1516            Some(AccountUpdateReason::WorkspaceRoutingReady)
1517        );
1518
1519        assert_eq!(
1520            serde_json::from_value::<AccountUpdateReason>(serde_json::json!("somethingNew"))
1521                .unwrap(),
1522            AccountUpdateReason::Unknown
1523        );
1524        assert_eq!(
1525            serde_json::to_value(AccountUpdateReason::Unknown).unwrap(),
1526            serde_json::json!("unknown")
1527        );
1528    }
1529
1530    #[test]
1531    fn test_thread_search_partial_round_trips() {
1532        let params = serde_json::json!({
1533            "requestId": 7,
1534            "data": [{
1535                "snippet": "needle",
1536                "thread": {
1537                    "cliVersion": "0.170.0", "createdAt": 0, "cwd": "/tmp",
1538                    "ephemeral": false, "id": "t1", "modelProvider": "openai",
1539                    "preview": "p", "sessionId": "s1", "source": "cli",
1540                    "status": {"type": "idle"}, "turns": [], "updatedAt": 0
1541                }
1542            }]
1543        });
1544        let n = Notification::from_envelope(methods::THREAD_SEARCH_PARTIAL, Some(params)).unwrap();
1545        let Notification::ThreadSearchPartial(partial) = &n else {
1546            panic!("expected ThreadSearchPartial, got {n:?}");
1547        };
1548        assert_eq!(partial.data.len(), 1);
1549        assert_eq!(partial.data[0].snippet, "needle");
1550        assert_eq!(partial.data[0].thread.id, "t1");
1551        let (method, _) = n.into_envelope().unwrap();
1552        assert_eq!(method, methods::THREAD_SEARCH_PARTIAL);
1553    }
1554
1555    #[test]
1556    fn test_thread_goal_params_round_trip_origin() {
1557        use crate::protocol_generated::types::{
1558            ThreadGoalClearParams, ThreadGoalMutationOrigin, ThreadGoalSetParams,
1559        };
1560
1561        let set = ThreadGoalSetParams {
1562            thread_id: "t1".into(),
1563            objective: Some("ship it".into()),
1564            origin: Some(ThreadGoalMutationOrigin::User),
1565            ..Default::default()
1566        };
1567        assert_eq!(
1568            serde_json::to_value(&set).unwrap(),
1569            serde_json::json!({"threadId": "t1", "objective": "ship it", "origin": "user"})
1570        );
1571
1572        let clear: ThreadGoalClearParams =
1573            serde_json::from_value(serde_json::json!({"threadId": "t1", "origin": "automatic"}))
1574                .unwrap();
1575        assert_eq!(clear.origin, Some(ThreadGoalMutationOrigin::Automatic));
1576
1577        // Older callers omit `origin`; it must stay optional and absent on the wire.
1578        let bare: ThreadGoalClearParams =
1579            serde_json::from_value(serde_json::json!({"threadId": "t1"})).unwrap();
1580        assert_eq!(bare.origin, None);
1581        assert_eq!(
1582            serde_json::to_value(&bare).unwrap(),
1583            serde_json::json!({"threadId": "t1"})
1584        );
1585    }
1586
1587    #[test]
1588    fn test_thread_prediction_updated_round_trips_both_results() {
1589        use crate::protocol_generated::types::ThreadPredictionResult;
1590
1591        for (result, expected) in [
1592            (
1593                serde_json::json!({"type": "completed", "text": "next prompt"}),
1594                ThreadPredictionResult::Completed {
1595                    text: Some("next prompt".into()),
1596                },
1597            ),
1598            (
1599                serde_json::json!({"type": "completed"}),
1600                ThreadPredictionResult::Completed { text: None },
1601            ),
1602            (
1603                serde_json::json!({"type": "failed"}),
1604                ThreadPredictionResult::Failed,
1605            ),
1606        ] {
1607            let wire = serde_json::json!({
1608                "method": "thread/prediction/updated",
1609                "params": {"result": result, "sourceTurnId": "u1", "threadId": "t1"},
1610            });
1611            let n: Notification = serde_json::from_value(wire.clone()).unwrap();
1612            let Notification::ThreadPredictionUpdated(p) = &n else {
1613                panic!("expected ThreadPredictionUpdated, got {:?}", n);
1614            };
1615            assert_eq!(p.result, expected);
1616            assert_eq!(p.source_turn_id, "u1");
1617            assert_eq!(serde_json::to_value(&n).unwrap(), wire);
1618        }
1619    }
1620
1621    #[test]
1622    fn test_turn_id_from_turn_started() {
1623        // turn/started carries the id under `turn.id`.
1624        let wire = serde_json::json!({
1625            "method": "turn/started",
1626            "params": {"threadId": "t1", "turn": {"id": "turn_42", "status": "inProgress"}},
1627        });
1628        let n: Notification = serde_json::from_value(wire).unwrap();
1629        assert!(matches!(n, Notification::TurnStarted(_)));
1630        assert_eq!(n.turn_id(), Some("turn_42"));
1631    }
1632
1633    #[test]
1634    fn test_turn_id_from_delta_field() {
1635        // Streaming notifications carry a flat `turnId`.
1636        let wire = serde_json::json!({
1637            "method": "item/agentMessage/delta",
1638            "params": {"threadId": "t1", "turnId": "turn_7", "itemId": "i1", "delta": "hi"},
1639        });
1640        let n: Notification = serde_json::from_value(wire).unwrap();
1641        assert_eq!(n.turn_id(), Some("turn_7"));
1642    }
1643
1644    #[test]
1645    fn test_turn_id_none_for_non_turn_notification() {
1646        let n = Notification::from_envelope(
1647            "thread/deleted",
1648            Some(serde_json::json!({"threadId": "t1"})),
1649        )
1650        .unwrap();
1651        assert_eq!(n.turn_id(), None);
1652    }
1653
1654    #[test]
1655    fn test_thread_item_accessor() {
1656        let wire = serde_json::json!({
1657            "method": "item/started",
1658            "params": {
1659                "threadId": "t1",
1660                "turnId": "turn_1",
1661                "startedAtMs": 0,
1662                "item": {"type": "agentMessage", "id": "i1", "text": "hi"},
1663            },
1664        });
1665        let n: Notification = serde_json::from_value(wire).unwrap();
1666        assert!(n.thread_item().is_some());
1667        // A non-item notification has no thread item.
1668        let other = Notification::from_envelope(
1669            "thread/deleted",
1670            Some(serde_json::json!({"threadId": "t1"})),
1671        )
1672        .unwrap();
1673        assert!(other.thread_item().is_none());
1674    }
1675
1676    #[test]
1677    fn test_server_message_from_json_str_notification() {
1678        let line = r#"{"method":"turn/started","params":{"threadId":"t1","turn":{"id":"turn_9","status":"inProgress"}}}"#;
1679        let msg = ServerMessage::from_json_str(line).expect("parses a notification frame");
1680        match msg {
1681            ServerMessage::Notification(n) => assert_eq!(n.turn_id(), Some("turn_9")),
1682            other => panic!("expected Notification, got {other:?}"),
1683        }
1684    }
1685
1686    #[test]
1687    fn test_server_message_from_value_request() {
1688        let frame = serde_json::json!({
1689            "id": 7,
1690            "method": "execCommandApproval",
1691            "params": {
1692                "callId": "c1",
1693                "command": ["ls"],
1694                "conversationId": "th_1",
1695                "cwd": "/tmp",
1696                "parsedCmd": [],
1697            },
1698        });
1699        let msg = ServerMessage::from_value(frame).expect("parses a request frame");
1700        match msg {
1701            ServerMessage::Request { id, request } => {
1702                assert_eq!(id, RequestId::Integer(7));
1703                assert!(matches!(request, ServerRequest::ExecCommandApproval(_)));
1704            }
1705            other => panic!("expected Request, got {other:?}"),
1706        }
1707    }
1708
1709    #[test]
1710    fn test_server_message_from_json_str_rejects_response() {
1711        // A response to a client request is not a server-initiated message.
1712        let line = r#"{"id":1,"result":{"threadId":"th_abc"}}"#;
1713        let err = ServerMessage::from_json_str(line).unwrap_err();
1714        assert!(matches!(err, Error::Protocol(_)), "got: {err:?}");
1715    }
1716
1717    #[test]
1718    fn test_server_message_from_json_str_unknown_method_ok() {
1719        let line = r#"{"method":"some/future/notification","params":{"x":1}}"#;
1720        let msg = ServerMessage::from_json_str(line).unwrap();
1721        assert!(msg.is_unknown());
1722    }
1723}