1use crate::error::{Error, ParseError};
27use crate::jsonrpc::{JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, RequestId};
28use crate::protocol::{
29 methods, AccountLoginCompletedNotification, AccountRateLimitsUpdatedNotification,
30 AccountUpdatedNotification, AgentMessageDeltaNotification, AppListUpdatedNotification,
31 AuthRecoveryNotification, CommandExecOutputDeltaNotification,
32 CommandExecutionOutputDeltaNotification, CommandExecutionRequestApprovalParams,
33 ConfigWarningNotification, ContextCompactedNotification, DeprecationNoticeNotification,
34 EnvironmentConnectionNotification, ErrorNotification,
35 ExternalAgentConfigImportCompletedNotification, ExternalAgentConfigImportProgressNotification,
36 FileChangeOutputDeltaNotification, FileChangePatchUpdatedNotification,
37 FileChangeRequestApprovalParams, FsChangedNotification,
38 FuzzyFileSearchSessionCompletedNotification, FuzzyFileSearchSessionUpdatedNotification,
39 GatewayOAuthChangedNotification, GuardianWarningNotification, HookCompletedNotification,
40 HookStartedNotification, ItemCompletedNotification,
41 ItemGuardianApprovalReviewCompletedNotification, ItemGuardianApprovalReviewStartedNotification,
42 ItemStartedNotification, McpServerEventStreamNotification,
43 McpServerOauthLoginCompletedNotification, McpServerStatusUpdatedNotification,
44 McpToolCallProgressNotification, ModelReroutedNotification,
45 ModelSafetyBufferingUpdatedNotification, ModelVerificationNotification, PlanDeltaNotification,
46 ProcessExitedNotification, ProcessOutputDeltaNotification, ProjectChangedNotification,
47 ReasoningSummaryPartAddedNotification, ReasoningSummaryTextDeltaNotification,
48 ReasoningTextDeltaNotification, RemoteControlStatusChangedNotification,
49 ServerRequestResolvedNotification, SkillsChangedNotification, StrictReviewRequiredNotification,
50 TerminalInteractionNotification, ThreadArchivedNotification,
51 ThreadAttachmentUpdatedNotification, ThreadClosedNotification, ThreadDeletedNotification,
52 ThreadGoalClearedNotification, ThreadGoalUpdatedNotification, ThreadNameUpdatedNotification,
53 ThreadPredictionUpdatedNotification, ThreadProjectUpdatedNotification,
54 ThreadQueueChangedNotification, ThreadRealtimeClosedNotification,
55 ThreadRealtimeErrorNotification, ThreadRealtimeItemAddedNotification,
56 ThreadRealtimeItemCompletedNotification, ThreadRealtimeItemStartedNotification,
57 ThreadRealtimeItemTranscriptDeltaNotification, ThreadRealtimeOutputAudioDeltaNotification,
58 ThreadRealtimeSdpNotification, ThreadRealtimeStartedNotification,
59 ThreadRealtimeTranscriptDeltaNotification, ThreadRealtimeTranscriptDoneNotification,
60 ThreadRevertedNotification, ThreadSettingsUpdatedNotification, ThreadStartedNotification,
61 ThreadStatusChangedNotification, ThreadTokenUsageUpdatedNotification,
62 ThreadUnarchivedNotification, TurnCompletedNotification, TurnDiffUpdatedNotification,
63 TurnModerationMetadataNotification, TurnPlanUpdatedNotification, TurnStartedNotification,
64 WarningNotification, WindowsSandboxSetupCompletedNotification,
65 WindowsWorldWritableWarningNotification,
66};
67use serde::{Deserialize, Deserializer, Serialize, Serializer};
68use serde_json::Value;
69
70#[derive(Debug, Clone)]
76#[allow(clippy::large_enum_variant)] pub enum Notification {
78 ThreadStarted(ThreadStartedNotification),
80 ThreadStatusChanged(ThreadStatusChangedNotification),
82 ThreadTokenUsageUpdated(ThreadTokenUsageUpdatedNotification),
84 TurnStarted(TurnStartedNotification),
86 TurnCompleted(TurnCompletedNotification),
88 ItemStarted(ItemStartedNotification),
90 ItemCompleted(ItemCompletedNotification),
92 AgentMessageDelta(AgentMessageDeltaNotification),
94 CmdOutputDelta(CommandExecutionOutputDeltaNotification),
96 FileChangeOutputDelta(FileChangeOutputDeltaNotification),
98 ReasoningDelta(ReasoningSummaryTextDeltaNotification),
100 Error(ErrorNotification),
102 AccountRateLimitsUpdated(AccountRateLimitsUpdatedNotification),
104 McpServerStartupStatusUpdated(McpServerStatusUpdatedNotification),
106 RemoteControlStatusChanged(RemoteControlStatusChangedNotification),
108 McpServerOauthLoginCompleted(McpServerOauthLoginCompletedNotification),
110 FileChangePatchUpdated(FileChangePatchUpdatedNotification),
112 PlanDelta(PlanDeltaNotification),
114 TurnPlanUpdated(TurnPlanUpdatedNotification),
116 TurnDiffUpdated(TurnDiffUpdatedNotification),
118 ReasoningSummaryPartAdded(ReasoningSummaryPartAddedNotification),
120 ReasoningTextDelta(ReasoningTextDeltaNotification),
122 AccountLoginCompleted(AccountLoginCompletedNotification),
124 DeprecationNotice(DeprecationNoticeNotification),
126 GuardianWarning(GuardianWarningNotification),
128 Warning(WarningNotification),
130 ThreadArchived(ThreadArchivedNotification),
132 ThreadClosed(ThreadClosedNotification),
134 ThreadDeleted(ThreadDeletedNotification),
136 ThreadUnarchived(ThreadUnarchivedNotification),
138 ThreadGoalCleared(ThreadGoalClearedNotification),
140 ThreadNameUpdated(ThreadNameUpdatedNotification),
142 ThreadAttachmentUpdated(ThreadAttachmentUpdatedNotification),
144 SkillsChanged(SkillsChangedNotification),
146 FsChanged(FsChangedNotification),
148 ConfigWarning(ConfigWarningNotification),
150 AccountUpdated(AccountUpdatedNotification),
152 GatewayOAuthChanged(GatewayOAuthChangedNotification),
154 AppListUpdated(AppListUpdatedNotification),
156 CommandExecOutputDelta(CommandExecOutputDeltaNotification),
158 ExternalAgentConfigImportCompleted(ExternalAgentConfigImportCompletedNotification),
160 FuzzyFileSearchSessionCompleted(FuzzyFileSearchSessionCompletedNotification),
162 FuzzyFileSearchSessionUpdated(FuzzyFileSearchSessionUpdatedNotification),
164 HookCompleted(HookCompletedNotification),
166 HookStarted(HookStartedNotification),
168 ItemGuardianApprovalReviewCompleted(ItemGuardianApprovalReviewCompletedNotification),
170 ItemGuardianApprovalReviewStarted(ItemGuardianApprovalReviewStartedNotification),
172 TerminalInteraction(TerminalInteractionNotification),
174 McpToolCallProgress(McpToolCallProgressNotification),
176 ModelRerouted(ModelReroutedNotification),
178 ModelVerification(ModelVerificationNotification),
180 ProcessExited(ProcessExitedNotification),
182 ProcessOutputDelta(ProcessOutputDeltaNotification),
184 ServerRequestResolved(ServerRequestResolvedNotification),
186 ContextCompacted(ContextCompactedNotification),
188 ThreadGoalUpdated(ThreadGoalUpdatedNotification),
190 ThreadRealtimeClosed(ThreadRealtimeClosedNotification),
192 ThreadRealtimeError(ThreadRealtimeErrorNotification),
194 ThreadRealtimeItemAdded(ThreadRealtimeItemAddedNotification),
196 ThreadRealtimeOutputAudioDelta(ThreadRealtimeOutputAudioDeltaNotification),
198 ThreadRealtimeSdp(ThreadRealtimeSdpNotification),
200 ThreadRealtimeStarted(ThreadRealtimeStartedNotification),
202 ThreadRealtimeTranscriptDelta(ThreadRealtimeTranscriptDeltaNotification),
204 ThreadRealtimeTranscriptDone(ThreadRealtimeTranscriptDoneNotification),
206 WindowsWorldWritableWarning(WindowsWorldWritableWarningNotification),
208 WindowsSandboxSetupCompleted(WindowsSandboxSetupCompletedNotification),
210 ThreadSettingsUpdated(ThreadSettingsUpdatedNotification),
212 TurnModerationMetadata(TurnModerationMetadataNotification),
214 ExternalAgentConfigImportProgress(ExternalAgentConfigImportProgressNotification),
216 ModelSafetyBufferingUpdated(ModelSafetyBufferingUpdatedNotification),
218 ThreadEnvironmentConnected(EnvironmentConnectionNotification),
220 ThreadEnvironmentDisconnected(EnvironmentConnectionNotification),
222 StrictReviewRequired(StrictReviewRequiredNotification),
224 ProjectChanged(ProjectChangedNotification),
226 ThreadProjectUpdated(ThreadProjectUpdatedNotification),
228 ThreadQueueChanged(ThreadQueueChangedNotification),
230 ThreadReverted(ThreadRevertedNotification),
232 McpServerEventStream(McpServerEventStreamNotification),
234 ThreadRealtimeItemStarted(ThreadRealtimeItemStartedNotification),
236 ThreadRealtimeItemCompleted(ThreadRealtimeItemCompletedNotification),
238 ThreadRealtimeItemTranscriptDelta(ThreadRealtimeItemTranscriptDeltaNotification),
240 ModelProviderAuthRecoveryStarted(AuthRecoveryNotification),
242 ModelProviderAuthRecoveryCompleted(AuthRecoveryNotification),
244 ThreadPredictionUpdated(ThreadPredictionUpdatedNotification),
246 Unknown {
250 method: String,
251 params: Option<Value>,
252 },
253}
254
255impl Notification {
256 pub fn method(&self) -> &str {
258 match self {
259 Self::ThreadStarted(_) => methods::THREAD_STARTED,
260 Self::StrictReviewRequired(_) => methods::STRICT_REVIEW_REQUIRED,
261 Self::ProjectChanged(_) => methods::PROJECT_CHANGED,
262 Self::ThreadProjectUpdated(_) => methods::THREAD_PROJECT_UPDATED,
263 Self::ThreadQueueChanged(_) => methods::THREAD_QUEUE_CHANGED,
264 Self::ThreadReverted(_) => methods::THREAD_REVERTED,
265 Self::ThreadPredictionUpdated(_) => methods::THREAD_PREDICTION_UPDATED,
266 Self::McpServerEventStream(_) => methods::MCP_SERVER_EVENT_STREAM,
267 Self::ThreadRealtimeItemStarted(_) => methods::THREAD_REALTIME_ITEM_STARTED,
268 Self::ThreadRealtimeItemCompleted(_) => methods::THREAD_REALTIME_ITEM_COMPLETED,
269 Self::ThreadRealtimeItemTranscriptDelta(_) => {
270 methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA
271 }
272 Self::ModelProviderAuthRecoveryStarted(_) => {
273 methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED
274 }
275 Self::ModelProviderAuthRecoveryCompleted(_) => {
276 methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED
277 }
278 Self::ThreadStatusChanged(_) => methods::THREAD_STATUS_CHANGED,
279 Self::ThreadTokenUsageUpdated(_) => methods::THREAD_TOKEN_USAGE_UPDATED,
280 Self::TurnStarted(_) => methods::TURN_STARTED,
281 Self::TurnCompleted(_) => methods::TURN_COMPLETED,
282 Self::ItemStarted(_) => methods::ITEM_STARTED,
283 Self::ItemCompleted(_) => methods::ITEM_COMPLETED,
284 Self::AgentMessageDelta(_) => methods::AGENT_MESSAGE_DELTA,
285 Self::CmdOutputDelta(_) => methods::CMD_OUTPUT_DELTA,
286 Self::FileChangeOutputDelta(_) => methods::FILE_CHANGE_OUTPUT_DELTA,
287 Self::ReasoningDelta(_) => methods::REASONING_DELTA,
288 Self::Error(_) => methods::ERROR,
289 Self::AccountRateLimitsUpdated(_) => methods::ACCOUNT_RATE_LIMITS_UPDATED,
290 Self::McpServerStartupStatusUpdated(_) => methods::MCP_SERVER_STARTUP_STATUS_UPDATED,
291 Self::RemoteControlStatusChanged(_) => methods::REMOTE_CONTROL_STATUS_CHANGED,
292 Self::McpServerOauthLoginCompleted(_) => methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED,
293 Self::FileChangePatchUpdated(_) => methods::FILE_CHANGE_PATCH_UPDATED,
294 Self::PlanDelta(_) => methods::PLAN_DELTA,
295 Self::TurnPlanUpdated(_) => methods::TURN_PLAN_UPDATED,
296 Self::TurnDiffUpdated(_) => methods::TURN_DIFF_UPDATED,
297 Self::ReasoningSummaryPartAdded(_) => methods::REASONING_SUMMARY_PART_ADDED,
298 Self::ReasoningTextDelta(_) => methods::REASONING_TEXT_DELTA,
299 Self::AccountLoginCompleted(_) => methods::ACCOUNT_LOGIN_COMPLETED,
300 Self::DeprecationNotice(_) => methods::DEPRECATION_NOTICE,
301 Self::GuardianWarning(_) => methods::GUARDIAN_WARNING,
302 Self::Warning(_) => methods::WARNING,
303 Self::ThreadArchived(_) => methods::THREAD_ARCHIVED,
304 Self::ThreadClosed(_) => methods::THREAD_CLOSED,
305 Self::ThreadDeleted(_) => methods::THREAD_DELETED,
306 Self::ThreadUnarchived(_) => methods::THREAD_UNARCHIVED,
307 Self::ThreadGoalCleared(_) => methods::THREAD_GOAL_CLEARED,
308 Self::ThreadNameUpdated(_) => methods::THREAD_NAME_UPDATED,
309 Self::ThreadAttachmentUpdated(_) => methods::THREAD_ATTACHMENT_UPDATED,
310 Self::SkillsChanged(_) => methods::SKILLS_CHANGED,
311 Self::FsChanged(_) => methods::FS_CHANGED,
312 Self::ConfigWarning(_) => methods::CONFIG_WARNING,
313 Self::AccountUpdated(_) => methods::ACCOUNT_UPDATED,
314 Self::GatewayOAuthChanged(_) => methods::ACCOUNT_GATEWAY_OAUTH_CHANGED,
315 Self::AppListUpdated(_) => methods::APP_LIST_UPDATED,
316 Self::CommandExecOutputDelta(_) => methods::COMMAND_EXEC_OUTPUT_DELTA,
317 Self::ExternalAgentConfigImportCompleted(_) => {
318 methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED
319 }
320 Self::FuzzyFileSearchSessionCompleted(_) => {
321 methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED
322 }
323 Self::FuzzyFileSearchSessionUpdated(_) => methods::FUZZY_FILE_SEARCH_SESSION_UPDATED,
324 Self::HookCompleted(_) => methods::HOOK_COMPLETED,
325 Self::HookStarted(_) => methods::HOOK_STARTED,
326 Self::ItemGuardianApprovalReviewCompleted(_) => {
327 methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED
328 }
329 Self::ItemGuardianApprovalReviewStarted(_) => {
330 methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED
331 }
332 Self::TerminalInteraction(_) => methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION,
333 Self::McpToolCallProgress(_) => methods::ITEM_MCP_TOOL_CALL_PROGRESS,
334 Self::ModelRerouted(_) => methods::MODEL_REROUTED,
335 Self::ModelVerification(_) => methods::MODEL_VERIFICATION,
336 Self::ProcessExited(_) => methods::PROCESS_EXITED,
337 Self::ProcessOutputDelta(_) => methods::PROCESS_OUTPUT_DELTA,
338 Self::ServerRequestResolved(_) => methods::SERVER_REQUEST_RESOLVED,
339 Self::ContextCompacted(_) => methods::THREAD_COMPACTED,
340 Self::ThreadGoalUpdated(_) => methods::THREAD_GOAL_UPDATED,
341 Self::ThreadRealtimeClosed(_) => methods::THREAD_REALTIME_CLOSED,
342 Self::ThreadRealtimeError(_) => methods::THREAD_REALTIME_ERROR,
343 Self::ThreadRealtimeItemAdded(_) => methods::THREAD_REALTIME_ITEM_ADDED,
344 Self::ThreadRealtimeOutputAudioDelta(_) => methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA,
345 Self::ThreadRealtimeSdp(_) => methods::THREAD_REALTIME_SDP,
346 Self::ThreadRealtimeStarted(_) => methods::THREAD_REALTIME_STARTED,
347 Self::ThreadRealtimeTranscriptDelta(_) => methods::THREAD_REALTIME_TRANSCRIPT_DELTA,
348 Self::ThreadRealtimeTranscriptDone(_) => methods::THREAD_REALTIME_TRANSCRIPT_DONE,
349 Self::WindowsWorldWritableWarning(_) => methods::WINDOWS_WORLD_WRITABLE_WARNING,
350 Self::WindowsSandboxSetupCompleted(_) => methods::WINDOWS_SANDBOX_SETUP_COMPLETED,
351 Self::ThreadSettingsUpdated(_) => methods::THREAD_SETTINGS_UPDATED,
352 Self::TurnModerationMetadata(_) => methods::TURN_MODERATION_METADATA,
353 Self::ExternalAgentConfigImportProgress(_) => {
354 methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS
355 }
356 Self::ModelSafetyBufferingUpdated(_) => methods::MODEL_SAFETY_BUFFERING_UPDATED,
357 Self::ThreadEnvironmentConnected(_) => methods::THREAD_ENVIRONMENT_CONNECTED,
358 Self::ThreadEnvironmentDisconnected(_) => methods::THREAD_ENVIRONMENT_DISCONNECTED,
359 Self::Unknown { method, .. } => method,
360 }
361 }
362
363 pub fn is_unknown(&self) -> bool {
365 matches!(self, Self::Unknown { .. })
366 }
367
368 pub fn turn_id(&self) -> Option<&str> {
380 let id = match self {
381 Self::TurnStarted(n) => n.turn.id.as_str(),
382 Self::TurnCompleted(n) => n.turn.id.as_str(),
383 Self::AgentMessageDelta(n) => n.turn_id.as_str(),
384 Self::CmdOutputDelta(n) => n.turn_id.as_str(),
385 Self::FileChangeOutputDelta(n) => n.turn_id.as_str(),
386 Self::ReasoningDelta(n) => n.turn_id.as_str(),
387 Self::Error(n) => n.turn_id.as_str(),
388 Self::FileChangePatchUpdated(n) => n.turn_id.as_str(),
389 Self::PlanDelta(n) => n.turn_id.as_str(),
390 Self::TurnPlanUpdated(n) => n.turn_id.as_str(),
391 Self::TurnDiffUpdated(n) => n.turn_id.as_str(),
392 Self::TurnModerationMetadata(n) => n.turn_id.as_str(),
393 Self::ReasoningSummaryPartAdded(n) => n.turn_id.as_str(),
394 Self::ReasoningTextDelta(n) => n.turn_id.as_str(),
395 Self::ItemStarted(n) => n.turn_id.as_str(),
396 Self::ItemCompleted(n) => n.turn_id.as_str(),
397 Self::ContextCompacted(n) => n.turn_id.as_str(),
398 Self::McpToolCallProgress(n) => n.turn_id.as_str(),
399 Self::ModelRerouted(n) => n.turn_id.as_str(),
400 Self::ModelVerification(n) => n.turn_id.as_str(),
401 Self::ModelSafetyBufferingUpdated(n) => n.turn_id.as_str(),
402 Self::TerminalInteraction(n) => n.turn_id.as_str(),
403 Self::ThreadTokenUsageUpdated(n) => n.turn_id.as_str(),
404 Self::ItemGuardianApprovalReviewStarted(n) => n.turn_id.as_str(),
405 Self::ItemGuardianApprovalReviewCompleted(n) => n.turn_id.as_str(),
406 _ => return None,
407 };
408 (!id.is_empty()).then_some(id)
409 }
410
411 pub fn thread_item(&self) -> Option<&crate::protocol::ThreadItem> {
417 match self {
418 Self::ItemStarted(n) => Some(&n.item),
419 Self::ItemCompleted(n) => Some(&n.item),
420 _ => None,
421 }
422 }
423
424 pub fn from_envelope(method: &str, params: Option<Value>) -> Result<Self, serde_json::Error> {
430 let params_value = params.clone().unwrap_or(Value::Null);
431 match method {
432 methods::THREAD_STARTED => {
433 serde_json::from_value(params_value).map(Self::ThreadStarted)
434 }
435 methods::STRICT_REVIEW_REQUIRED => {
436 serde_json::from_value(params_value).map(Self::StrictReviewRequired)
437 }
438 methods::PROJECT_CHANGED => {
439 serde_json::from_value(params_value).map(Self::ProjectChanged)
440 }
441 methods::THREAD_PROJECT_UPDATED => {
442 serde_json::from_value(params_value).map(Self::ThreadProjectUpdated)
443 }
444 methods::THREAD_QUEUE_CHANGED => {
445 serde_json::from_value(params_value).map(Self::ThreadQueueChanged)
446 }
447 methods::THREAD_REVERTED => {
448 serde_json::from_value(params_value).map(Self::ThreadReverted)
449 }
450 methods::THREAD_PREDICTION_UPDATED => {
451 serde_json::from_value(params_value).map(Self::ThreadPredictionUpdated)
452 }
453 methods::MCP_SERVER_EVENT_STREAM => {
454 serde_json::from_value(params_value).map(Self::McpServerEventStream)
455 }
456 methods::THREAD_REALTIME_ITEM_STARTED => {
457 serde_json::from_value(params_value).map(Self::ThreadRealtimeItemStarted)
458 }
459 methods::THREAD_REALTIME_ITEM_COMPLETED => {
460 serde_json::from_value(params_value).map(Self::ThreadRealtimeItemCompleted)
461 }
462 methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA => {
463 serde_json::from_value(params_value).map(Self::ThreadRealtimeItemTranscriptDelta)
464 }
465 methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED => {
466 serde_json::from_value(params_value).map(Self::ModelProviderAuthRecoveryStarted)
467 }
468 methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED => {
469 serde_json::from_value(params_value).map(Self::ModelProviderAuthRecoveryCompleted)
470 }
471 methods::THREAD_STATUS_CHANGED => {
472 serde_json::from_value(params_value).map(Self::ThreadStatusChanged)
473 }
474 methods::THREAD_TOKEN_USAGE_UPDATED => {
475 serde_json::from_value(params_value).map(Self::ThreadTokenUsageUpdated)
476 }
477 methods::TURN_STARTED => serde_json::from_value(params_value).map(Self::TurnStarted),
478 methods::TURN_COMPLETED => {
479 serde_json::from_value(params_value).map(Self::TurnCompleted)
480 }
481 methods::ITEM_STARTED => serde_json::from_value(params_value).map(Self::ItemStarted),
482 methods::ITEM_COMPLETED => {
483 serde_json::from_value(params_value).map(Self::ItemCompleted)
484 }
485 methods::AGENT_MESSAGE_DELTA => {
486 serde_json::from_value(params_value).map(Self::AgentMessageDelta)
487 }
488 methods::CMD_OUTPUT_DELTA => {
489 serde_json::from_value(params_value).map(Self::CmdOutputDelta)
490 }
491 methods::FILE_CHANGE_OUTPUT_DELTA => {
492 serde_json::from_value(params_value).map(Self::FileChangeOutputDelta)
493 }
494 methods::REASONING_DELTA => {
495 serde_json::from_value(params_value).map(Self::ReasoningDelta)
496 }
497 methods::ERROR => serde_json::from_value(params_value).map(Self::Error),
498 methods::ACCOUNT_RATE_LIMITS_UPDATED => {
499 serde_json::from_value(params_value).map(Self::AccountRateLimitsUpdated)
500 }
501 methods::MCP_SERVER_STARTUP_STATUS_UPDATED => {
502 serde_json::from_value(params_value).map(Self::McpServerStartupStatusUpdated)
503 }
504 methods::REMOTE_CONTROL_STATUS_CHANGED => {
505 serde_json::from_value(params_value).map(Self::RemoteControlStatusChanged)
506 }
507 methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED => {
508 serde_json::from_value(params_value).map(Self::McpServerOauthLoginCompleted)
509 }
510 methods::FILE_CHANGE_PATCH_UPDATED => {
511 serde_json::from_value(params_value).map(Self::FileChangePatchUpdated)
512 }
513 methods::PLAN_DELTA => serde_json::from_value(params_value).map(Self::PlanDelta),
514 methods::TURN_PLAN_UPDATED => {
515 serde_json::from_value(params_value).map(Self::TurnPlanUpdated)
516 }
517 methods::TURN_DIFF_UPDATED => {
518 serde_json::from_value(params_value).map(Self::TurnDiffUpdated)
519 }
520 methods::REASONING_SUMMARY_PART_ADDED => {
521 serde_json::from_value(params_value).map(Self::ReasoningSummaryPartAdded)
522 }
523 methods::REASONING_TEXT_DELTA => {
524 serde_json::from_value(params_value).map(Self::ReasoningTextDelta)
525 }
526 methods::ACCOUNT_LOGIN_COMPLETED => {
527 serde_json::from_value(params_value).map(Self::AccountLoginCompleted)
528 }
529 methods::DEPRECATION_NOTICE => {
530 serde_json::from_value(params_value).map(Self::DeprecationNotice)
531 }
532 methods::GUARDIAN_WARNING => {
533 serde_json::from_value(params_value).map(Self::GuardianWarning)
534 }
535 methods::WARNING => serde_json::from_value(params_value).map(Self::Warning),
536 methods::THREAD_ARCHIVED => {
537 serde_json::from_value(params_value).map(Self::ThreadArchived)
538 }
539 methods::THREAD_CLOSED => serde_json::from_value(params_value).map(Self::ThreadClosed),
540 methods::THREAD_DELETED => {
541 serde_json::from_value(params_value).map(Self::ThreadDeleted)
542 }
543 methods::THREAD_UNARCHIVED => {
544 serde_json::from_value(params_value).map(Self::ThreadUnarchived)
545 }
546 methods::THREAD_GOAL_CLEARED => {
547 serde_json::from_value(params_value).map(Self::ThreadGoalCleared)
548 }
549 methods::THREAD_NAME_UPDATED => {
550 serde_json::from_value(params_value).map(Self::ThreadNameUpdated)
551 }
552 methods::THREAD_ATTACHMENT_UPDATED => {
553 serde_json::from_value(params_value).map(Self::ThreadAttachmentUpdated)
554 }
555 methods::SKILLS_CHANGED => {
556 serde_json::from_value(params_value).map(Self::SkillsChanged)
557 }
558 methods::FS_CHANGED => serde_json::from_value(params_value).map(Self::FsChanged),
559 methods::CONFIG_WARNING => {
560 serde_json::from_value(params_value).map(Self::ConfigWarning)
561 }
562 methods::ACCOUNT_UPDATED => {
563 serde_json::from_value(params_value).map(Self::AccountUpdated)
564 }
565 methods::ACCOUNT_GATEWAY_OAUTH_CHANGED => {
566 serde_json::from_value(params_value).map(Self::GatewayOAuthChanged)
567 }
568 methods::APP_LIST_UPDATED => {
569 serde_json::from_value(params_value).map(Self::AppListUpdated)
570 }
571 methods::COMMAND_EXEC_OUTPUT_DELTA => {
572 serde_json::from_value(params_value).map(Self::CommandExecOutputDelta)
573 }
574 methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED => {
575 serde_json::from_value(params_value).map(Self::ExternalAgentConfigImportCompleted)
576 }
577 methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED => {
578 serde_json::from_value(params_value).map(Self::FuzzyFileSearchSessionCompleted)
579 }
580 methods::FUZZY_FILE_SEARCH_SESSION_UPDATED => {
581 serde_json::from_value(params_value).map(Self::FuzzyFileSearchSessionUpdated)
582 }
583 methods::HOOK_COMPLETED => {
584 serde_json::from_value(params_value).map(Self::HookCompleted)
585 }
586 methods::HOOK_STARTED => serde_json::from_value(params_value).map(Self::HookStarted),
587 methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED => {
588 serde_json::from_value(params_value).map(Self::ItemGuardianApprovalReviewCompleted)
589 }
590 methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED => {
591 serde_json::from_value(params_value).map(Self::ItemGuardianApprovalReviewStarted)
592 }
593 methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION => {
594 serde_json::from_value(params_value).map(Self::TerminalInteraction)
595 }
596 methods::ITEM_MCP_TOOL_CALL_PROGRESS => {
597 serde_json::from_value(params_value).map(Self::McpToolCallProgress)
598 }
599 methods::MODEL_REROUTED => {
600 serde_json::from_value(params_value).map(Self::ModelRerouted)
601 }
602 methods::MODEL_VERIFICATION => {
603 serde_json::from_value(params_value).map(Self::ModelVerification)
604 }
605 methods::PROCESS_EXITED => {
606 serde_json::from_value(params_value).map(Self::ProcessExited)
607 }
608 methods::PROCESS_OUTPUT_DELTA => {
609 serde_json::from_value(params_value).map(Self::ProcessOutputDelta)
610 }
611 methods::SERVER_REQUEST_RESOLVED => {
612 serde_json::from_value(params_value).map(Self::ServerRequestResolved)
613 }
614 methods::THREAD_COMPACTED => {
615 serde_json::from_value(params_value).map(Self::ContextCompacted)
616 }
617 methods::THREAD_GOAL_UPDATED => {
618 serde_json::from_value(params_value).map(Self::ThreadGoalUpdated)
619 }
620 methods::THREAD_REALTIME_CLOSED => {
621 serde_json::from_value(params_value).map(Self::ThreadRealtimeClosed)
622 }
623 methods::THREAD_REALTIME_ERROR => {
624 serde_json::from_value(params_value).map(Self::ThreadRealtimeError)
625 }
626 methods::THREAD_REALTIME_ITEM_ADDED => {
627 serde_json::from_value(params_value).map(Self::ThreadRealtimeItemAdded)
628 }
629 methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA => {
630 serde_json::from_value(params_value).map(Self::ThreadRealtimeOutputAudioDelta)
631 }
632 methods::THREAD_REALTIME_SDP => {
633 serde_json::from_value(params_value).map(Self::ThreadRealtimeSdp)
634 }
635 methods::THREAD_REALTIME_STARTED => {
636 serde_json::from_value(params_value).map(Self::ThreadRealtimeStarted)
637 }
638 methods::THREAD_REALTIME_TRANSCRIPT_DELTA => {
639 serde_json::from_value(params_value).map(Self::ThreadRealtimeTranscriptDelta)
640 }
641 methods::THREAD_REALTIME_TRANSCRIPT_DONE => {
642 serde_json::from_value(params_value).map(Self::ThreadRealtimeTranscriptDone)
643 }
644 methods::WINDOWS_WORLD_WRITABLE_WARNING => {
645 serde_json::from_value(params_value).map(Self::WindowsWorldWritableWarning)
646 }
647 methods::WINDOWS_SANDBOX_SETUP_COMPLETED => {
648 serde_json::from_value(params_value).map(Self::WindowsSandboxSetupCompleted)
649 }
650 methods::THREAD_SETTINGS_UPDATED => {
651 serde_json::from_value(params_value).map(Self::ThreadSettingsUpdated)
652 }
653 methods::TURN_MODERATION_METADATA => {
654 serde_json::from_value(params_value).map(Self::TurnModerationMetadata)
655 }
656 methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS => {
657 serde_json::from_value(params_value).map(Self::ExternalAgentConfigImportProgress)
658 }
659 methods::MODEL_SAFETY_BUFFERING_UPDATED => {
660 serde_json::from_value(params_value).map(Self::ModelSafetyBufferingUpdated)
661 }
662 methods::THREAD_ENVIRONMENT_CONNECTED => {
663 serde_json::from_value(params_value).map(Self::ThreadEnvironmentConnected)
664 }
665 methods::THREAD_ENVIRONMENT_DISCONNECTED => {
666 serde_json::from_value(params_value).map(Self::ThreadEnvironmentDisconnected)
667 }
668 _ => Ok(Self::Unknown {
669 method: method.to_string(),
670 params,
671 }),
672 }
673 }
674
675 pub fn into_envelope(self) -> Result<(String, Option<Value>), serde_json::Error> {
677 fn pack<T: Serialize>(
678 method: &str,
679 v: &T,
680 ) -> Result<(String, Option<Value>), serde_json::Error> {
681 Ok((method.to_string(), Some(serde_json::to_value(v)?)))
682 }
683 match &self {
684 Self::ThreadStarted(v) => pack(methods::THREAD_STARTED, v),
685 Self::StrictReviewRequired(v) => pack(methods::STRICT_REVIEW_REQUIRED, v),
686 Self::ProjectChanged(v) => pack(methods::PROJECT_CHANGED, v),
687 Self::ThreadProjectUpdated(v) => pack(methods::THREAD_PROJECT_UPDATED, v),
688 Self::ThreadQueueChanged(v) => pack(methods::THREAD_QUEUE_CHANGED, v),
689 Self::ThreadReverted(v) => pack(methods::THREAD_REVERTED, v),
690 Self::ThreadPredictionUpdated(v) => pack(methods::THREAD_PREDICTION_UPDATED, v),
691 Self::McpServerEventStream(v) => pack(methods::MCP_SERVER_EVENT_STREAM, v),
692 Self::ThreadRealtimeItemStarted(v) => pack(methods::THREAD_REALTIME_ITEM_STARTED, v),
693 Self::ThreadRealtimeItemCompleted(v) => {
694 pack(methods::THREAD_REALTIME_ITEM_COMPLETED, v)
695 }
696 Self::ThreadRealtimeItemTranscriptDelta(v) => {
697 pack(methods::THREAD_REALTIME_ITEM_TRANSCRIPT_DELTA, v)
698 }
699 Self::ModelProviderAuthRecoveryStarted(v) => {
700 pack(methods::MODEL_PROVIDER_AUTH_RECOVERY_STARTED, v)
701 }
702 Self::ModelProviderAuthRecoveryCompleted(v) => {
703 pack(methods::MODEL_PROVIDER_AUTH_RECOVERY_COMPLETED, v)
704 }
705 Self::ThreadStatusChanged(v) => pack(methods::THREAD_STATUS_CHANGED, v),
706 Self::ThreadTokenUsageUpdated(v) => pack(methods::THREAD_TOKEN_USAGE_UPDATED, v),
707 Self::TurnStarted(v) => pack(methods::TURN_STARTED, v),
708 Self::TurnCompleted(v) => pack(methods::TURN_COMPLETED, v),
709 Self::ItemStarted(v) => pack(methods::ITEM_STARTED, v),
710 Self::ItemCompleted(v) => pack(methods::ITEM_COMPLETED, v),
711 Self::AgentMessageDelta(v) => pack(methods::AGENT_MESSAGE_DELTA, v),
712 Self::CmdOutputDelta(v) => pack(methods::CMD_OUTPUT_DELTA, v),
713 Self::FileChangeOutputDelta(v) => pack(methods::FILE_CHANGE_OUTPUT_DELTA, v),
714 Self::ReasoningDelta(v) => pack(methods::REASONING_DELTA, v),
715 Self::Error(v) => pack(methods::ERROR, v),
716 Self::AccountRateLimitsUpdated(v) => pack(methods::ACCOUNT_RATE_LIMITS_UPDATED, v),
717 Self::McpServerStartupStatusUpdated(v) => {
718 pack(methods::MCP_SERVER_STARTUP_STATUS_UPDATED, v)
719 }
720 Self::RemoteControlStatusChanged(v) => pack(methods::REMOTE_CONTROL_STATUS_CHANGED, v),
721 Self::McpServerOauthLoginCompleted(v) => {
722 pack(methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED, v)
723 }
724 Self::FileChangePatchUpdated(v) => pack(methods::FILE_CHANGE_PATCH_UPDATED, v),
725 Self::PlanDelta(v) => pack(methods::PLAN_DELTA, v),
726 Self::TurnPlanUpdated(v) => pack(methods::TURN_PLAN_UPDATED, v),
727 Self::TurnDiffUpdated(v) => pack(methods::TURN_DIFF_UPDATED, v),
728 Self::ReasoningSummaryPartAdded(v) => pack(methods::REASONING_SUMMARY_PART_ADDED, v),
729 Self::ReasoningTextDelta(v) => pack(methods::REASONING_TEXT_DELTA, v),
730 Self::AccountLoginCompleted(v) => pack(methods::ACCOUNT_LOGIN_COMPLETED, v),
731 Self::DeprecationNotice(v) => pack(methods::DEPRECATION_NOTICE, v),
732 Self::GuardianWarning(v) => pack(methods::GUARDIAN_WARNING, v),
733 Self::Warning(v) => pack(methods::WARNING, v),
734 Self::ThreadArchived(v) => pack(methods::THREAD_ARCHIVED, v),
735 Self::ThreadClosed(v) => pack(methods::THREAD_CLOSED, v),
736 Self::ThreadDeleted(v) => pack(methods::THREAD_DELETED, v),
737 Self::ThreadUnarchived(v) => pack(methods::THREAD_UNARCHIVED, v),
738 Self::ThreadGoalCleared(v) => pack(methods::THREAD_GOAL_CLEARED, v),
739 Self::ThreadNameUpdated(v) => pack(methods::THREAD_NAME_UPDATED, v),
740 Self::ThreadAttachmentUpdated(v) => pack(methods::THREAD_ATTACHMENT_UPDATED, v),
741 Self::SkillsChanged(v) => pack(methods::SKILLS_CHANGED, v),
742 Self::FsChanged(v) => pack(methods::FS_CHANGED, v),
743 Self::ConfigWarning(v) => pack(methods::CONFIG_WARNING, v),
744 Self::AccountUpdated(v) => pack(methods::ACCOUNT_UPDATED, v),
745 Self::GatewayOAuthChanged(v) => pack(methods::ACCOUNT_GATEWAY_OAUTH_CHANGED, v),
746 Self::AppListUpdated(v) => pack(methods::APP_LIST_UPDATED, v),
747 Self::CommandExecOutputDelta(v) => pack(methods::COMMAND_EXEC_OUTPUT_DELTA, v),
748 Self::ExternalAgentConfigImportCompleted(v) => {
749 pack(methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED, v)
750 }
751 Self::FuzzyFileSearchSessionCompleted(v) => {
752 pack(methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED, v)
753 }
754 Self::FuzzyFileSearchSessionUpdated(v) => {
755 pack(methods::FUZZY_FILE_SEARCH_SESSION_UPDATED, v)
756 }
757 Self::HookCompleted(v) => pack(methods::HOOK_COMPLETED, v),
758 Self::HookStarted(v) => pack(methods::HOOK_STARTED, v),
759 Self::ItemGuardianApprovalReviewCompleted(v) => {
760 pack(methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED, v)
761 }
762 Self::ItemGuardianApprovalReviewStarted(v) => {
763 pack(methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED, v)
764 }
765 Self::TerminalInteraction(v) => {
766 pack(methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION, v)
767 }
768 Self::McpToolCallProgress(v) => pack(methods::ITEM_MCP_TOOL_CALL_PROGRESS, v),
769 Self::ModelRerouted(v) => pack(methods::MODEL_REROUTED, v),
770 Self::ModelVerification(v) => pack(methods::MODEL_VERIFICATION, v),
771 Self::ProcessExited(v) => pack(methods::PROCESS_EXITED, v),
772 Self::ProcessOutputDelta(v) => pack(methods::PROCESS_OUTPUT_DELTA, v),
773 Self::ServerRequestResolved(v) => pack(methods::SERVER_REQUEST_RESOLVED, v),
774 Self::ContextCompacted(v) => pack(methods::THREAD_COMPACTED, v),
775 Self::ThreadGoalUpdated(v) => pack(methods::THREAD_GOAL_UPDATED, v),
776 Self::ThreadRealtimeClosed(v) => pack(methods::THREAD_REALTIME_CLOSED, v),
777 Self::ThreadRealtimeError(v) => pack(methods::THREAD_REALTIME_ERROR, v),
778 Self::ThreadRealtimeItemAdded(v) => pack(methods::THREAD_REALTIME_ITEM_ADDED, v),
779 Self::ThreadRealtimeOutputAudioDelta(v) => {
780 pack(methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA, v)
781 }
782 Self::ThreadRealtimeSdp(v) => pack(methods::THREAD_REALTIME_SDP, v),
783 Self::ThreadRealtimeStarted(v) => pack(methods::THREAD_REALTIME_STARTED, v),
784 Self::ThreadRealtimeTranscriptDelta(v) => {
785 pack(methods::THREAD_REALTIME_TRANSCRIPT_DELTA, v)
786 }
787 Self::ThreadRealtimeTranscriptDone(v) => {
788 pack(methods::THREAD_REALTIME_TRANSCRIPT_DONE, v)
789 }
790 Self::WindowsWorldWritableWarning(v) => {
791 pack(methods::WINDOWS_WORLD_WRITABLE_WARNING, v)
792 }
793 Self::WindowsSandboxSetupCompleted(v) => {
794 pack(methods::WINDOWS_SANDBOX_SETUP_COMPLETED, v)
795 }
796 Self::ThreadSettingsUpdated(v) => pack(methods::THREAD_SETTINGS_UPDATED, v),
797 Self::TurnModerationMetadata(v) => pack(methods::TURN_MODERATION_METADATA, v),
798 Self::ExternalAgentConfigImportProgress(v) => {
799 pack(methods::EXTERNAL_AGENT_CONFIG_IMPORT_PROGRESS, v)
800 }
801 Self::ModelSafetyBufferingUpdated(v) => {
802 pack(methods::MODEL_SAFETY_BUFFERING_UPDATED, v)
803 }
804 Self::ThreadEnvironmentConnected(v) => pack(methods::THREAD_ENVIRONMENT_CONNECTED, v),
805 Self::ThreadEnvironmentDisconnected(v) => {
806 pack(methods::THREAD_ENVIRONMENT_DISCONNECTED, v)
807 }
808 Self::Unknown { method, params } => Ok((method.clone(), params.clone())),
809 }
810 }
811}
812
813impl Serialize for Notification {
814 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
815 let (method, params) = self
816 .clone()
817 .into_envelope()
818 .map_err(serde::ser::Error::custom)?;
819 let mut env = serde_json::Map::new();
820 env.insert("method".to_string(), Value::String(method));
821 if let Some(p) = params {
822 env.insert("params".to_string(), p);
823 }
824 Value::Object(env).serialize(serializer)
825 }
826}
827
828impl<'de> Deserialize<'de> for Notification {
829 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
830 let value = Value::deserialize(deserializer)?;
831 let method = value
832 .get("method")
833 .and_then(|v| v.as_str())
834 .ok_or_else(|| serde::de::Error::missing_field("method"))?
835 .to_string();
836 let params = value.get("params").cloned();
837 Self::from_envelope(&method, params).map_err(serde::de::Error::custom)
838 }
839}
840
841#[derive(Debug, Clone)]
848pub enum ServerRequest {
849 CmdExecApproval(CommandExecutionRequestApprovalParams),
851 FileChangeApproval(FileChangeRequestApprovalParams),
853 ToolRequestUserInput(crate::protocol::ToolRequestUserInputParams),
855 McpServerElicitationRequest(crate::protocol::McpServerElicitationRequestParams),
857 PermissionsRequestApproval(crate::protocol::PermissionsRequestApprovalParams),
859 ItemToolCall(crate::protocol::DynamicToolCallParams),
861 ChatgptAuthTokensRefresh(crate::protocol::ChatgptAuthTokensRefreshParams),
863 AttestationGenerate(crate::protocol::AttestationGenerateParams),
865 ApplyPatchApproval(crate::protocol::ApplyPatchApprovalParams),
867 ExecCommandApproval(crate::protocol::ExecCommandApprovalParams),
869 Unknown {
871 method: String,
872 params: Option<Value>,
873 },
874}
875
876impl ServerRequest {
877 pub fn method(&self) -> &str {
879 match self {
880 Self::CmdExecApproval(_) => methods::CMD_EXEC_APPROVAL,
881 Self::FileChangeApproval(_) => methods::FILE_CHANGE_APPROVAL,
882 Self::ToolRequestUserInput(_) => methods::TOOL_REQUEST_USER_INPUT,
883 Self::McpServerElicitationRequest(_) => methods::MCP_SERVER_ELICITATION_REQUEST,
884 Self::PermissionsRequestApproval(_) => methods::PERMISSIONS_REQUEST_APPROVAL,
885 Self::ItemToolCall(_) => methods::ITEM_TOOL_CALL,
886 Self::ChatgptAuthTokensRefresh(_) => methods::CHATGPT_AUTH_TOKENS_REFRESH,
887 Self::AttestationGenerate(_) => methods::ATTESTATION_GENERATE,
888 Self::ApplyPatchApproval(_) => methods::APPLY_PATCH_APPROVAL,
889 Self::ExecCommandApproval(_) => methods::EXEC_COMMAND_APPROVAL,
890 Self::Unknown { method, .. } => method,
891 }
892 }
893
894 pub fn is_unknown(&self) -> bool {
896 matches!(self, Self::Unknown { .. })
897 }
898
899 pub fn from_envelope(method: &str, params: Option<Value>) -> Result<Self, serde_json::Error> {
901 let params_value = params.clone().unwrap_or(Value::Null);
902 match method {
903 methods::CMD_EXEC_APPROVAL => {
904 serde_json::from_value(params_value).map(Self::CmdExecApproval)
905 }
906 methods::FILE_CHANGE_APPROVAL => {
907 serde_json::from_value(params_value).map(Self::FileChangeApproval)
908 }
909 methods::TOOL_REQUEST_USER_INPUT => {
910 serde_json::from_value(params_value).map(Self::ToolRequestUserInput)
911 }
912 methods::MCP_SERVER_ELICITATION_REQUEST => {
913 serde_json::from_value(params_value).map(Self::McpServerElicitationRequest)
914 }
915 methods::PERMISSIONS_REQUEST_APPROVAL => {
916 serde_json::from_value(params_value).map(Self::PermissionsRequestApproval)
917 }
918 methods::ITEM_TOOL_CALL => serde_json::from_value(params_value).map(Self::ItemToolCall),
919 methods::CHATGPT_AUTH_TOKENS_REFRESH => {
920 serde_json::from_value(params_value).map(Self::ChatgptAuthTokensRefresh)
921 }
922 methods::ATTESTATION_GENERATE => {
923 serde_json::from_value(params_value).map(Self::AttestationGenerate)
924 }
925 methods::APPLY_PATCH_APPROVAL => {
926 serde_json::from_value(params_value).map(Self::ApplyPatchApproval)
927 }
928 methods::EXEC_COMMAND_APPROVAL => {
929 serde_json::from_value(params_value).map(Self::ExecCommandApproval)
930 }
931 _ => Ok(Self::Unknown {
932 method: method.to_string(),
933 params,
934 }),
935 }
936 }
937}
938
939#[allow(clippy::large_enum_variant)]
948#[derive(Debug, Clone)]
949pub enum ServerMessage {
950 Notification(Notification),
952 Request {
954 id: RequestId,
955 request: ServerRequest,
956 },
957}
958
959impl ServerMessage {
960 pub fn is_unknown(&self) -> bool {
962 match self {
963 Self::Notification(n) => n.is_unknown(),
964 Self::Request { request, .. } => request.is_unknown(),
965 }
966 }
967
968 pub fn from_json_str(s: &str) -> Result<Self, Error> {
983 let msg: JsonRpcMessage = serde_json::from_str(s)
984 .map_err(|e| Error::Deserialization(ParseError::from_line(s, e)))?;
985 Self::from_jsonrpc(msg)
986 }
987
988 pub fn from_value(value: Value) -> Result<Self, Error> {
992 let msg: JsonRpcMessage = serde_json::from_value(value.clone())
993 .map_err(|e| Error::Deserialization(ParseError::from_line(value.to_string(), e)))?;
994 Self::from_jsonrpc(msg)
995 }
996
997 fn from_jsonrpc(msg: JsonRpcMessage) -> Result<Self, Error> {
998 match msg {
999 JsonRpcMessage::Notification(JsonRpcNotification { method, params }) => {
1000 Notification::from_envelope(&method, params.clone())
1001 .map(ServerMessage::Notification)
1002 .map_err(|e| Error::Deserialization(ParseError::from_envelope(method, params, e)))
1003 }
1004 JsonRpcMessage::Request(JsonRpcRequest { id, method, params }) => {
1005 ServerRequest::from_envelope(&method, params.clone())
1006 .map(|request| ServerMessage::Request { id, request })
1007 .map_err(|e| Error::Deserialization(ParseError::from_envelope(method, params, e)))
1008 }
1009 JsonRpcMessage::Response(resp) => Err(Error::Protocol(format!(
1010 "frame is a JSON-RPC response (id={}), not a server-initiated message",
1011 resp.id
1012 ))),
1013 JsonRpcMessage::Error(err) => Err(Error::Protocol(format!(
1014 "frame is a JSON-RPC error response (id={}, code={}), not a server-initiated message",
1015 err.id, err.error.code
1016 ))),
1017 }
1018 }
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023 use super::*;
1024
1025 #[test]
1026 fn test_notification_unknown_method_routes_to_unknown_variant() {
1027 let n = Notification::from_envelope("foo/bar", Some(serde_json::json!({"x": 1})))
1028 .expect("unknown methods do not error");
1029 match n {
1030 Notification::Unknown { method, params } => {
1031 assert_eq!(method, "foo/bar");
1032 assert_eq!(params, Some(serde_json::json!({"x": 1})));
1033 }
1034 other => panic!("expected Unknown, got {:?}", other),
1035 }
1036 }
1037
1038 #[test]
1039 fn test_notification_known_method_with_bad_params_errors() {
1040 let err = Notification::from_envelope("thread/started", Some(serde_json::json!({})));
1042 assert!(err.is_err());
1043 }
1044
1045 #[test]
1046 fn test_notification_round_trip_envelope() {
1047 let wire = serde_json::json!({
1048 "method": "item/agentMessage/delta",
1049 "params": {"threadId": "t1", "turnId": "u1", "itemId": "i1", "delta": "hi"},
1050 });
1051 let n: Notification = serde_json::from_value(wire.clone()).unwrap();
1052 assert!(matches!(n, Notification::AgentMessageDelta(_)));
1053 let back = serde_json::to_value(&n).unwrap();
1054 assert_eq!(back, wire);
1055 }
1056
1057 #[test]
1058 fn test_thread_prediction_updated_round_trips_both_results() {
1059 use crate::protocol_generated::types::ThreadPredictionResult;
1060
1061 for (result, expected) in [
1062 (
1063 serde_json::json!({"type": "completed", "text": "next prompt"}),
1064 ThreadPredictionResult::Completed {
1065 text: Some("next prompt".into()),
1066 },
1067 ),
1068 (
1069 serde_json::json!({"type": "completed"}),
1070 ThreadPredictionResult::Completed { text: None },
1071 ),
1072 (
1073 serde_json::json!({"type": "failed"}),
1074 ThreadPredictionResult::Failed,
1075 ),
1076 ] {
1077 let wire = serde_json::json!({
1078 "method": "thread/prediction/updated",
1079 "params": {"result": result, "sourceTurnId": "u1", "threadId": "t1"},
1080 });
1081 let n: Notification = serde_json::from_value(wire.clone()).unwrap();
1082 let Notification::ThreadPredictionUpdated(p) = &n else {
1083 panic!("expected ThreadPredictionUpdated, got {:?}", n);
1084 };
1085 assert_eq!(p.result, expected);
1086 assert_eq!(p.source_turn_id, "u1");
1087 assert_eq!(serde_json::to_value(&n).unwrap(), wire);
1088 }
1089 }
1090
1091 #[test]
1092 fn test_turn_id_from_turn_started() {
1093 let wire = serde_json::json!({
1095 "method": "turn/started",
1096 "params": {"threadId": "t1", "turn": {"id": "turn_42", "status": "inProgress"}},
1097 });
1098 let n: Notification = serde_json::from_value(wire).unwrap();
1099 assert!(matches!(n, Notification::TurnStarted(_)));
1100 assert_eq!(n.turn_id(), Some("turn_42"));
1101 }
1102
1103 #[test]
1104 fn test_turn_id_from_delta_field() {
1105 let wire = serde_json::json!({
1107 "method": "item/agentMessage/delta",
1108 "params": {"threadId": "t1", "turnId": "turn_7", "itemId": "i1", "delta": "hi"},
1109 });
1110 let n: Notification = serde_json::from_value(wire).unwrap();
1111 assert_eq!(n.turn_id(), Some("turn_7"));
1112 }
1113
1114 #[test]
1115 fn test_turn_id_none_for_non_turn_notification() {
1116 let n = Notification::from_envelope(
1117 "thread/deleted",
1118 Some(serde_json::json!({"threadId": "t1"})),
1119 )
1120 .unwrap();
1121 assert_eq!(n.turn_id(), None);
1122 }
1123
1124 #[test]
1125 fn test_thread_item_accessor() {
1126 let wire = serde_json::json!({
1127 "method": "item/started",
1128 "params": {
1129 "threadId": "t1",
1130 "turnId": "turn_1",
1131 "startedAtMs": 0,
1132 "item": {"type": "agentMessage", "id": "i1", "text": "hi"},
1133 },
1134 });
1135 let n: Notification = serde_json::from_value(wire).unwrap();
1136 assert!(n.thread_item().is_some());
1137 let other = Notification::from_envelope(
1139 "thread/deleted",
1140 Some(serde_json::json!({"threadId": "t1"})),
1141 )
1142 .unwrap();
1143 assert!(other.thread_item().is_none());
1144 }
1145
1146 #[test]
1147 fn test_server_message_from_json_str_notification() {
1148 let line = r#"{"method":"turn/started","params":{"threadId":"t1","turn":{"id":"turn_9","status":"inProgress"}}}"#;
1149 let msg = ServerMessage::from_json_str(line).expect("parses a notification frame");
1150 match msg {
1151 ServerMessage::Notification(n) => assert_eq!(n.turn_id(), Some("turn_9")),
1152 other => panic!("expected Notification, got {other:?}"),
1153 }
1154 }
1155
1156 #[test]
1157 fn test_server_message_from_value_request() {
1158 let frame = serde_json::json!({
1159 "id": 7,
1160 "method": "execCommandApproval",
1161 "params": {
1162 "callId": "c1",
1163 "command": ["ls"],
1164 "conversationId": "th_1",
1165 "cwd": "/tmp",
1166 "parsedCmd": [],
1167 },
1168 });
1169 let msg = ServerMessage::from_value(frame).expect("parses a request frame");
1170 match msg {
1171 ServerMessage::Request { id, request } => {
1172 assert_eq!(id, RequestId::Integer(7));
1173 assert!(matches!(request, ServerRequest::ExecCommandApproval(_)));
1174 }
1175 other => panic!("expected Request, got {other:?}"),
1176 }
1177 }
1178
1179 #[test]
1180 fn test_server_message_from_json_str_rejects_response() {
1181 let line = r#"{"id":1,"result":{"threadId":"th_abc"}}"#;
1183 let err = ServerMessage::from_json_str(line).unwrap_err();
1184 assert!(matches!(err, Error::Protocol(_)), "got: {err:?}");
1185 }
1186
1187 #[test]
1188 fn test_server_message_from_json_str_unknown_method_ok() {
1189 let line = r#"{"method":"some/future/notification","params":{"x":1}}"#;
1190 let msg = ServerMessage::from_json_str(line).unwrap();
1191 assert!(msg.is_unknown());
1192 }
1193}