返回 CodeWhale
common.rs
1 #[cfg(test)]
2 use std::path::Path;
3 use std::path::PathBuf;
4
5 use crate::JSONRPCNotification;
6 use crate::JSONRPCRequest;
7 use crate::JsonSchema;
8 use crate::RequestId;
9 use crate::TS;
10 #[cfg(test)]
11 use crate::export::GeneratedSchema;
12 #[cfg(test)]
13 use crate::export::write_json_schema;
14 use crate::protocol::v1;
15 use crate::protocol::v2;
16 use codex_experimental_api_macros::ExperimentalApi;
17 use serde::Deserialize;
18 use serde::Serialize;
19 use strum_macros::Display;
20
21 /// Authentication mode for OpenAI-backed providers.
22 #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)]
23 #[serde(rename_all = "lowercase")]
24 pub enum AuthMode {
25 /// OpenAI API key provided by the caller and stored by Codex.
26 ApiKey,
27 /// ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex).
28 Chatgpt,
29 /// [UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.
30 ///
31 /// ChatGPT auth tokens are supplied by an external host app and are only
32 /// stored in memory. Token refresh must be handled by the external host app.
33 #[serde(rename = "chatgptAuthTokens")]
34 #[ts(rename = "chatgptAuthTokens")]
35 #[strum(serialize = "chatgptAuthTokens")]
36 ChatgptAuthTokens,
37 /// Backend auth supplied as request headers.
38 #[serde(rename = "headers")]
39 #[ts(rename = "headers")]
40 #[strum(serialize = "headers")]
41 Headers,
42 /// Programmatic Codex auth backed by a registered Agent Identity.
43 #[serde(rename = "agentIdentity")]
44 #[ts(rename = "agentIdentity")]
45 #[strum(serialize = "agentIdentity")]
46 AgentIdentity,
47 /// Programmatic Codex auth backed by a personal access token.
48 #[serde(rename = "personalAccessToken")]
49 #[ts(rename = "personalAccessToken")]
50 #[strum(serialize = "personalAccessToken")]
51 PersonalAccessToken,
52 /// Amazon Bedrock bearer token managed by Codex.
53 #[serde(rename = "bedrockApiKey")]
54 #[ts(rename = "bedrockApiKey")]
55 #[strum(serialize = "bedrockApiKey")]
56 BedrockApiKey,
57 /// Amazon Bedrock AWS access keys managed by Codex.
58 #[serde(rename = "bedrockAccessKeys")]
59 #[ts(rename = "bedrockAccessKeys")]
60 #[strum(serialize = "bedrockAccessKeys")]
61 BedrockAccessKeys,
62 }
63
64 impl AuthMode {
65 /// Returns whether this mode represents an authenticated human ChatGPT account.
66 pub fn has_chatgpt_account(self) -> bool {
67 match self {
68 Self::Chatgpt | Self::ChatgptAuthTokens | Self::PersonalAccessToken => true,
69 Self::ApiKey
70 | Self::Headers
71 | Self::AgentIdentity
72 | Self::BedrockApiKey
73 | Self::BedrockAccessKeys => false,
74 }
75 }
76
77 /// Returns whether this mode is backed by Codex services rather than a direct model API.
78 pub fn uses_codex_backend(self) -> bool {
79 match self {
80 Self::Chatgpt
81 | Self::ChatgptAuthTokens
82 | Self::Headers
83 | Self::AgentIdentity
84 | Self::PersonalAccessToken => true,
85 Self::ApiKey | Self::BedrockApiKey | Self::BedrockAccessKeys => false,
86 }
87 }
88 }
89
90 macro_rules! experimental_reason_expr {
91 // If a request variant is explicitly marked experimental, that reason wins.
92 (variant $variant:ident, #[experimental($reason:expr)] $params:ident $(, $inspect_params:tt)?) => {
93 Some($reason)
94 };
95 // `inspect_params: true` is used when a method is mostly stable but needs
96 // field-level gating from its params type (for example, ThreadStart).
97 (variant $variant:ident, $params:ident, true) => {
98 crate::experimental_api::ExperimentalApi::experimental_reason($params)
99 };
100 (variant $variant:ident, $params:ident $(, $inspect_params:tt)?) => {
101 None
102 };
103 }
104
105 #[cfg(test)]
106 macro_rules! experimental_method_entry {
107 (#[experimental($reason:expr)] => $wire:literal) => {
108 $wire
109 };
110 (#[experimental($reason:expr)]) => {
111 $reason
112 };
113 ($($tt:tt)*) => {
114 ""
115 };
116 }
117
118 #[cfg(test)]
119 macro_rules! experimental_type_entry {
120 (#[experimental($reason:expr)] $ty:ty) => {
121 stringify!($ty)
122 };
123 ($ty:ty) => {
124 ""
125 };
126 }
127
128 #[derive(Debug, Clone, PartialEq, Eq)]
129 pub enum ClientRequestSerializationScope {
130 Global(&'static str),
131 GlobalSharedRead(&'static str),
132 Thread { thread_id: String },
133 ThreadPath { path: PathBuf },
134 CommandExecProcess { process_id: String },
135 Process { process_handle: String },
136 FuzzyFileSearchSession { session_id: String },
137 FsWatch { watch_id: String },
138 McpOauth { server_name: String },
139 }
140
141 macro_rules! serialization_scope_expr {
142 ($actual_params:ident, None) => {
143 None
144 };
145 ($actual_params:ident, global($key:literal)) => {
146 Some(ClientRequestSerializationScope::Global($key))
147 };
148 ($actual_params:ident, global_shared_read($key:literal)) => {
149 Some(ClientRequestSerializationScope::GlobalSharedRead($key))
150 };
151 // Match one or more dot-separated fields, allowing both `params.thread_id`
152 // and nested paths like `params.start.thread_id`. The resolved ID selects
153 // the per-thread request queue, preserving ordering with other thread operations.
154 ($actual_params:ident, thread_id($params:ident . $($field:ident).+)) => {
155 Some(ClientRequestSerializationScope::Thread {
156 thread_id: $actual_params.$($field).+.clone(),
157 })
158 };
159 ($actual_params:ident, optional_thread_id($params:ident . $field:ident)) => {
160 $actual_params
161 .$field
162 .clone()
163 .map(|thread_id| ClientRequestSerializationScope::Thread { thread_id })
164 };
165 ($actual_params:ident, thread_or_path($params:ident . $thread_field:ident, $params2:ident . $path_field:ident)) => {
166 if !$actual_params.$thread_field.is_empty() {
167 Some(ClientRequestSerializationScope::Thread {
168 thread_id: $actual_params.$thread_field.clone(),
169 })
170 } else if let Some(path) = $actual_params.$path_field.clone() {
171 Some(ClientRequestSerializationScope::ThreadPath { path })
172 } else {
173 Some(ClientRequestSerializationScope::Thread {
174 thread_id: $actual_params.$thread_field.clone(),
175 })
176 }
177 };
178 ($actual_params:ident, optional_command_process_id($params:ident . $field:ident)) => {
179 $actual_params
180 .$field
181 .clone()
182 .map(|process_id| ClientRequestSerializationScope::CommandExecProcess { process_id })
183 };
184 ($actual_params:ident, command_process_id($params:ident . $field:ident)) => {
185 Some(ClientRequestSerializationScope::CommandExecProcess {
186 process_id: $actual_params.$field.clone(),
187 })
188 };
189 ($actual_params:ident, process_handle($params:ident . $field:ident)) => {
190 Some(ClientRequestSerializationScope::Process {
191 process_handle: $actual_params.$field.clone(),
192 })
193 };
194 ($actual_params:ident, fuzzy_session_id($params:ident . $field:ident)) => {
195 Some(ClientRequestSerializationScope::FuzzyFileSearchSession {
196 session_id: $actual_params.$field.clone(),
197 })
198 };
199 ($actual_params:ident, fs_watch_id($params:ident . $field:ident)) => {
200 Some(ClientRequestSerializationScope::FsWatch {
201 watch_id: $actual_params.$field.clone(),
202 })
203 };
204 ($actual_params:ident, mcp_oauth_server($params:ident . $field:ident)) => {
205 Some(ClientRequestSerializationScope::McpOauth {
206 server_name: $actual_params.$field.clone(),
207 })
208 };
209 }
210
211 /// Generates an `enum ClientRequest` where each variant is a request that the
212 /// client can send to the server. Each variant has associated `params` and
213 /// `response` types. Also generates a `export_client_responses()` function to
214 /// export all response types to TypeScript.
215 macro_rules! client_request_definitions {
216 (
217 $(
218 $(#[experimental($reason:expr)])?
219 $(#[doc = $variant_doc:literal])*
220 $variant:ident => $wire:literal {
221 params: $(#[$params_meta:meta])* $params:ty,
222 $(inspect_params: $inspect_params:tt,)?
223 serialization: $serialization:ident $( ( $($serialization_args:tt)* ) )?,
224 $(manual_payload_conversion: $manual_payload_conversion:ident,)?
225 response: $response:ty,
226 }
227 ),* $(,)?
228 ) => {
229 /// Request from the client to the server.
230 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
231 #[allow(clippy::large_enum_variant)]
232 #[serde(tag = "method", rename_all = "camelCase")]
233 pub enum ClientRequest {
234 $(
235 $(#[doc = $variant_doc])*
236 #[serde(rename = $wire)]
237 #[ts(rename = $wire)]
238 $variant {
239 #[serde(rename = "id")]
240 request_id: RequestId,
241 $(#[$params_meta])*
242 params: $params,
243 },
244 )*
245 }
246
247 impl ClientRequest {
248 pub fn id(&self) -> &RequestId {
249 match self {
250 $(Self::$variant { request_id, .. } => request_id,)*
251 }
252 }
253
254 pub const fn method_name(&self) -> &'static str {
255 match self {
256 $(Self::$variant { .. } => $wire,)*
257 }
258 }
259
260 pub fn serialization_scope(&self) -> Option<ClientRequestSerializationScope> {
261 match self {
262 $(
263 Self::$variant { params, .. } => {
264 let _ = params;
265 serialization_scope_expr!(
266 params, $serialization $( ( $($serialization_args)* ) )?
267 )
268 }
269 )*
270 }
271 }
272 }
273
274 impl TryFrom<JSONRPCRequest> for ClientRequest {
275 type Error = serde_json::Error;
276
277 fn try_from(request: JSONRPCRequest) -> Result<Self, Self::Error> {
278 let JSONRPCRequest {
279 id: request_id,
280 method,
281 params,
282 trace: _,
283 } = request;
284 let mut request = serde_json::Map::new();
285 request.insert("id".to_string(), serde_json::to_value(request_id)?);
286 request.insert("method".to_string(), serde_json::Value::String(method));
287 if let Some(params) = params {
288 request.insert("params".to_string(), params);
289 }
290 serde_json::from_value(serde_json::Value::Object(request))
291 }
292 }
293
294 /// Typed response from the server to the client.
295 #[derive(Serialize, Deserialize, Debug, Clone)]
296 #[allow(clippy::large_enum_variant)]
297 #[serde(tag = "method", rename_all = "camelCase")]
298 pub enum ClientResponse {
299 $(
300 $(#[doc = $variant_doc])*
301 #[serde(rename = $wire)]
302 $variant {
303 #[serde(rename = "id")]
304 request_id: RequestId,
305 response: $response,
306 },
307 )*
308 }
309
310 impl ClientResponse {
311 pub fn id(&self) -> &RequestId {
312 match self {
313 $(Self::$variant { request_id, .. } => request_id,)*
314 }
315 }
316
317 pub fn method(&self) -> String {
318 match self {
319 $(Self::$variant { .. } => $wire.to_string(),)*
320 }
321 }
322
323 pub fn into_jsonrpc_parts(
324 self,
325 ) -> std::result::Result<(RequestId, crate::Result), serde_json::Error> {
326 let (request_id, response) = match self {
327 $(
328 Self::$variant { request_id, response } => {
329 (request_id, ClientResponsePayload::$variant(response))
330 }
331 )*
332 };
333 serde_json::to_value(response).map(|result| (request_id, result))
334 }
335 }
336
337 #[derive(Debug, Clone, Serialize)]
338 #[serde(untagged)]
339 #[allow(clippy::large_enum_variant)]
340 pub enum ClientResponsePayload {
341 $( $variant($response), )*
342 InterruptConversation(v1::InterruptConversationResponse),
343 }
344
345 impl ClientResponsePayload {
346 pub fn into_client_response(self, request_id: RequestId) -> Option<ClientResponse> {
347 match self {
348 $(
349 Self::$variant(response) => {
350 Some(ClientResponse::$variant {
351 request_id,
352 response,
353 })
354 }
355 )*
356 Self::InterruptConversation(_) => None,
357 }
358 }
359
360 pub fn into_jsonrpc_parts(
361 self,
362 request_id: RequestId,
363 ) -> std::result::Result<(RequestId, crate::Result), serde_json::Error> {
364 self.to_jsonrpc_parts(request_id)
365 }
366
367 pub fn to_jsonrpc_parts(
368 &self,
369 request_id: RequestId,
370 ) -> std::result::Result<(RequestId, crate::Result), serde_json::Error> {
371 serde_json::to_value(self).map(|result| (request_id, result))
372 }
373 }
374
375 impl From<v1::InterruptConversationResponse> for ClientResponsePayload {
376 fn from(response: v1::InterruptConversationResponse) -> Self {
377 Self::InterruptConversation(response)
378 }
379 }
380
381 $(
382 client_response_payload_from_impl!(
383 $variant,
384 $response
385 $(, $manual_payload_conversion)?
386 );
387 )*
388
389 impl crate::experimental_api::ExperimentalApi for ClientRequest {
390 fn experimental_reason(&self) -> Option<&'static str> {
391 match self {
392 $(
393 Self::$variant { params: _params, .. } => {
394 experimental_reason_expr!(
395 variant $variant,
396 $(#[experimental($reason)])?
397 _params
398 $(, $inspect_params)?
399 )
400 }
401 )*
402 }
403 }
404 }
405
406 #[cfg(test)]
407 pub(crate) const EXPERIMENTAL_CLIENT_METHODS: &[&str] = &[
408 $(
409 experimental_method_entry!($(#[experimental($reason)])? => $wire),
410 )*
411 ];
412 #[cfg(test)]
413 pub(crate) const EXPERIMENTAL_CLIENT_METHOD_PARAM_TYPES: &[&str] = &[
414 $(
415 experimental_type_entry!($(#[experimental($reason)])? $params),
416 )*
417 ];
418 #[cfg(test)]
419 pub(crate) const EXPERIMENTAL_CLIENT_METHOD_RESPONSE_TYPES: &[&str] = &[
420 $(
421 experimental_type_entry!($(#[experimental($reason)])? $response),
422 )*
423 ];
424
425 #[cfg(test)]
426 pub fn export_client_responses(
427 out_dir: &::std::path::Path,
428 ) -> ::std::result::Result<(), ::ts_rs::ExportError> {
429 $(
430 <$response as ::ts_rs::TS>::export_all_to(out_dir)?;
431 )*
432 Ok(())
433 }
434
435 #[cfg(test)]
436 pub(crate) fn visit_client_response_types(v: &mut impl ::ts_rs::TypeVisitor) {
437 $(
438 v.visit::<$response>();
439 )*
440 }
441
442 #[cfg(test)]
443 #[allow(clippy::vec_init_then_push)]
444 pub fn export_client_response_schemas(
445 out_dir: &::std::path::Path,
446 ) -> ::anyhow::Result<Vec<GeneratedSchema>> {
447 let mut schemas = Vec::new();
448 $(
449 schemas.push(write_json_schema::<$response>(out_dir, stringify!($response))?);
450 )*
451 Ok(schemas)
452 }
453
454 #[cfg(test)]
455 #[allow(clippy::vec_init_then_push)]
456 pub fn export_client_param_schemas(
457 out_dir: &::std::path::Path,
458 ) -> ::anyhow::Result<Vec<GeneratedSchema>> {
459 let mut schemas = Vec::new();
460 $(
461 schemas.push(write_json_schema::<$params>(out_dir, stringify!($params))?);
462 )*
463 Ok(schemas)
464 }
465 };
466 }
467
468 macro_rules! client_response_payload_from_impl {
469 ($variant:ident, $response:ty) => {
470 impl From<$response> for ClientResponsePayload {
471 fn from(response: $response) -> Self {
472 Self::$variant(response)
473 }
474 }
475 };
476 ($variant:ident, $response:ty, manual) => {};
477 }
478
479 /// Preserve explicit `undefined` accepted by the original stable usage request.
480 ///
481 /// A Rust-based TypeScript proxy retains dependency discovery; a raw `#[ts(type = ...)]`
482 /// override would silently omit the generated params import and schema fixture.
483 #[allow(dead_code)]
484 #[derive(TS)]
485 #[ts(untagged)]
486 enum GetAccountTokenUsageParamsTypeScript {
487 Params(v2::GetAccountTokenUsageParams),
488 #[ts(type = "undefined")]
489 Undefined,
490 }
491
492 /// Preserve omitted/undefined params while exporting the new usage capability type.
493 #[allow(dead_code)]
494 #[derive(TS)]
495 #[ts(untagged)]
496 enum GetAccountRateLimitsParamsTypeScript {
497 Params(v2::GetAccountRateLimitsParams),
498 #[ts(type = "undefined")]
499 Undefined,
500 }
501
502 client_request_definitions! {
503 Initialize => "initialize" {
504 params: v1::InitializeParams,
505 serialization: None,
506 response: v1::InitializeResponse,
507 },
508
509 #[experimental("server/diagnostics")]
510 /// Read content-free, process-local diagnostics.
511 ServerDiagnostics => "server/diagnostics" {
512 params: v2::ServerDiagnosticsParams,
513 serialization: None,
514 response: v2::ServerDiagnosticsResponse,
515 },
516
517 #[experimental("userVerification/status")]
518 UserVerificationStatus => "userVerification/status" {
519 params: v2::UserVerificationStatusParams,
520 serialization: None,
521 response: v2::UserVerificationStatusResponse,
522 },
523
524 #[experimental("userVerification/enroll")]
525 UserVerificationEnroll => "userVerification/enroll" {
526 params: v2::UserVerificationEnrollParams,
527 serialization: None,
528 response: v2::UserVerificationEnrollResponse,
529 },
530
531 #[experimental("userVerification/delete")]
532 UserVerificationDelete => "userVerification/delete" {
533 params: v2::UserVerificationDeleteParams,
534 serialization: None,
535 response: v2::UserVerificationDeleteResponse,
536 },
537
538 #[experimental("userVerification/verify")]
539 UserVerificationVerify => "userVerification/verify" {
540 params: v2::UserVerificationVerifyParams,
541 serialization: None,
542 response: v2::UserVerificationVerifyResponse,
543 },
544
545 #[experimental("userVerification/cancel")]
546 UserVerificationCancel => "userVerification/cancel" {
547 params: v2::UserVerificationCancelParams,
548 serialization: None,
549 response: v2::UserVerificationCancelResponse,
550 },
551
552 /// NEW APIs
553 // Thread lifecycle
554 // Uses `inspect_params` because only some fields are experimental.
555 ThreadStart => "thread/start" {
556 params: v2::ThreadStartParams,
557 inspect_params: true,
558 serialization: None,
559 response: v2::ThreadStartResponse,
560 },
561 ThreadResume => "thread/resume" {
562 params: v2::ThreadResumeParams,
563 inspect_params: true,
564 serialization: thread_or_path(params.thread_id, params.path),
565 response: v2::ThreadResumeResponse,
566 },
567 ThreadFork => "thread/fork" {
568 params: v2::ThreadForkParams,
569 inspect_params: true,
570 serialization: thread_or_path(params.thread_id, params.path),
571 response: v2::ThreadForkResponse,
572 },
573 #[experimental("thread/sample")]
574 ThreadSample => "thread/sample" {
575 params: v2::ThreadSampleParams,
576 // Waiting for a sample must not block requests on its parent thread.
577 serialization: None,
578 response: v2::ThreadSampleResponse,
579 },
580 #[experimental("thread/sample/cancel")]
581 ThreadSampleCancel => "thread/sample/cancel" {
582 params: v2::ThreadSampleCancelParams,
583 serialization: None,
584 response: v2::ThreadSampleCancelResponse,
585 },
586 ThreadArchive => "thread/archive" {
587 params: v2::ThreadArchiveParams,
588 serialization: thread_id(params.thread_id),
589 response: v2::ThreadArchiveResponse,
590 },
591 ThreadDelete => "thread/delete" {
592 params: v2::ThreadDeleteParams,
593 serialization: thread_id(params.thread_id),
594 response: v2::ThreadDeleteResponse,
595 },
596 ThreadUnsubscribe => "thread/unsubscribe" {
597 params: v2::ThreadUnsubscribeParams,
598 serialization: thread_id(params.thread_id),
599 response: v2::ThreadUnsubscribeResponse,
600 },
601 #[experimental("thread/increment_elicitation")]
602 /// Increment the thread-local out-of-band elicitation counter.
603 ///
604 /// This is used by external helpers to pause timeout accounting while a user
605 /// approval or other elicitation is pending outside the app-server request flow.
606 ThreadIncrementElicitation => "thread/increment_elicitation" {
607 params: v2::ThreadIncrementElicitationParams,
608 serialization: thread_id(params.thread_id),
609 response: v2::ThreadIncrementElicitationResponse,
610 },
611 #[experimental("thread/decrement_elicitation")]
612 /// Decrement the thread-local out-of-band elicitation counter.
613 ///
614 /// When the count reaches zero, timeout accounting resumes for the thread.
615 ThreadDecrementElicitation => "thread/decrement_elicitation" {
616 params: v2::ThreadDecrementElicitationParams,
617 serialization: thread_id(params.thread_id),
618 response: v2::ThreadDecrementElicitationResponse,
619 },
620 ThreadSetName => "thread/name/set" {
621 params: v2::ThreadSetNameParams,
622 serialization: thread_id(params.thread_id),
623 response: v2::ThreadSetNameResponse,
624 },
625 #[experimental("thread/prediction/request")]
626 ThreadPredictionRequest => "thread/prediction/request" {
627 params: v2::ThreadPredictionRequestParams,
628 serialization: thread_id(params.thread_id),
629 response: v2::ThreadPredictionRequestResponse,
630 },
631 ThreadGoalSet => "thread/goal/set" {
632 params: v2::ThreadGoalSetParams,
633 serialization: thread_id(params.thread_id),
634 response: v2::ThreadGoalSetResponse,
635 },
636 ThreadGoalGet => "thread/goal/get" {
637 params: v2::ThreadGoalGetParams,
638 serialization: thread_id(params.thread_id),
639 response: v2::ThreadGoalGetResponse,
640 },
641 ThreadGoalClear => "thread/goal/clear" {
642 params: v2::ThreadGoalClearParams,
643 serialization: thread_id(params.thread_id),
644 response: v2::ThreadGoalClearResponse,
645 },
646 #[experimental("thread/queue/add")]
647 ThreadQueueAdd => "thread/queue/add" {
648 params: v2::ThreadQueueAddParams,
649 serialization: thread_id(params.thread_id),
650 response: v2::ThreadQueueAddResponse,
651 },
652 #[experimental("thread/queue/list")]
653 ThreadQueueList => "thread/queue/list" {
654 params: v2::ThreadQueueListParams,
655 serialization: thread_id(params.thread_id),
656 response: v2::ThreadQueueListResponse,
657 },
658 #[experimental("thread/queue/update")]
659 ThreadQueueUpdate => "thread/queue/update" {
660 params: v2::ThreadQueueUpdateParams,
661 serialization: thread_id(params.thread_id),
662 response: v2::ThreadQueueUpdateResponse,
663 },
664 #[experimental("thread/queue/delete")]
665 ThreadQueueDelete => "thread/queue/delete" {
666 params: v2::ThreadQueueDeleteParams,
667 serialization: thread_id(params.thread_id),
668 response: v2::ThreadQueueDeleteResponse,
669 },
670 #[experimental("thread/queue/reorder")]
671 ThreadQueueReorder => "thread/queue/reorder" {
672 params: v2::ThreadQueueReorderParams,
673 serialization: thread_id(params.thread_id),
674 response: v2::ThreadQueueReorderResponse,
675 },
676 #[experimental("thread/queue/start")]
677 ThreadQueueStart => "thread/queue/start" {
678 params: v2::ThreadQueueStartParams,
679 serialization: thread_id(params.thread_id),
680 response: v2::ThreadQueueStartResponse,
681 },
682 ThreadMetadataUpdate => "thread/metadata/update" {
683 params: v2::ThreadMetadataUpdateParams,
684 inspect_params: true,
685 serialization: thread_id(params.thread_id),
686 response: v2::ThreadMetadataUpdateResponse,
687 },
688 ThreadAttachmentAdd => "thread/attachment/add" {
689 params: v2::ThreadAttachmentAddParams,
690 serialization: thread_id(params.thread_id),
691 response: v2::ThreadAttachmentAddResponse,
692 },
693 ThreadAttachmentList => "thread/attachment/list" {
694 params: v2::ThreadAttachmentListParams,
695 serialization: None,
696 response: v2::ThreadAttachmentListResponse,
697 },
698 ThreadAttachmentOwnerList => "thread/attachmentOwner/list" {
699 params: v2::ThreadAttachmentOwnerListParams,
700 serialization: None,
701 response: v2::ThreadAttachmentOwnerListResponse,
702 },
703 ThreadAttachmentRemove => "thread/attachment/remove" {
704 params: v2::ThreadAttachmentRemoveParams,
705 serialization: thread_id(params.thread_id),
706 response: v2::ThreadAttachmentRemoveResponse,
707 },
708 ThreadSectionMove => "thread/section/move" {
709 params: v2::ThreadSectionMoveParams,
710 serialization: thread_id(params.thread_id),
711 response: v2::ThreadSectionMoveResponse,
712 },
713 #[experimental("thread/settings/update")]
714 ThreadSettingsUpdate => "thread/settings/update" {
715 params: v2::ThreadSettingsUpdateParams,
716 inspect_params: true,
717 serialization: thread_id(params.thread_id),
718 response: v2::ThreadSettingsUpdateResponse,
719 },
720 #[experimental("thread/memoryMode/set")]
721 ThreadMemoryModeSet => "thread/memoryMode/set" {
722 params: v2::ThreadMemoryModeSetParams,
723 serialization: thread_id(params.thread_id),
724 response: v2::ThreadMemoryModeSetResponse,
725 },
726 #[experimental("thread/memory/read")]
727 ThreadMemoryRead => "thread/memory/read" {
728 params: v2::ThreadMemoryReadParams,
729 serialization: thread_id(params.thread_id),
730 response: v2::ThreadMemoryReadResponse,
731 },
732 #[experimental("memory/status")]
733 MemoryStatus => "memory/status" {
734 params: v2::MemoryStatusParams,
735 serialization: global("memory"),
736 response: v2::MemoryStatusResponse,
737 },
738 #[experimental("memory/reset")]
739 MemoryReset => "memory/reset" {
740 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
741 serialization: global("memory"),
742 response: v2::MemoryResetResponse,
743 },
744 #[experimental("rollout/compress")]
745 /// Start a best-effort background compression pass for cold local rollouts.
746 RolloutCompress => "rollout/compress" {
747 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
748 serialization: None,
749 response: v2::RolloutCompressResponse,
750 },
751 ThreadUnarchive => "thread/unarchive" {
752 params: v2::ThreadUnarchiveParams,
753 serialization: thread_id(params.thread_id),
754 response: v2::ThreadUnarchiveResponse,
755 },
756 ThreadCompactStart => "thread/compact/start" {
757 params: v2::ThreadCompactStartParams,
758 serialization: thread_id(params.thread_id),
759 response: v2::ThreadCompactStartResponse,
760 },
761 ThreadShellCommand => "thread/shellCommand" {
762 params: v2::ThreadShellCommandParams,
763 serialization: thread_id(params.thread_id),
764 response: v2::ThreadShellCommandResponse,
765 },
766 ThreadApproveGuardianDeniedAction => "thread/approveGuardianDeniedAction" {
767 params: v2::ThreadApproveGuardianDeniedActionParams,
768 serialization: thread_id(params.thread_id),
769 response: v2::ThreadApproveGuardianDeniedActionResponse,
770 },
771 #[experimental("thread/backgroundTerminals/clean")]
772 ThreadBackgroundTerminalsClean => "thread/backgroundTerminals/clean" {
773 params: v2::ThreadBackgroundTerminalsCleanParams,
774 serialization: thread_id(params.thread_id),
775 response: v2::ThreadBackgroundTerminalsCleanResponse,
776 },
777 #[experimental("thread/backgroundTerminals/list")]
778 ThreadBackgroundTerminalsList => "thread/backgroundTerminals/list" {
779 params: v2::ThreadBackgroundTerminalsListParams,
780 serialization: thread_id(params.thread_id),
781 response: v2::ThreadBackgroundTerminalsListResponse,
782 },
783 #[experimental("thread/backgroundTerminals/terminate")]
784 ThreadBackgroundTerminalsTerminate => "thread/backgroundTerminals/terminate" {
785 params: v2::ThreadBackgroundTerminalsTerminateParams,
786 serialization: thread_id(params.thread_id),
787 response: v2::ThreadBackgroundTerminalsTerminateResponse,
788 },
789 ThreadRevert => "thread/revert" {
790 params: v2::ThreadRevertParams,
791 serialization: thread_id(params.thread_id),
792 response: v2::ThreadRevertResponse,
793 },
794 ThreadList => "thread/list" {
795 params: v2::ThreadListParams,
796 inspect_params: true,
797 serialization: None,
798 response: v2::ThreadListResponse,
799 },
800 #[experimental("project/list")]
801 ProjectList => "project/list" {
802 params: v2::ProjectListParams,
803 serialization: global_shared_read("projects"),
804 response: v2::ProjectListResponse,
805 },
806 #[experimental("project/read")]
807 ProjectRead => "project/read" {
808 params: v2::ProjectReadParams,
809 serialization: global_shared_read("projects"),
810 response: v2::ProjectReadResponse,
811 },
812 #[experimental("project/create")]
813 ProjectCreate => "project/create" {
814 params: v2::ProjectCreateParams,
815 serialization: global("projects"),
816 response: v2::ProjectCreateResponse,
817 },
818 #[experimental("project/import")]
819 ProjectImport => "project/import" {
820 params: v2::ProjectImportParams,
821 serialization: global("projects"),
822 response: v2::ProjectImportResponse,
823 },
824 #[experimental("project/update")]
825 ProjectUpdate => "project/update" {
826 params: v2::ProjectUpdateParams,
827 serialization: global("projects"),
828 response: v2::ProjectUpdateResponse,
829 },
830 #[experimental("project/move")]
831 ProjectMove => "project/move" {
832 params: v2::ProjectMoveParams,
833 serialization: global("projects"),
834 response: v2::ProjectMoveResponse,
835 },
836 #[experimental("project/delete")]
837 ProjectDelete => "project/delete" {
838 params: v2::ProjectDeleteParams,
839 serialization: global("projects"),
840 response: v2::ProjectDeleteResponse,
841 },
842 ThreadSectionList => "threadSection/list" {
843 params: v2::ThreadSectionListParams,
844 serialization: global_shared_read("thread-sections"),
845 response: v2::ThreadSectionListResponse,
846 },
847 ThreadSectionCreate => "threadSection/create" {
848 params: v2::ThreadSectionCreateParams,
849 serialization: global("thread-sections"),
850 response: v2::ThreadSectionCreateResponse,
851 },
852 ThreadSectionUpdate => "threadSection/update" {
853 params: v2::ThreadSectionUpdateParams,
854 serialization: global("thread-sections"),
855 response: v2::ThreadSectionUpdateResponse,
856 },
857 ThreadSectionDelete => "threadSection/delete" {
858 params: v2::ThreadSectionDeleteParams,
859 serialization: global("thread-sections"),
860 response: v2::ThreadSectionDeleteResponse,
861 },
862 #[experimental("thread/search")]
863 ThreadSearch => "thread/search" {
864 params: v2::ThreadSearchParams,
865 serialization: None,
866 response: v2::ThreadSearchResponse,
867 },
868 #[experimental("thread/searchOccurrences")]
869 ThreadSearchOccurrences => "thread/searchOccurrences" {
870 params: v2::ThreadSearchOccurrencesParams,
871 // Explicitly concurrent: this reads persisted paginated history.
872 serialization: None,
873 response: v2::ThreadSearchOccurrencesResponse,
874 },
875 ThreadLoadedList => "thread/loaded/list" {
876 params: v2::ThreadLoadedListParams,
877 serialization: None,
878 response: v2::ThreadLoadedListResponse,
879 },
880 ThreadRead => "thread/read" {
881 params: v2::ThreadReadParams,
882 serialization: thread_id(params.thread_id),
883 response: v2::ThreadReadResponse,
884 },
885 #[experimental("thread/readState/update")]
886 ThreadReadStateUpdate => "thread/readState/update" {
887 params: v2::ThreadReadStateUpdateParams,
888 serialization: thread_id(params.thread_id),
889 response: v2::ThreadReadStateUpdateResponse,
890 },
891 ThreadTurnsList => "thread/turns/list" {
892 params: v2::ThreadTurnsListParams,
893 // Explicitly concurrent: this primarily reads append-only rollout storage.
894 serialization: None,
895 response: v2::ThreadTurnsListResponse,
896 },
897 ThreadItemsList => "thread/items/list" {
898 params: v2::ThreadItemsListParams,
899 // Explicitly concurrent: this primarily reads append-only rollout storage.
900 serialization: None,
901 response: v2::ThreadItemsListResponse,
902 },
903 #[experimental("thread/items/read")]
904 ThreadItemsRead => "thread/items/read" {
905 params: v2::ThreadItemsReadParams,
906 // Explicitly concurrent: this primarily reads append-only rollout storage.
907 serialization: None,
908 response: v2::ThreadItemsReadResponse,
909 },
910 /// Append raw Responses API items to the thread history without starting a user turn.
911 ThreadInjectItems => "thread/inject_items" {
912 params: v2::ThreadInjectItemsParams,
913 serialization: thread_id(params.thread_id),
914 response: v2::ThreadInjectItemsResponse,
915 },
916 SkillsList => "skills/list" {
917 params: v2::SkillsListParams,
918 serialization: global_shared_read("config"),
919 response: v2::SkillsListResponse,
920 },
921 SkillsExtraRootsSet => "skills/extraRoots/set" {
922 params: v2::SkillsExtraRootsSetParams,
923 serialization: global("config"),
924 response: v2::SkillsExtraRootsSetResponse,
925 },
926 HooksList => "hooks/list" {
927 params: v2::HooksListParams,
928 serialization: global_shared_read("config"),
929 response: v2::HooksListResponse,
930 },
931 MarketplaceAdd => "marketplace/add" {
932 params: v2::MarketplaceAddParams,
933 serialization: global("config"),
934 response: v2::MarketplaceAddResponse,
935 },
936 MarketplaceRemove => "marketplace/remove" {
937 params: v2::MarketplaceRemoveParams,
938 serialization: global("config"),
939 response: v2::MarketplaceRemoveResponse,
940 },
941 MarketplaceUpgrade => "marketplace/upgrade" {
942 params: v2::MarketplaceUpgradeParams,
943 serialization: global("config"),
944 response: v2::MarketplaceUpgradeResponse,
945 },
946 PluginList => "plugin/list" {
947 params: v2::PluginListParams,
948 serialization: None,
949 response: v2::PluginListResponse,
950 },
951 #[experimental("plugin/search")]
952 PluginSearch => "plugin/search" {
953 params: v2::PluginSearchParams,
954 serialization: None,
955 response: v2::PluginSearchResponse,
956 },
957 PluginInstalled => "plugin/installed" {
958 params: v2::PluginInstalledParams,
959 serialization: None,
960 response: v2::PluginInstalledResponse,
961 },
962 PluginReconcile => "plugin/reconcile" {
963 params: v2::PluginReconcileParams,
964 serialization: None,
965 response: v2::PluginReconcileResponse,
966 },
967 PluginRead => "plugin/read" {
968 params: v2::PluginReadParams,
969 serialization: None,
970 response: v2::PluginReadResponse,
971 },
972 PluginSkillRead => "plugin/skill/read" {
973 params: v2::PluginSkillReadParams,
974 serialization: global("config"),
975 response: v2::PluginSkillReadResponse,
976 },
977 PluginShareSave => "plugin/share/save" {
978 params: v2::PluginShareSaveParams,
979 serialization: global("config"),
980 response: v2::PluginShareSaveResponse,
981 },
982 PluginShareUpdateTargets => "plugin/share/updateTargets" {
983 params: v2::PluginShareUpdateTargetsParams,
984 serialization: global("config"),
985 response: v2::PluginShareUpdateTargetsResponse,
986 },
987 PluginShareList => "plugin/share/list" {
988 params: v2::PluginShareListParams,
989 serialization: global("config"),
990 response: v2::PluginShareListResponse,
991 },
992 PluginShareCheckout => "plugin/share/checkout" {
993 params: v2::PluginShareCheckoutParams,
994 serialization: global("config"),
995 response: v2::PluginShareCheckoutResponse,
996 },
997 PluginShareDelete => "plugin/share/delete" {
998 params: v2::PluginShareDeleteParams,
999 serialization: global("config"),
1000 response: v2::PluginShareDeleteResponse,
1001 },
1002 AppsRead => "app/read" {
1003 params: v2::AppsReadParams,
1004 serialization: None,
1005 response: v2::AppsReadResponse,
1006 },
1007 AppsList => "app/list" {
1008 params: v2::AppsListParams,
1009 serialization: None,
1010 response: v2::AppsListResponse,
1011 },
1012 AppsInstalled => "app/installed" {
1013 params: v2::AppsInstalledParams,
1014 serialization: None,
1015 response: v2::AppsInstalledResponse,
1016 },
1017 // File system requests are intentionally concurrent. Desktop already treats local
1018 // file system operations as concurrent, and app-server remote fs mirrors that model.
1019 FsReadFile => "fs/readFile" {
1020 params: v2::FsReadFileParams,
1021 serialization: None,
1022 response: v2::FsReadFileResponse,
1023 },
1024 FsWriteFile => "fs/writeFile" {
1025 params: v2::FsWriteFileParams,
1026 serialization: None,
1027 response: v2::FsWriteFileResponse,
1028 },
1029 FsCreateDirectory => "fs/createDirectory" {
1030 params: v2::FsCreateDirectoryParams,
1031 serialization: None,
1032 response: v2::FsCreateDirectoryResponse,
1033 },
1034 FsGetMetadata => "fs/getMetadata" {
1035 params: v2::FsGetMetadataParams,
1036 serialization: None,
1037 response: v2::FsGetMetadataResponse,
1038 },
1039 FsReadDirectory => "fs/readDirectory" {
1040 params: v2::FsReadDirectoryParams,
1041 serialization: None,
1042 response: v2::FsReadDirectoryResponse,
1043 },
1044 FsRemove => "fs/remove" {
1045 params: v2::FsRemoveParams,
1046 serialization: None,
1047 response: v2::FsRemoveResponse,
1048 },
1049 FsCopy => "fs/copy" {
1050 params: v2::FsCopyParams,
1051 serialization: None,
1052 response: v2::FsCopyResponse,
1053 },
1054 FsWatch => "fs/watch" {
1055 params: v2::FsWatchParams,
1056 serialization: fs_watch_id(params.watch_id),
1057 response: v2::FsWatchResponse,
1058 },
1059 FsUnwatch => "fs/unwatch" {
1060 params: v2::FsUnwatchParams,
1061 serialization: fs_watch_id(params.watch_id),
1062 response: v2::FsUnwatchResponse,
1063 },
1064 SkillsConfigWrite => "skills/config/write" {
1065 params: v2::SkillsConfigWriteParams,
1066 serialization: global("config"),
1067 response: v2::SkillsConfigWriteResponse,
1068 },
1069 PluginInstall => "plugin/install" {
1070 params: v2::PluginInstallParams,
1071 serialization: global("config"),
1072 response: v2::PluginInstallResponse,
1073 },
1074 PluginUninstall => "plugin/uninstall" {
1075 params: v2::PluginUninstallParams,
1076 serialization: global("config"),
1077 response: v2::PluginUninstallResponse,
1078 },
1079 TurnStart => "turn/start" {
1080 params: v2::TurnStartParams,
1081 inspect_params: true,
1082 serialization: thread_id(params.thread_id),
1083 response: v2::TurnStartResponse,
1084 },
1085 #[experimental("turn/settings/update")]
1086 TurnSettingsUpdate => "turn/settings/update" {
1087 params: v2::TurnSettingsUpdateParams,
1088 serialization: thread_id(params.thread_id),
1089 response: v2::TurnSettingsUpdateResponse,
1090 },
1091 TurnSteer => "turn/steer" {
1092 params: v2::TurnSteerParams,
1093 inspect_params: true,
1094 serialization: thread_id(params.thread_id),
1095 response: v2::TurnSteerResponse,
1096 },
1097 TurnInterrupt => "turn/interrupt" {
1098 params: v2::TurnInterruptParams,
1099 serialization: thread_id(params.thread_id),
1100 response: v2::TurnInterruptResponse,
1101 },
1102 #[experimental("thread/realtime/start")]
1103 ThreadRealtimeStart => "thread/realtime/start" {
1104 params: v2::ThreadRealtimeStartParams,
1105 serialization: thread_id(params.thread_id),
1106 response: v2::ThreadRealtimeStartResponse,
1107 },
1108 #[experimental("thread/realtime/appendAudio")]
1109 ThreadRealtimeAppendAudio => "thread/realtime/appendAudio" {
1110 params: v2::ThreadRealtimeAppendAudioParams,
1111 serialization: thread_id(params.thread_id),
1112 response: v2::ThreadRealtimeAppendAudioResponse,
1113 },
1114 #[experimental("thread/realtime/appendText")]
1115 ThreadRealtimeAppendText => "thread/realtime/appendText" {
1116 params: v2::ThreadRealtimeAppendTextParams,
1117 serialization: thread_id(params.thread_id),
1118 response: v2::ThreadRealtimeAppendTextResponse,
1119 },
1120 #[experimental("thread/realtime/appendSpeech")]
1121 ThreadRealtimeAppendSpeech => "thread/realtime/appendSpeech" {
1122 params: v2::ThreadRealtimeAppendSpeechParams,
1123 serialization: thread_id(params.thread_id),
1124 response: v2::ThreadRealtimeAppendSpeechResponse,
1125 },
1126 #[experimental("thread/realtime/stop")]
1127 ThreadRealtimeStop => "thread/realtime/stop" {
1128 params: v2::ThreadRealtimeStopParams,
1129 serialization: thread_id(params.thread_id),
1130 response: v2::ThreadRealtimeStopResponse,
1131 },
1132 #[experimental("thread/timeline/list")]
1133 ThreadTimelineList => "thread/timeline/list" {
1134 params: v2::ThreadTimelineListParams,
1135 serialization: thread_id(params.thread_id),
1136 response: v2::ThreadTimelineListResponse,
1137 },
1138 #[experimental("thread/realtime/listVoices")]
1139 ThreadRealtimeListVoices => "thread/realtime/listVoices" {
1140 params: v2::ThreadRealtimeListVoicesParams,
1141 serialization: None,
1142 response: v2::ThreadRealtimeListVoicesResponse,
1143 },
1144 ReviewStart => "review/start" {
1145 params: v2::ReviewStartParams,
1146 serialization: thread_id(params.thread_id),
1147 response: v2::ReviewStartResponse,
1148 },
1149
1150 ModelList => "model/list" {
1151 params: v2::ModelListParams,
1152 serialization: None,
1153 response: v2::ModelListResponse,
1154 },
1155 GatewayOAuthRead => "account/gatewayOAuth/read" {
1156 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1157 serialization: None,
1158 response: v2::GatewayOAuthReadResponse,
1159 },
1160 GatewayOAuthLogin => "account/gatewayOAuth/login" {
1161 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1162 serialization: None,
1163 response: v2::GatewayOAuthLoginResponse,
1164 },
1165 GatewayOAuthCancel => "account/gatewayOAuth/cancel" {
1166 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1167 serialization: None,
1168 response: v2::GatewayOAuthCancelResponse,
1169 },
1170 ModelProviderCapabilitiesRead => "modelProvider/capabilities/read" {
1171 params: v2::ModelProviderCapabilitiesReadParams,
1172 serialization: None,
1173 response: v2::ModelProviderCapabilitiesReadResponse,
1174 },
1175 ExperimentalFeatureList => "experimentalFeature/list" {
1176 params: v2::ExperimentalFeatureListParams,
1177 serialization: global("config"),
1178 response: v2::ExperimentalFeatureListResponse,
1179 },
1180 PermissionProfileList => "permissionProfile/list" {
1181 params: v2::PermissionProfileListParams,
1182 serialization: global_shared_read("config"),
1183 response: v2::PermissionProfileListResponse,
1184 },
1185 ExperimentalFeatureEnablementSet => "experimentalFeature/enablement/set" {
1186 params: v2::ExperimentalFeatureEnablementSetParams,
1187 serialization: global("config"),
1188 response: v2::ExperimentalFeatureEnablementSetResponse,
1189 },
1190 #[experimental("remoteControl/enable")]
1191 RemoteControlEnable => "remoteControl/enable" {
1192 params: #[serde(skip_serializing_if = "Option::is_none")] v2::NullableRemoteControlEnableParams,
1193 serialization: global("remote-control"),
1194 response: v2::RemoteControlEnableResponse,
1195 },
1196 #[experimental("remoteControl/disable")]
1197 RemoteControlDisable => "remoteControl/disable" {
1198 params: #[serde(skip_serializing_if = "Option::is_none")] v2::NullableRemoteControlDisableParams,
1199 serialization: global("remote-control"),
1200 response: v2::RemoteControlDisableResponse,
1201 },
1202 #[experimental("remoteControl/status/read")]
1203 RemoteControlStatusRead => "remoteControl/status/read" {
1204 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1205 serialization: global_shared_read("remote-control"),
1206 response: v2::RemoteControlStatusReadResponse,
1207 },
1208 #[experimental("remoteControl/pairing/start")]
1209 RemoteControlPairingStart => "remoteControl/pairing/start" {
1210 params: v2::RemoteControlPairingStartParams,
1211 serialization: global("remote-control-pairing"),
1212 response: v2::RemoteControlPairingStartResponse,
1213 },
1214 #[experimental("remoteControl/pairing/status")]
1215 RemoteControlPairingStatus => "remoteControl/pairing/status" {
1216 params: v2::RemoteControlPairingStatusParams,
1217 serialization: global_shared_read("remote-control-pairing"),
1218 response: v2::RemoteControlPairingStatusResponse,
1219 },
1220 #[experimental("remoteControl/client/list")]
1221 RemoteControlClientsList => "remoteControl/client/list" {
1222 params: v2::RemoteControlClientsListParams,
1223 serialization: global_shared_read("remote-control-clients"),
1224 response: v2::RemoteControlClientsListResponse,
1225 },
1226 #[experimental("remoteControl/client/revoke")]
1227 RemoteControlClientsRevoke => "remoteControl/client/revoke" {
1228 params: v2::RemoteControlClientsRevokeParams,
1229 serialization: global("remote-control-clients"),
1230 response: v2::RemoteControlClientsRevokeResponse,
1231 },
1232 #[experimental("collaborationMode/list")]
1233 /// Lists collaboration mode presets.
1234 CollaborationModeList => "collaborationMode/list" {
1235 params: v2::CollaborationModeListParams,
1236 serialization: None,
1237 response: v2::CollaborationModeListResponse,
1238 },
1239 #[experimental("mock/experimentalMethod")]
1240 /// Test-only method used to validate experimental gating.
1241 MockExperimentalMethod => "mock/experimentalMethod" {
1242 params: v2::MockExperimentalMethodParams,
1243 serialization: None,
1244 response: v2::MockExperimentalMethodResponse,
1245 },
1246 #[experimental("environment/add")]
1247 /// Adds or replaces a remote environment by id for later selection.
1248 EnvironmentAdd => "environment/add" {
1249 params: v2::EnvironmentAddParams,
1250 serialization: global("environment"),
1251 response: v2::EnvironmentAddResponse,
1252 },
1253 #[experimental("environment/info")]
1254 /// Reads information from a configured execution environment.
1255 EnvironmentInfo => "environment/info" {
1256 params: v2::EnvironmentInfoParams,
1257 serialization: global_shared_read("environment"),
1258 response: v2::EnvironmentInfoResponse,
1259 },
1260 #[experimental("environment/status")]
1261 /// Reads the current status of a configured execution environment.
1262 EnvironmentStatus => "environment/status" {
1263 params: v2::EnvironmentStatusParams,
1264 serialization: global_shared_read("environment"),
1265 response: v2::EnvironmentStatusResponse,
1266 },
1267
1268 McpServerOauthLogin => "mcpServer/oauth/login" {
1269 params: v2::McpServerOauthLoginParams,
1270 serialization: mcp_oauth_server(params.name),
1271 response: v2::McpServerOauthLoginResponse,
1272 },
1273
1274 McpServerRefresh => "config/mcpServer/reload" {
1275 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1276 serialization: global("mcp-registry"),
1277 response: v2::McpServerRefreshResponse,
1278 },
1279
1280 McpServerStatusList => "mcpServerStatus/list" {
1281 params: v2::ListMcpServerStatusParams,
1282 serialization: global("mcp-registry"),
1283 response: v2::ListMcpServerStatusResponse,
1284 },
1285
1286 McpResourceRead => "mcpServer/resource/read" {
1287 params: v2::McpResourceReadParams,
1288 serialization: optional_thread_id(params.thread_id),
1289 response: v2::McpResourceReadResponse,
1290 },
1291
1292 #[experimental("mcpServer/event/stream/start")]
1293 McpServerEventStreamStart => "mcpServer/event/stream/start" {
1294 params: v2::McpServerEventStreamStartParams,
1295 serialization: None,
1296 response: v2::McpServerEventStreamStartResponse,
1297 },
1298
1299 #[experimental("mcpServer/event/stream/stop")]
1300 McpServerEventStreamStop => "mcpServer/event/stream/stop" {
1301 params: v2::McpServerEventStreamStopParams,
1302 serialization: None,
1303 response: v2::McpServerEventStreamStopResponse,
1304 },
1305
1306 McpServerToolCall => "mcpServer/tool/call" {
1307 params: v2::McpServerToolCallParams,
1308 serialization: thread_id(params.thread_id),
1309 response: v2::McpServerToolCallResponse,
1310 },
1311
1312 WindowsSandboxSetupStart => "windowsSandbox/setupStart" {
1313 params: v2::WindowsSandboxSetupStartParams,
1314 serialization: global("windows-sandbox-setup"),
1315 response: v2::WindowsSandboxSetupStartResponse,
1316 },
1317 WindowsSandboxReadiness => "windowsSandbox/readiness" {
1318 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1319 serialization: global("config"),
1320 response: v2::WindowsSandboxReadinessResponse,
1321 },
1322
1323 LoginAccount => "account/login/start" {
1324 params: v2::LoginAccountParams,
1325 inspect_params: true,
1326 serialization: global("account-auth"),
1327 response: v2::LoginAccountResponse,
1328 },
1329
1330 #[experimental("account/bedrock/discover")]
1331 BedrockDiscover => "account/bedrock/discover" {
1332 params: v2::BedrockDiscoverParams,
1333 serialization: global_shared_read("account-auth"),
1334 response: v2::BedrockDiscoverResponse,
1335 },
1336
1337 #[experimental("account/bedrock/setup")]
1338 BedrockSetup => "account/bedrock/setup" {
1339 params: v2::BedrockSetupParams,
1340 serialization: global("account-auth"),
1341 response: v2::BedrockSetupResponse,
1342 },
1343
1344 #[experimental("account/gcp/setup")]
1345 GcpSetup => "account/gcp/setup" {
1346 params: v2::GcpSetupParams,
1347 serialization: global("account-auth"),
1348 response: v2::GcpSetupResponse,
1349 },
1350
1351 #[experimental("account/bedrock/checkGovCloudRequirements")]
1352 BedrockCheckGovCloudRequirements => "account/bedrock/checkGovCloudRequirements" {
1353 params: v2::BedrockCheckGovCloudRequirementsParams,
1354 serialization: global("account-auth"),
1355 response: v2::BedrockCheckGovCloudRequirementsResponse,
1356 },
1357
1358 CancelLoginAccount => "account/login/cancel" {
1359 params: v2::CancelLoginAccountParams,
1360 serialization: global("account-auth"),
1361 response: v2::CancelLoginAccountResponse,
1362 },
1363
1364 #[experimental("accountSession/list")]
1365 AccountSessionsList => "accountSession/list" {
1366 params: v2::AccountSessionsListParams,
1367 serialization: global("account-auth"),
1368 manual_payload_conversion: manual,
1369 response: v2::AccountSessionsResponse,
1370 },
1371
1372 #[experimental("accountSession/switch")]
1373 AccountSessionsSwitch => "accountSession/switch" {
1374 params: v2::AccountSessionsSwitchParams,
1375 serialization: global("account-auth"),
1376 manual_payload_conversion: manual,
1377 response: v2::AccountSessionsSwitchResponse,
1378 },
1379
1380 LogoutAccount => "account/logout" {
1381 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1382 serialization: global("account-auth"),
1383 response: v2::LogoutAccountResponse,
1384 },
1385
1386 GetAccountRateLimits => "account/rateLimits/read" {
1387 params: #[ts(optional, as = "Option<GetAccountRateLimitsParamsTypeScript>", inline)] #[serde(default, skip_serializing_if = "Option::is_none")] v2::NullableGetAccountRateLimitsParams,
1388 serialization: None,
1389 response: v2::GetAccountRateLimitsResponse,
1390 },
1391
1392 ConsumeAccountRateLimitResetCredit => "account/rateLimitResetCredit/consume" {
1393 params: v2::ConsumeAccountRateLimitResetCreditParams,
1394 serialization: global("account-auth"),
1395 response: v2::ConsumeAccountRateLimitResetCreditResponse,
1396 },
1397
1398 GetAccountTokenUsage => "account/usage/read" {
1399 params: #[ts(optional, as = "Option<GetAccountTokenUsageParamsTypeScript>", inline)] #[serde(default, skip_serializing_if = "Option::is_none")] v2::NullableGetAccountTokenUsageParams,
1400 serialization: None,
1401 response: v2::GetAccountTokenUsageResponse,
1402 },
1403
1404 GetWorkspaceMessages => "account/workspaceMessages/read" {
1405 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1406 serialization: None,
1407 response: v2::GetWorkspaceMessagesResponse,
1408 },
1409
1410 SendAddCreditsNudgeEmail => "account/sendAddCreditsNudgeEmail" {
1411 params: v2::SendAddCreditsNudgeEmailParams,
1412 serialization: global("account-auth"),
1413 response: v2::SendAddCreditsNudgeEmailResponse,
1414 },
1415
1416 FeedbackUpload => "feedback/upload" {
1417 params: v2::FeedbackUploadParams,
1418 serialization: None,
1419 response: v2::FeedbackUploadResponse,
1420 },
1421
1422 FeedbackSave => "feedback/save" {
1423 params: v2::FeedbackSaveParams,
1424 serialization: None,
1425 response: v2::FeedbackSaveResponse,
1426 },
1427
1428 /// Execute a standalone command (argv vector) under the server's sandbox.
1429 OneOffCommandExec => "command/exec" {
1430 params: v2::CommandExecParams,
1431 inspect_params: true,
1432 serialization: optional_command_process_id(params.process_id),
1433 response: v2::CommandExecResponse,
1434 },
1435 /// Write stdin bytes to a running `command/exec` session or close stdin.
1436 CommandExecWrite => "command/exec/write" {
1437 params: v2::CommandExecWriteParams,
1438 serialization: command_process_id(params.process_id),
1439 response: v2::CommandExecWriteResponse,
1440 },
1441 /// Terminate a running `command/exec` session by client-supplied `processId`.
1442 CommandExecTerminate => "command/exec/terminate" {
1443 params: v2::CommandExecTerminateParams,
1444 serialization: command_process_id(params.process_id),
1445 response: v2::CommandExecTerminateResponse,
1446 },
1447 /// Resize a running PTY-backed `command/exec` session by client-supplied `processId`.
1448 CommandExecResize => "command/exec/resize" {
1449 params: v2::CommandExecResizeParams,
1450 serialization: command_process_id(params.process_id),
1451 response: v2::CommandExecResizeResponse,
1452 },
1453 #[experimental("process/spawn")]
1454 /// Spawn a standalone process (argv vector) without a Codex sandbox.
1455 ProcessSpawn => "process/spawn" {
1456 params: v2::ProcessSpawnParams,
1457 serialization: process_handle(params.process_handle),
1458 response: v2::ProcessSpawnResponse,
1459 },
1460 #[experimental("process/writeStdin")]
1461 /// Write stdin bytes to a running `process/spawn` session or close stdin.
1462 ProcessWriteStdin => "process/writeStdin" {
1463 params: v2::ProcessWriteStdinParams,
1464 serialization: process_handle(params.process_handle),
1465 response: v2::ProcessWriteStdinResponse,
1466 },
1467 #[experimental("process/kill")]
1468 /// Terminate a running `process/spawn` session by client-supplied `processHandle`.
1469 ProcessKill => "process/kill" {
1470 params: v2::ProcessKillParams,
1471 serialization: process_handle(params.process_handle),
1472 response: v2::ProcessKillResponse,
1473 },
1474 #[experimental("process/resizePty")]
1475 /// Resize a running PTY-backed `process/spawn` session by client-supplied `processHandle`.
1476 ProcessResizePty => "process/resizePty" {
1477 params: v2::ProcessResizePtyParams,
1478 serialization: process_handle(params.process_handle),
1479 response: v2::ProcessResizePtyResponse,
1480 },
1481
1482 ConfigRead => "config/read" {
1483 params: v2::ConfigReadParams,
1484 serialization: global_shared_read("config"),
1485 response: v2::ConfigReadResponse,
1486 },
1487 ExternalAgentConfigDetect => "externalAgentConfig/detect" {
1488 params: v2::ExternalAgentConfigDetectParams,
1489 serialization: global("external-agent-detect"),
1490 response: v2::ExternalAgentConfigDetectResponse,
1491 },
1492 ExternalAgentConfigImport => "externalAgentConfig/import" {
1493 params: v2::ExternalAgentConfigImportParams,
1494 serialization: global("config"),
1495 response: v2::ExternalAgentConfigImportResponse,
1496 },
1497 ExternalAgentConfigImportHistoryRecord => "externalAgentConfig/import/recordHistory" {
1498 params: v2::ExternalAgentConfigImportHistoryRecordParams,
1499 serialization: global("config"),
1500 response: v2::ExternalAgentConfigImportHistoryRecordResponse,
1501 },
1502 ExternalAgentConfigImportHistoriesRead => "externalAgentConfig/import/readHistories" {
1503 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1504 serialization: global_shared_read("config"),
1505 response: v2::ExternalAgentConfigImportHistoriesReadResponse,
1506 },
1507 ConfigValueWrite => "config/value/write" {
1508 params: v2::ConfigValueWriteParams,
1509 serialization: global("config"),
1510 manual_payload_conversion: manual,
1511 response: v2::ConfigWriteResponse,
1512 },
1513 ConfigBatchWrite => "config/batchWrite" {
1514 params: v2::ConfigBatchWriteParams,
1515 serialization: global("config"),
1516 manual_payload_conversion: manual,
1517 response: v2::ConfigWriteResponse,
1518 },
1519
1520 ConfigRequirementsRead => "configRequirements/read" {
1521 params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
1522 serialization: global_shared_read("config"),
1523 response: v2::ConfigRequirementsReadResponse,
1524 },
1525
1526 GetAccount => "account/read" {
1527 params: v2::GetAccountParams,
1528 serialization: global("account-auth"),
1529 response: v2::GetAccountResponse,
1530 },
1531
1532 /// DEPRECATED APIs below
1533 GetConversationSummary => "getConversationSummary" {
1534 params: v1::GetConversationSummaryParams,
1535 serialization: None,
1536 response: v1::GetConversationSummaryResponse,
1537 },
1538 GitDiffToRemote => "gitDiffToRemote" {
1539 params: v1::GitDiffToRemoteParams,
1540 serialization: None,
1541 response: v1::GitDiffToRemoteResponse,
1542 },
1543 /// DEPRECATED in favor of GetAccount
1544 GetAuthStatus => "getAuthStatus" {
1545 params: v1::GetAuthStatusParams,
1546 serialization: global("account-auth"),
1547 response: v1::GetAuthStatusResponse,
1548 },
1549 // Legacy fuzzy search cancellation is intentionally concurrent: clients reuse a
1550 // cancellation token so a newer request can cancel an older in-flight search.
1551 FuzzyFileSearch => "fuzzyFileSearch" {
1552 params: FuzzyFileSearchParams,
1553 serialization: None,
1554 response: FuzzyFileSearchResponse,
1555 },
1556 #[experimental("fuzzyFileSearch/sessionStart")]
1557 FuzzyFileSearchSessionStart => "fuzzyFileSearch/sessionStart" {
1558 params: FuzzyFileSearchSessionStartParams,
1559 serialization: fuzzy_session_id(params.session_id),
1560 response: FuzzyFileSearchSessionStartResponse,
1561 },
1562 #[experimental("fuzzyFileSearch/sessionUpdate")]
1563 FuzzyFileSearchSessionUpdate => "fuzzyFileSearch/sessionUpdate" {
1564 params: FuzzyFileSearchSessionUpdateParams,
1565 serialization: fuzzy_session_id(params.session_id),
1566 response: FuzzyFileSearchSessionUpdateResponse,
1567 },
1568 #[experimental("fuzzyFileSearch/sessionStop")]
1569 FuzzyFileSearchSessionStop => "fuzzyFileSearch/sessionStop" {
1570 params: FuzzyFileSearchSessionStopParams,
1571 serialization: fuzzy_session_id(params.session_id),
1572 response: FuzzyFileSearchSessionStopResponse,
1573 },
1574 }
1575
1576 /// Generates an `enum ServerRequest` where each variant is a request that the
1577 /// server can send to the client along with the corresponding params and
1578 /// response types. It also generates helper types used by the app/server
1579 /// infrastructure (payload enum, request constructor, and export helpers).
1580 macro_rules! server_request_definitions {
1581 (
1582 $(
1583 $(#[experimental($reason:expr)])?
1584 $(#[doc = $variant_doc:literal])*
1585 $variant:ident $(=> $wire:literal)? {
1586 params: $params:ty,
1587 response: $response:ty,
1588 }
1589 ),* $(,)?
1590 ) => {
1591 /// Request initiated from the server and sent to the client.
1592 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1593 #[allow(clippy::large_enum_variant)]
1594 #[serde(tag = "method", rename_all = "camelCase")]
1595 pub enum ServerRequest {
1596 $(
1597 $(#[doc = $variant_doc])*
1598 $(#[serde(rename = $wire)] #[ts(rename = $wire)])?
1599 $variant {
1600 #[serde(rename = "id")]
1601 request_id: RequestId,
1602 params: $params,
1603 },
1604 )*
1605 }
1606
1607 impl ServerRequest {
1608 pub fn id(&self) -> &RequestId {
1609 match self {
1610 $(Self::$variant { request_id, .. } => request_id,)*
1611 }
1612 }
1613
1614 pub fn response_from_result(
1615 &self,
1616 result: crate::Result,
1617 ) -> serde_json::Result<ServerResponse> {
1618 match self {
1619 $(
1620 Self::$variant { request_id, .. } => {
1621 let response = serde_json::from_value::<$response>(result)?;
1622 Ok(ServerResponse::$variant {
1623 request_id: request_id.clone(),
1624 response,
1625 })
1626 }
1627 )*
1628 }
1629 }
1630 }
1631
1632 /// Typed response from the client to the server.
1633 #[derive(Serialize, Deserialize, Debug, Clone)]
1634 #[serde(tag = "method", rename_all = "camelCase")]
1635 pub enum ServerResponse {
1636 $(
1637 $(#[doc = $variant_doc])*
1638 $(#[serde(rename = $wire)])?
1639 $variant {
1640 #[serde(rename = "id")]
1641 request_id: RequestId,
1642 response: $response,
1643 },
1644 )*
1645 }
1646
1647 impl ServerResponse {
1648 pub fn id(&self) -> &RequestId {
1649 match self {
1650 $(Self::$variant { request_id, .. } => request_id,)*
1651 }
1652 }
1653
1654 pub fn method(&self) -> String {
1655 serde_json::to_value(self)
1656 .ok()
1657 .and_then(|value| {
1658 value
1659 .get("method")
1660 .and_then(serde_json::Value::as_str)
1661 .map(str::to_owned)
1662 })
1663 .unwrap_or_else(|| "<unknown>".to_string())
1664 }
1665 }
1666
1667 #[derive(Debug, Clone, PartialEq, JsonSchema)]
1668 #[allow(clippy::large_enum_variant)]
1669 pub enum ServerRequestPayload {
1670 $( $variant($params), )*
1671 }
1672
1673 impl ServerRequestPayload {
1674 pub fn request_with_id(self, request_id: RequestId) -> ServerRequest {
1675 match self {
1676 $(Self::$variant(params) => ServerRequest::$variant { request_id, params },)*
1677 }
1678 }
1679 }
1680
1681 #[cfg(test)]
1682 pub(crate) const EXPERIMENTAL_SERVER_METHODS: &[&str] = &[
1683 $(
1684 experimental_method_entry!($(#[experimental($reason)])? $(=> $wire)?),
1685 )*
1686 ];
1687 #[cfg(test)]
1688 pub(crate) const EXPERIMENTAL_SERVER_METHOD_PARAM_TYPES: &[&str] = &[
1689 $(
1690 experimental_type_entry!($(#[experimental($reason)])? $params),
1691 )*
1692 ];
1693 #[cfg(test)]
1694 pub(crate) const EXPERIMENTAL_SERVER_METHOD_RESPONSE_TYPES: &[&str] = &[
1695 $(
1696 experimental_type_entry!($(#[experimental($reason)])? $response),
1697 )*
1698 ];
1699
1700 #[cfg(test)]
1701 pub fn export_server_responses(
1702 out_dir: &::std::path::Path,
1703 ) -> ::std::result::Result<(), ::ts_rs::ExportError> {
1704 $(
1705 <$response as ::ts_rs::TS>::export_all_to(out_dir)?;
1706 )*
1707 Ok(())
1708 }
1709
1710 #[cfg(test)]
1711 pub(crate) fn visit_server_response_types(v: &mut impl ::ts_rs::TypeVisitor) {
1712 $(
1713 v.visit::<$response>();
1714 )*
1715 }
1716
1717 #[cfg(test)]
1718 #[allow(clippy::vec_init_then_push)]
1719 pub fn export_server_response_schemas(
1720 out_dir: &Path,
1721 ) -> ::anyhow::Result<Vec<GeneratedSchema>> {
1722 let mut schemas = Vec::new();
1723 $(
1724 schemas.push(crate::export::write_json_schema::<$response>(
1725 out_dir,
1726 concat!(stringify!($variant), "Response"),
1727 )?);
1728 )*
1729 Ok(schemas)
1730 }
1731
1732 #[cfg(test)]
1733 #[allow(clippy::vec_init_then_push)]
1734 pub fn export_server_param_schemas(
1735 out_dir: &Path,
1736 ) -> ::anyhow::Result<Vec<GeneratedSchema>> {
1737 let mut schemas = Vec::new();
1738 $(
1739 schemas.push(crate::export::write_json_schema::<$params>(
1740 out_dir,
1741 concat!(stringify!($variant), "Params"),
1742 )?);
1743 )*
1744 Ok(schemas)
1745 }
1746 };
1747 }
1748
1749 /// Generates `ServerNotification` enum and helpers, including a JSON Schema
1750 /// exporter for each notification.
1751 macro_rules! server_notification_definitions {
1752 (
1753 $(
1754 $(#[$variant_meta:meta])*
1755 $variant:ident $(=> $wire:literal)? ( $payload:ty )
1756 ),* $(,)?
1757 ) => {
1758 /// Notification sent from the server to the client.
1759 #[derive(
1760 Serialize,
1761 Deserialize,
1762 Debug,
1763 Clone,
1764 JsonSchema,
1765 TS,
1766 Display,
1767 ExperimentalApi,
1768 )]
1769 #[allow(clippy::large_enum_variant)]
1770 #[serde(tag = "method", content = "params", rename_all = "camelCase")]
1771 #[strum(serialize_all = "camelCase")]
1772 pub enum ServerNotification {
1773 $(
1774 $(#[$variant_meta])*
1775 $(#[serde(rename = $wire)] #[ts(rename = $wire)] #[strum(serialize = $wire)])?
1776 $variant($payload),
1777 )*
1778 }
1779
1780 impl ServerNotification {
1781 pub fn to_params(self) -> Result<serde_json::Value, serde_json::Error> {
1782 match self {
1783 $(Self::$variant(params) => serde_json::to_value(params),)*
1784 }
1785 }
1786 }
1787
1788 impl TryFrom<JSONRPCNotification> for ServerNotification {
1789 type Error = serde_json::Error;
1790
1791 fn try_from(value: JSONRPCNotification) -> Result<Self, serde_json::Error> {
1792 serde_json::from_value(serde_json::to_value(value)?)
1793 }
1794 }
1795
1796 #[cfg(test)]
1797 #[allow(clippy::vec_init_then_push)]
1798 pub fn export_server_notification_schemas(
1799 out_dir: &::std::path::Path,
1800 ) -> ::anyhow::Result<Vec<GeneratedSchema>> {
1801 let mut schemas = Vec::new();
1802 $(schemas.push(crate::export::write_json_schema::<$payload>(out_dir, stringify!($payload))?);)*
1803 Ok(schemas)
1804 }
1805 };
1806 }
1807 /// Notifications sent from the client to the server.
1808 macro_rules! client_notification_definitions {
1809 (
1810 $(
1811 $(#[$variant_meta:meta])*
1812 $variant:ident $( ( $payload:ty ) )?
1813 ),* $(,)?
1814 ) => {
1815 #[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS, Display)]
1816 #[serde(tag = "method", content = "params", rename_all = "camelCase")]
1817 #[strum(serialize_all = "camelCase")]
1818 pub enum ClientNotification {
1819 $(
1820 $(#[$variant_meta])*
1821 $variant $( ( $payload ) )?,
1822 )*
1823 }
1824
1825 #[cfg(test)]
1826 pub fn export_client_notification_schemas(
1827 _out_dir: &::std::path::Path,
1828 ) -> ::anyhow::Result<Vec<GeneratedSchema>> {
1829 let schemas = Vec::new();
1830 $( $(schemas.push(crate::export::write_json_schema::<$payload>(_out_dir, stringify!($payload))?);)? )*
1831 Ok(schemas)
1832 }
1833 };
1834 }
1835
1836 impl TryFrom<JSONRPCRequest> for ServerRequest {
1837 type Error = serde_json::Error;
1838
1839 fn try_from(value: JSONRPCRequest) -> Result<Self, Self::Error> {
1840 serde_json::from_value(serde_json::to_value(value)?)
1841 }
1842 }
1843
1844 server_request_definitions! {
1845 /// NEW APIs
1846 /// Sent when approval is requested for a specific command execution.
1847 /// This request is used for Turns started via turn/start.
1848 CommandExecutionRequestApproval => "item/commandExecution/requestApproval" {
1849 params: v2::CommandExecutionRequestApprovalParams,
1850 response: v2::CommandExecutionRequestApprovalResponse,
1851 },
1852
1853 /// Sent when approval is requested for a specific file change.
1854 /// This request is used for Turns started via turn/start.
1855 FileChangeRequestApproval => "item/fileChange/requestApproval" {
1856 params: v2::FileChangeRequestApprovalParams,
1857 response: v2::FileChangeRequestApprovalResponse,
1858 },
1859
1860 /// EXPERIMENTAL - Request input from the user for a tool call.
1861 ToolRequestUserInput => "item/tool/requestUserInput" {
1862 params: v2::ToolRequestUserInputParams,
1863 response: v2::ToolRequestUserInputResponse,
1864 },
1865
1866 /// Request input for an MCP server elicitation.
1867 McpServerElicitationRequest => "mcpServer/elicitation/request" {
1868 params: v2::McpServerElicitationRequestParams,
1869 response: v2::McpServerElicitationRequestResponse,
1870 },
1871
1872 /// Request approval for additional permissions from the user.
1873 PermissionsRequestApproval => "item/permissions/requestApproval" {
1874 params: v2::PermissionsRequestApprovalParams,
1875 response: v2::PermissionsRequestApprovalResponse,
1876 },
1877
1878 /// Execute a dynamic tool call on the client.
1879 DynamicToolCall => "item/tool/call" {
1880 params: v2::DynamicToolCallParams,
1881 response: v2::DynamicToolCallResponse,
1882 },
1883
1884 ChatgptAuthTokensRefresh => "account/chatgptAuthTokens/refresh" {
1885 params: v2::ChatgptAuthTokensRefreshParams,
1886 response: v2::ChatgptAuthTokensRefreshResponse,
1887 },
1888
1889 /// Generate a fresh upstream attestation result on demand.
1890 AttestationGenerate => "attestation/generate" {
1891 params: v2::AttestationGenerateParams,
1892 response: v2::AttestationGenerateResponse,
1893 },
1894
1895 #[experimental("currentTime/read")]
1896 /// Read the current time from an external clock owned by the client.
1897 CurrentTimeRead => "currentTime/read" {
1898 params: v2::CurrentTimeReadParams,
1899 response: v2::CurrentTimeReadResponse,
1900 },
1901
1902 /// DEPRECATED APIs below
1903 /// Request to approve a patch.
1904 /// This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).
1905 ApplyPatchApproval {
1906 params: v1::ApplyPatchApprovalParams,
1907 response: v1::ApplyPatchApprovalResponse,
1908 },
1909 /// Request to exec a command.
1910 /// This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).
1911 ExecCommandApproval {
1912 params: v1::ExecCommandApprovalParams,
1913 response: v1::ExecCommandApprovalResponse,
1914 },
1915 }
1916
1917 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1918 #[serde(rename_all = "camelCase")]
1919 #[ts(rename_all = "camelCase")]
1920 pub struct FuzzyFileSearchParams {
1921 pub query: String,
1922 pub roots: Vec<String>,
1923 // if provided, will cancel any previous request that used the same value
1924 pub cancellation_token: Option<String>,
1925 }
1926
1927 /// Superset of [`codex_file_search::FileMatch`]
1928 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1929 pub struct FuzzyFileSearchResult {
1930 pub root: String,
1931 pub path: String,
1932 pub match_type: FuzzyFileSearchMatchType,
1933 pub file_name: String,
1934 pub score: u32,
1935 pub indices: Option<Vec<u32>>,
1936 }
1937
1938 #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
1939 #[serde(rename_all = "camelCase")]
1940 #[ts(rename_all = "camelCase")]
1941 pub enum FuzzyFileSearchMatchType {
1942 File,
1943 Directory,
1944 }
1945
1946 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1947 pub struct FuzzyFileSearchResponse {
1948 pub files: Vec<FuzzyFileSearchResult>,
1949 }
1950
1951 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1952 #[serde(rename_all = "camelCase")]
1953 #[ts(rename_all = "camelCase")]
1954 pub struct FuzzyFileSearchSessionStartParams {
1955 pub session_id: String,
1956 pub roots: Vec<String>,
1957 }
1958
1959 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, Default)]
1960 pub struct FuzzyFileSearchSessionStartResponse {}
1961
1962 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1963 #[serde(rename_all = "camelCase")]
1964 #[ts(rename_all = "camelCase")]
1965 pub struct FuzzyFileSearchSessionUpdateParams {
1966 pub session_id: String,
1967 pub query: String,
1968 }
1969
1970 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, Default)]
1971 pub struct FuzzyFileSearchSessionUpdateResponse {}
1972
1973 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1974 #[serde(rename_all = "camelCase")]
1975 #[ts(rename_all = "camelCase")]
1976 pub struct FuzzyFileSearchSessionStopParams {
1977 pub session_id: String,
1978 }
1979
1980 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, Default)]
1981 pub struct FuzzyFileSearchSessionStopResponse {}
1982
1983 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1984 #[serde(rename_all = "camelCase")]
1985 #[ts(rename_all = "camelCase")]
1986 pub struct FuzzyFileSearchSessionUpdatedNotification {
1987 pub session_id: String,
1988 pub query: String,
1989 pub files: Vec<FuzzyFileSearchResult>,
1990 }
1991
1992 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
1993 #[serde(rename_all = "camelCase")]
1994 #[ts(rename_all = "camelCase")]
1995 pub struct FuzzyFileSearchSessionCompletedNotification {
1996 pub session_id: String,
1997 }
1998
1999 server_notification_definitions! {
2000 /// NEW NOTIFICATIONS
2001 Error => "error" (v2::ErrorNotification),
2002 ThreadStarted => "thread/started" (v2::ThreadStartedNotification),
2003 ThreadStatusChanged => "thread/status/changed" (v2::ThreadStatusChangedNotification),
2004 #[experimental("thread/readState/changed")]
2005 ThreadReadStateChanged => "thread/readState/changed" (v2::ThreadReadStateChangedNotification),
2006 ThreadArchived => "thread/archived" (v2::ThreadArchivedNotification),
2007 ThreadDeleted => "thread/deleted" (v2::ThreadDeletedNotification),
2008 ThreadUnarchived => "thread/unarchived" (v2::ThreadUnarchivedNotification),
2009 ThreadClosed => "thread/closed" (v2::ThreadClosedNotification),
2010 ThreadReverted => "thread/reverted" (v2::ThreadRevertedNotification),
2011 SkillsChanged => "skills/changed" (v2::SkillsChangedNotification),
2012 ThreadNameUpdated => "thread/name/updated" (v2::ThreadNameUpdatedNotification),
2013 ThreadAttachmentUpdated => "thread/attachment/updated" (v2::ThreadAttachmentUpdatedNotification),
2014 ThreadGoalUpdated => "thread/goal/updated" (v2::ThreadGoalUpdatedNotification),
2015 #[experimental("thread/prediction/updated")]
2016 ThreadPredictionUpdated => "thread/prediction/updated" (v2::ThreadPredictionUpdatedNotification),
2017 ThreadGoalCleared => "thread/goal/cleared" (v2::ThreadGoalClearedNotification),
2018 #[experimental("thread/queue/changed")]
2019 ThreadQueueChanged => "thread/queue/changed" (v2::ThreadQueueChangedNotification),
2020 #[experimental("project/changed")]
2021 ProjectChanged => "project/changed" (v2::ProjectChangedNotification),
2022 #[experimental("thread/project/updated")]
2023 ThreadProjectUpdated => "thread/project/updated" (v2::ThreadProjectUpdatedNotification),
2024 #[experimental("thread/environment/connected")]
2025 EnvironmentConnected => "thread/environment/connected" (v2::EnvironmentConnectionNotification),
2026 #[experimental("thread/environment/disconnected")]
2027 EnvironmentDisconnected => "thread/environment/disconnected" (v2::EnvironmentConnectionNotification),
2028 #[experimental("thread/settings/updated")]
2029 ThreadSettingsUpdated => "thread/settings/updated" (v2::ThreadSettingsUpdatedNotification),
2030 ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification),
2031 TurnStarted => "turn/started" (v2::TurnStartedNotification),
2032 HookStarted => "hook/started" (v2::HookStartedNotification),
2033 TurnCompleted => "turn/completed" (v2::TurnCompletedNotification),
2034 HookCompleted => "hook/completed" (v2::HookCompletedNotification),
2035 TurnDiffUpdated => "turn/diff/updated" (v2::TurnDiffUpdatedNotification),
2036 TurnPlanUpdated => "turn/plan/updated" (v2::TurnPlanUpdatedNotification),
2037 ItemStarted => "item/started" (v2::ItemStartedNotification),
2038 ItemGuardianApprovalReviewStarted => "item/autoApprovalReview/started" (v2::ItemGuardianApprovalReviewStartedNotification),
2039 ItemGuardianApprovalReviewCompleted => "item/autoApprovalReview/completed" (v2::ItemGuardianApprovalReviewCompletedNotification),
2040 #[experimental("autoApprovalReview/strictReviewRequired")]
2041 StrictReviewRequired => "autoApprovalReview/strictReviewRequired" (v2::StrictReviewRequiredNotification),
2042 ItemCompleted => "item/completed" (v2::ItemCompletedNotification),
2043 /// This event is internal-only. Used by Codex Cloud.
2044 RawResponseItemCompleted => "rawResponseItem/completed" (v2::RawResponseItemCompletedNotification),
2045 /// This event is internal-only. Used by clients that need exact upstream usage.
2046 RawResponseCompleted => "rawResponse/completed" (v2::RawResponseCompletedNotification),
2047 AgentMessageDelta => "item/agentMessage/delta" (v2::AgentMessageDeltaNotification),
2048 /// EXPERIMENTAL - proposed plan streaming deltas for plan items.
2049 PlanDelta => "item/plan/delta" (v2::PlanDeltaNotification),
2050 /// Stream base64-encoded stdout/stderr chunks for a running `command/exec` session.
2051 CommandExecOutputDelta => "command/exec/outputDelta" (v2::CommandExecOutputDeltaNotification),
2052 /// Stream base64-encoded stdout/stderr chunks for a running `process/spawn` session.
2053 #[experimental("process/outputDelta")]
2054 ProcessOutputDelta => "process/outputDelta" (v2::ProcessOutputDeltaNotification),
2055 /// Final exit notification for a `process/spawn` session.
2056 #[experimental("process/exited")]
2057 ProcessExited => "process/exited" (v2::ProcessExitedNotification),
2058 CommandExecutionOutputDelta => "item/commandExecution/outputDelta" (v2::CommandExecutionOutputDeltaNotification),
2059 TerminalInteraction => "item/commandExecution/terminalInteraction" (v2::TerminalInteractionNotification),
2060 /// Deprecated legacy apply_patch output stream notification.
2061 FileChangeOutputDelta => "item/fileChange/outputDelta" (v2::FileChangeOutputDeltaNotification),
2062 FileChangePatchUpdated => "item/fileChange/patchUpdated" (v2::FileChangePatchUpdatedNotification),
2063 ServerRequestResolved => "serverRequest/resolved" (v2::ServerRequestResolvedNotification),
2064 McpToolCallProgress => "item/mcpToolCall/progress" (v2::McpToolCallProgressNotification),
2065 McpServerOauthLoginCompleted => "mcpServer/oauthLogin/completed" (v2::McpServerOauthLoginCompletedNotification),
2066 McpServerStatusUpdated => "mcpServer/startupStatus/updated" (v2::McpServerStatusUpdatedNotification),
2067 #[experimental("mcpServer/event/stream/notification")]
2068 McpServerEventStream => "mcpServer/event/stream/notification" (v2::McpServerEventStreamNotification),
2069 AccountUpdated => "account/updated" (v2::AccountUpdatedNotification),
2070 GatewayOAuthChanged => "account/gatewayOAuth/changed" (v2::GatewayOAuthChangedNotification),
2071 AccountRateLimitsUpdated => "account/rateLimits/updated" (v2::AccountRateLimitsUpdatedNotification),
2072 AppListUpdated => "app/list/updated" (v2::AppListUpdatedNotification),
2073 RemoteControlStatusChanged => "remoteControl/status/changed" (v2::RemoteControlStatusChangedNotification),
2074 ExternalAgentConfigImportProgress => "externalAgentConfig/import/progress" (v2::ExternalAgentConfigImportProgressNotification),
2075 ExternalAgentConfigImportCompleted => "externalAgentConfig/import/completed" (v2::ExternalAgentConfigImportCompletedNotification),
2076 FsChanged => "fs/changed" (v2::FsChangedNotification),
2077 ReasoningSummaryTextDelta => "item/reasoning/summaryTextDelta" (v2::ReasoningSummaryTextDeltaNotification),
2078 ReasoningSummaryPartAdded => "item/reasoning/summaryPartAdded" (v2::ReasoningSummaryPartAddedNotification),
2079 ReasoningTextDelta => "item/reasoning/textDelta" (v2::ReasoningTextDeltaNotification),
2080 /// Deprecated: Use `ContextCompaction` item type instead.
2081 ContextCompacted => "thread/compacted" (v2::ContextCompactedNotification),
2082 ModelRerouted => "model/rerouted" (v2::ModelReroutedNotification),
2083 ModelVerification => "model/verification" (v2::ModelVerificationNotification),
2084 AuthRecoveryStarted => "modelProvider/authRecoveryStarted" (v2::AuthRecoveryNotification),
2085 AuthRecoveryCompleted => "modelProvider/authRecoveryCompleted" (v2::AuthRecoveryNotification),
2086 #[experimental("turn/moderationMetadata")]
2087 TurnModerationMetadata => "turn/moderationMetadata" (v2::TurnModerationMetadataNotification),
2088 ModelSafetyBufferingUpdated => "model/safetyBuffering/updated" (v2::ModelSafetyBufferingUpdatedNotification),
2089 Warning => "warning" (v2::WarningNotification),
2090 GuardianWarning => "guardianWarning" (v2::GuardianWarningNotification),
2091 DeprecationNotice => "deprecationNotice" (v2::DeprecationNoticeNotification),
2092 ConfigWarning => "configWarning" (v2::ConfigWarningNotification),
2093 FuzzyFileSearchSessionUpdated => "fuzzyFileSearch/sessionUpdated" (FuzzyFileSearchSessionUpdatedNotification),
2094 FuzzyFileSearchSessionCompleted => "fuzzyFileSearch/sessionCompleted" (FuzzyFileSearchSessionCompletedNotification),
2095 #[experimental("thread/realtime/started")]
2096 ThreadRealtimeStarted => "thread/realtime/started" (v2::ThreadRealtimeStartedNotification),
2097 #[experimental("thread/realtime/itemAdded")]
2098 ThreadRealtimeItemAdded => "thread/realtime/itemAdded" (v2::ThreadRealtimeItemAddedNotification),
2099 #[experimental("thread/realtime/item/started")]
2100 ThreadRealtimeItemStarted => "thread/realtime/item/started" (v2::ThreadRealtimeItemStartedNotification),
2101 #[experimental("thread/realtime/item/transcript/delta")]
2102 ThreadRealtimeItemTranscriptDelta => "thread/realtime/item/transcript/delta" (v2::ThreadRealtimeItemTranscriptDeltaNotification),
2103 #[experimental("thread/realtime/item/completed")]
2104 ThreadRealtimeItemCompleted => "thread/realtime/item/completed" (v2::ThreadRealtimeItemCompletedNotification),
2105 #[experimental("thread/realtime/transcript/delta")]
2106 ThreadRealtimeTranscriptDelta => "thread/realtime/transcript/delta" (v2::ThreadRealtimeTranscriptDeltaNotification),
2107 #[experimental("thread/realtime/transcript/done")]
2108 ThreadRealtimeTranscriptDone => "thread/realtime/transcript/done" (v2::ThreadRealtimeTranscriptDoneNotification),
2109 #[experimental("thread/realtime/outputAudio/delta")]
2110 ThreadRealtimeOutputAudioDelta => "thread/realtime/outputAudio/delta" (v2::ThreadRealtimeOutputAudioDeltaNotification),
2111 #[experimental("thread/realtime/sdp")]
2112 ThreadRealtimeSdp => "thread/realtime/sdp" (v2::ThreadRealtimeSdpNotification),
2113 #[experimental("thread/realtime/error")]
2114 ThreadRealtimeError => "thread/realtime/error" (v2::ThreadRealtimeErrorNotification),
2115 #[experimental("thread/realtime/closed")]
2116 ThreadRealtimeClosed => "thread/realtime/closed" (v2::ThreadRealtimeClosedNotification),
2117
2118 /// Notifies the user of world-writable directories on Windows, which cannot be protected by the sandbox.
2119 WindowsWorldWritableWarning => "windows/worldWritableWarning" (v2::WindowsWorldWritableWarningNotification),
2120 WindowsSandboxSetupCompleted => "windowsSandbox/setupCompleted" (v2::WindowsSandboxSetupCompletedNotification),
2121
2122 #[serde(rename = "account/login/completed")]
2123 #[ts(rename = "account/login/completed")]
2124 #[strum(serialize = "account/login/completed")]
2125 AccountLoginCompleted(v2::AccountLoginCompletedNotification),
2126
2127 }
2128
2129 /// Server notification envelope sent over app-server transports.
2130 ///
2131 /// `emitted_at_ms` records when app-server emitted the notification, before it
2132 /// is fanned out to individual connections.
2133 #[derive(Serialize, Deserialize, Debug, Clone, TS)]
2134 #[serde(rename_all = "camelCase")]
2135 pub struct ServerNotificationEnvelope {
2136 #[serde(flatten)]
2137 pub notification: ServerNotification,
2138 /// Unix timestamp (in milliseconds) when app-server emitted this notification.
2139 ///
2140 /// Optional so clients can decode notifications from older app-server
2141 /// versions. Current app-server versions always populate it.
2142 #[serde(default, skip_serializing_if = "Option::is_none")]
2143 #[ts(optional)]
2144 #[ts(type = "number")]
2145 pub emitted_at_ms: Option<i64>,
2146 }
2147
2148 client_notification_definitions! {
2149 Initialized,
2150 }
2151
2152 #[cfg(test)]
2153 mod tests {
2154 use super::*;
2155 use anyhow::Result;
2156 use codex_protocol::ThreadId;
2157 use codex_protocol::account::PlanType;
2158 use codex_protocol::config_types::MultiAgentMode;
2159 use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
2160 use codex_protocol::parse_command::ParsedCommand;
2161 use codex_protocol::protocol::CodexResponseHandoffMode;
2162 use codex_protocol::protocol::ConversationTextRole;
2163 use codex_protocol::protocol::RealtimeConversationVersion;
2164 use codex_protocol::protocol::RealtimeOutputModality;
2165 use codex_protocol::protocol::RealtimeVoice;
2166 use codex_utils_absolute_path::AbsolutePathBuf;
2167 use codex_utils_absolute_path::test_support::PathBufExt;
2168 use codex_utils_absolute_path::test_support::test_path_buf;
2169 use pretty_assertions::assert_eq;
2170 use serde_json::json;
2171 use std::path::PathBuf;
2172
2173 fn absolute_path_string(path: &str) -> String {
2174 let path = format!("/{}", path.trim_start_matches('/'));
2175 test_path_buf(&path).display().to_string()
2176 }
2177
2178 fn absolute_path(path: &str) -> AbsolutePathBuf {
2179 let path = format!("/{}", path.trim_start_matches('/'));
2180 test_path_buf(&path).abs()
2181 }
2182
2183 fn request_id() -> RequestId {
2184 const REQUEST_ID: i64 = 1;
2185 RequestId::Integer(REQUEST_ID)
2186 }
2187
2188 fn decode_client_request_through_json(
2189 request: &JSONRPCRequest,
2190 ) -> std::result::Result<ClientRequest, String> {
2191 serde_json::to_value(request)
2192 .and_then(serde_json::from_value)
2193 .map_err(|err| err.to_string())
2194 }
2195
2196 #[test]
2197 fn jsonrpc_request_conversion_preserves_serde_enum_decoding() {
2198 let requests = [
2199 JSONRPCRequest {
2200 id: RequestId::Integer(1),
2201 method: "thread/archive".to_string(),
2202 params: Some(json!({"threadId": "thread-1"})),
2203 trace: Some(codex_protocol::protocol::W3cTraceContext {
2204 traceparent: Some("traceparent".to_string()),
2205 tracestate: Some("tracestate".to_string()),
2206 }),
2207 },
2208 // Required params preserve distinct omitted and explicit-null errors.
2209 JSONRPCRequest {
2210 id: RequestId::Integer(2),
2211 method: "thread/archive".to_string(),
2212 params: None,
2213 trace: None,
2214 },
2215 JSONRPCRequest {
2216 id: RequestId::Integer(3),
2217 method: "thread/archive".to_string(),
2218 params: Some(serde_json::Value::Null),
2219 trace: None,
2220 },
2221 // Optional unit params preserve omitted, null, and empty-object behavior.
2222 JSONRPCRequest {
2223 id: RequestId::Integer(4),
2224 method: "memory/reset".to_string(),
2225 params: None,
2226 trace: None,
2227 },
2228 JSONRPCRequest {
2229 id: RequestId::Integer(5),
2230 method: "memory/reset".to_string(),
2231 params: Some(serde_json::Value::Null),
2232 trace: None,
2233 },
2234 JSONRPCRequest {
2235 id: RequestId::Integer(6),
2236 method: "memory/reset".to_string(),
2237 params: Some(json!({})),
2238 trace: None,
2239 },
2240 JSONRPCRequest {
2241 id: RequestId::Integer(7),
2242 method: "getConversationSummary".to_string(),
2243 params: Some(json!({
2244 "conversationId": "67e55044-10b1-426f-9247-bb680e5fe0c8"
2245 })),
2246 trace: None,
2247 },
2248 JSONRPCRequest {
2249 id: RequestId::Integer(8),
2250 method: "unknown/method".to_string(),
2251 params: Some(json!({})),
2252 trace: None,
2253 },
2254 ];
2255
2256 for request in requests {
2257 let expected = decode_client_request_through_json(&request);
2258 let actual = ClientRequest::try_from(request).map_err(|err| err.to_string());
2259 assert_eq!(actual, expected);
2260 }
2261 }
2262
2263 #[test]
2264 fn thread_section_move_round_trips_and_serializes_by_thread() -> Result<()> {
2265 assert_eq!(
2266 serde_json::to_value(v2::ThreadSortKey::SectionPosition)?,
2267 json!("section_position")
2268 );
2269 let request = ClientRequest::ThreadSectionMove {
2270 request_id: request_id(),
2271 params: v2::ThreadSectionMoveParams {
2272 thread_id: "thread-1".to_string(),
2273 section_id: Some("01984de2-8f74-7c91-a3b2-5c5e937cf318".to_string()),
2274 before_thread_id: Some("thread-2".to_string()),
2275 },
2276 };
2277 assert_eq!(
2278 serde_json::to_value(&request)?,
2279 json!({
2280 "method": "thread/section/move",
2281 "id": 1,
2282 "params": {
2283 "threadId": "thread-1",
2284 "sectionId": "01984de2-8f74-7c91-a3b2-5c5e937cf318",
2285 "beforeThreadId": "thread-2"
2286 }
2287 })
2288 );
2289 assert_eq!(
2290 request.serialization_scope(),
2291 Some(ClientRequestSerializationScope::Thread {
2292 thread_id: "thread-1".to_string()
2293 })
2294 );
2295
2296 let append_request = ClientRequest::try_from(JSONRPCRequest {
2297 id: request_id(),
2298 method: "thread/section/move".to_string(),
2299 params: Some(json!({
2300 "threadId": "thread-1",
2301 "sectionId": "01984de2-8f74-7c91-a3b2-5c5e937cf318"
2302 })),
2303 trace: None,
2304 })?;
2305 assert_eq!(
2306 append_request,
2307 ClientRequest::ThreadSectionMove {
2308 request_id: request_id(),
2309 params: v2::ThreadSectionMoveParams {
2310 thread_id: "thread-1".to_string(),
2311 section_id: Some("01984de2-8f74-7c91-a3b2-5c5e937cf318".to_string()),
2312 before_thread_id: None,
2313 },
2314 }
2315 );
2316
2317 let clear_request = ClientRequest::try_from(JSONRPCRequest {
2318 id: request_id(),
2319 method: "thread/section/move".to_string(),
2320 params: Some(json!({
2321 "threadId": "thread-1",
2322 "sectionId": null
2323 })),
2324 trace: None,
2325 })?;
2326 assert_eq!(
2327 clear_request,
2328 ClientRequest::ThreadSectionMove {
2329 request_id: request_id(),
2330 params: v2::ThreadSectionMoveParams {
2331 thread_id: "thread-1".to_string(),
2332 section_id: None,
2333 before_thread_id: None,
2334 },
2335 }
2336 );
2337 assert!(
2338 ClientRequest::try_from(JSONRPCRequest {
2339 id: request_id(),
2340 method: "thread/section/move".to_string(),
2341 params: Some(json!({ "threadId": "thread-1" })),
2342 trace: None,
2343 })
2344 .is_err()
2345 );
2346 Ok(())
2347 }
2348
2349 #[test]
2350 fn client_request_serialization_scope_covers_keyed_families() {
2351 let thread_id = "thread-1".to_string();
2352 let thread_resume = ClientRequest::ThreadResume {
2353 request_id: request_id(),
2354 params: v2::ThreadResumeParams {
2355 thread_id: thread_id.clone(),
2356 ..Default::default()
2357 },
2358 };
2359 assert_eq!(
2360 thread_resume.serialization_scope(),
2361 Some(ClientRequestSerializationScope::Thread {
2362 thread_id: thread_id.clone()
2363 })
2364 );
2365
2366 let thread_resume_with_path = ClientRequest::ThreadResume {
2367 request_id: request_id(),
2368 params: v2::ThreadResumeParams {
2369 thread_id: thread_id.clone(),
2370 path: Some(PathBuf::from("/tmp/resume-thread.jsonl")),
2371 ..Default::default()
2372 },
2373 };
2374 assert_eq!(
2375 thread_resume_with_path.serialization_scope(),
2376 Some(ClientRequestSerializationScope::Thread {
2377 thread_id: thread_id.clone()
2378 })
2379 );
2380
2381 let thread_fork = ClientRequest::ThreadFork {
2382 request_id: request_id(),
2383 params: v2::ThreadForkParams {
2384 thread_id: thread_id.clone(),
2385 path: Some(PathBuf::from("/tmp/source-thread.jsonl")),
2386 ..Default::default()
2387 },
2388 };
2389 assert_eq!(
2390 thread_fork.serialization_scope(),
2391 Some(ClientRequestSerializationScope::Thread { thread_id })
2392 );
2393
2394 let command_exec = ClientRequest::OneOffCommandExec {
2395 request_id: request_id(),
2396 params: v2::CommandExecParams {
2397 command: vec!["sleep".to_string(), "10".to_string()],
2398 process_id: Some("proc-1".to_string()),
2399 tty: false,
2400 stream_stdin: false,
2401 stream_stdout_stderr: false,
2402 output_bytes_cap: None,
2403 disable_output_cap: false,
2404 disable_timeout: false,
2405 timeout_ms: None,
2406 cwd: None,
2407 env: None,
2408 size: None,
2409 sandbox_policy: None,
2410 permission_profile: None,
2411 },
2412 };
2413 assert_eq!(
2414 command_exec.serialization_scope(),
2415 Some(ClientRequestSerializationScope::CommandExecProcess {
2416 process_id: "proc-1".to_string()
2417 })
2418 );
2419
2420 let fuzzy_update = ClientRequest::FuzzyFileSearchSessionUpdate {
2421 request_id: request_id(),
2422 params: FuzzyFileSearchSessionUpdateParams {
2423 session_id: "search-1".to_string(),
2424 query: "lib".to_string(),
2425 },
2426 };
2427 assert_eq!(
2428 fuzzy_update.serialization_scope(),
2429 Some(ClientRequestSerializationScope::FuzzyFileSearchSession {
2430 session_id: "search-1".to_string()
2431 })
2432 );
2433
2434 let fs_watch = ClientRequest::FsWatch {
2435 request_id: request_id(),
2436 params: v2::FsWatchParams {
2437 watch_id: "watch-1".to_string(),
2438 path: absolute_path("/tmp/repo"),
2439 },
2440 };
2441 assert_eq!(
2442 fs_watch.serialization_scope(),
2443 Some(ClientRequestSerializationScope::FsWatch {
2444 watch_id: "watch-1".to_string()
2445 })
2446 );
2447
2448 let plugin_install = ClientRequest::PluginInstall {
2449 request_id: request_id(),
2450 params: v2::PluginInstallParams {
2451 marketplace_path: Some(absolute_path("/tmp/marketplace")),
2452 remote_marketplace_name: None,
2453 install_attempt_id: None,
2454 plugin_name: "plugin-a".to_string(),
2455 },
2456 };
2457 assert_eq!(
2458 plugin_install.serialization_scope(),
2459 Some(ClientRequestSerializationScope::Global("config"))
2460 );
2461
2462 let skills_list = ClientRequest::SkillsList {
2463 request_id: request_id(),
2464 params: v2::SkillsListParams {
2465 cwds: Vec::new(),
2466 force_reload: false,
2467 },
2468 };
2469 assert_eq!(
2470 skills_list.serialization_scope(),
2471 Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
2472 );
2473
2474 let hooks_list = ClientRequest::HooksList {
2475 request_id: request_id(),
2476 params: v2::HooksListParams::default(),
2477 };
2478 assert_eq!(
2479 hooks_list.serialization_scope(),
2480 Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
2481 );
2482
2483 let skills_extra_roots_set = ClientRequest::SkillsExtraRootsSet {
2484 request_id: request_id(),
2485 params: v2::SkillsExtraRootsSetParams {
2486 extra_roots: vec![absolute_path("/tmp/skills")],
2487 },
2488 };
2489 assert_eq!(
2490 skills_extra_roots_set.serialization_scope(),
2491 Some(ClientRequestSerializationScope::Global("config"))
2492 );
2493
2494 let plugin_list = ClientRequest::PluginList {
2495 request_id: request_id(),
2496 params: v2::PluginListParams {
2497 cwds: None,
2498 marketplace_kinds: None,
2499 force_refetch: false,
2500 },
2501 };
2502 assert_eq!(plugin_list.serialization_scope(), None);
2503
2504 let plugin_read = ClientRequest::PluginRead {
2505 request_id: request_id(),
2506 params: v2::PluginReadParams {
2507 marketplace_path: Some(absolute_path("/tmp/marketplace")),
2508 remote_marketplace_name: None,
2509 plugin_name: "plugin-a".to_string(),
2510 },
2511 };
2512 assert_eq!(plugin_read.serialization_scope(), None);
2513
2514 let plugin_installed = ClientRequest::PluginInstalled {
2515 request_id: request_id(),
2516 params: v2::PluginInstalledParams {
2517 cwds: None,
2518 install_suggestion_plugin_names: None,
2519 },
2520 };
2521 assert_eq!(plugin_installed.serialization_scope(), None);
2522
2523 let plugin_uninstall = ClientRequest::PluginUninstall {
2524 request_id: request_id(),
2525 params: v2::PluginUninstallParams {
2526 plugin_id: "plugin-a".to_string(),
2527 },
2528 };
2529 assert_eq!(
2530 plugin_uninstall.serialization_scope(),
2531 Some(ClientRequestSerializationScope::Global("config"))
2532 );
2533
2534 let mcp_oauth = ClientRequest::McpServerOauthLogin {
2535 request_id: request_id(),
2536 params: v2::McpServerOauthLoginParams {
2537 name: "server-a".to_string(),
2538 thread_id: None,
2539 client_registration: None,
2540 scopes: None,
2541 timeout_secs: None,
2542 },
2543 };
2544 assert_eq!(
2545 mcp_oauth.serialization_scope(),
2546 Some(ClientRequestSerializationScope::McpOauth {
2547 server_name: "server-a".to_string()
2548 })
2549 );
2550
2551 let mcp_resource_read = ClientRequest::McpResourceRead {
2552 request_id: request_id(),
2553 params: v2::McpResourceReadParams {
2554 thread_id: Some("thread-1".to_string()),
2555 origin_call_id: None,
2556 server: "server-a".to_string(),
2557 uri: "file:///tmp/resource".to_string(),
2558 connector_id: None,
2559 target: None,
2560 },
2561 };
2562 assert_eq!(
2563 mcp_resource_read.serialization_scope(),
2564 Some(ClientRequestSerializationScope::Thread {
2565 thread_id: "thread-1".to_string()
2566 })
2567 );
2568
2569 let config_read = ClientRequest::ConfigRead {
2570 request_id: request_id(),
2571 params: v2::ConfigReadParams {
2572 include_layers: false,
2573 cwd: None,
2574 },
2575 };
2576 assert_eq!(
2577 config_read.serialization_scope(),
2578 Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
2579 );
2580
2581 let config_requirements_read = ClientRequest::ConfigRequirementsRead {
2582 request_id: request_id(),
2583 params: None,
2584 };
2585 assert_eq!(
2586 config_requirements_read.serialization_scope(),
2587 Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
2588 );
2589
2590 let account_read = ClientRequest::GetAccount {
2591 request_id: request_id(),
2592 params: v2::GetAccountParams {
2593 refresh_token: false,
2594 },
2595 };
2596 assert_eq!(
2597 account_read.serialization_scope(),
2598 Some(ClientRequestSerializationScope::Global("account-auth"))
2599 );
2600
2601 let thread_goal_set = ClientRequest::ThreadGoalSet {
2602 request_id: request_id(),
2603 params: v2::ThreadGoalSetParams {
2604 origin: None,
2605 thread_id: "goal-thread".to_string(),
2606 objective: Some("ship it".to_string()),
2607 status: None,
2608 token_budget: None,
2609 },
2610 };
2611 assert_eq!(
2612 thread_goal_set.serialization_scope(),
2613 Some(ClientRequestSerializationScope::Thread {
2614 thread_id: "goal-thread".to_string()
2615 })
2616 );
2617
2618 let guardian_approval = ClientRequest::ThreadApproveGuardianDeniedAction {
2619 request_id: request_id(),
2620 params: v2::ThreadApproveGuardianDeniedActionParams {
2621 thread_id: "guardian-thread".to_string(),
2622 event: json!({ "type": "guardian" }),
2623 },
2624 };
2625 assert_eq!(
2626 guardian_approval.serialization_scope(),
2627 Some(ClientRequestSerializationScope::Thread {
2628 thread_id: "guardian-thread".to_string()
2629 })
2630 );
2631
2632 let marketplace_remove = ClientRequest::MarketplaceRemove {
2633 request_id: request_id(),
2634 params: v2::MarketplaceRemoveParams {
2635 marketplace_name: "marketplace".to_string(),
2636 },
2637 };
2638 assert_eq!(
2639 marketplace_remove.serialization_scope(),
2640 Some(ClientRequestSerializationScope::Global("config"))
2641 );
2642
2643 let add_credits_nudge = ClientRequest::SendAddCreditsNudgeEmail {
2644 request_id: request_id(),
2645 params: v2::SendAddCreditsNudgeEmailParams {
2646 credit_type: v2::AddCreditsNudgeCreditType::Credits,
2647 },
2648 };
2649 assert_eq!(
2650 add_credits_nudge.serialization_scope(),
2651 Some(ClientRequestSerializationScope::Global("account-auth"))
2652 );
2653
2654 let environment_add = ClientRequest::EnvironmentAdd {
2655 request_id: request_id(),
2656 params: v2::EnvironmentAddParams {
2657 skills: None,
2658 auth_bearer_token: None,
2659 websocket_request_id: None,
2660 environment_id: "remote-a".to_string(),
2661 exec_server_url: "ws://127.0.0.1:8765".to_string(),
2662 connect_timeout_ms: None,
2663 },
2664 };
2665 assert_eq!(
2666 environment_add.serialization_scope(),
2667 Some(ClientRequestSerializationScope::Global("environment"))
2668 );
2669 }
2670
2671 #[test]
2672 fn client_request_serialization_scope_covers_unkeyed_representatives() {
2673 let initialize = ClientRequest::Initialize {
2674 request_id: request_id(),
2675 params: v1::InitializeParams {
2676 client_info: v1::ClientInfo {
2677 name: "test".to_string(),
2678 title: None,
2679 version: "0.1.0".to_string(),
2680 },
2681 capabilities: None,
2682 },
2683 };
2684 assert_eq!(initialize.serialization_scope(), None);
2685
2686 let thread_start = ClientRequest::ThreadStart {
2687 request_id: request_id(),
2688 params: v2::ThreadStartParams::default(),
2689 };
2690 assert_eq!(thread_start.serialization_scope(), None);
2691
2692 let command_exec = ClientRequest::OneOffCommandExec {
2693 request_id: request_id(),
2694 params: v2::CommandExecParams {
2695 command: vec!["true".to_string()],
2696 process_id: None,
2697 tty: false,
2698 stream_stdin: false,
2699 stream_stdout_stderr: false,
2700 output_bytes_cap: None,
2701 disable_output_cap: false,
2702 disable_timeout: false,
2703 timeout_ms: None,
2704 cwd: None,
2705 env: None,
2706 size: None,
2707 sandbox_policy: None,
2708 permission_profile: None,
2709 },
2710 };
2711 assert_eq!(command_exec.serialization_scope(), None);
2712
2713 let fs_read = ClientRequest::FsReadFile {
2714 request_id: request_id(),
2715 params: v2::FsReadFileParams {
2716 path: absolute_path("/tmp/file.txt"),
2717 },
2718 };
2719 assert_eq!(fs_read.serialization_scope(), None);
2720
2721 let thread_turns_list = ClientRequest::ThreadTurnsList {
2722 request_id: request_id(),
2723 params: v2::ThreadTurnsListParams {
2724 thread_id: "thread-1".to_string(),
2725 cursor: None,
2726 limit: None,
2727 sort_direction: None,
2728 items_view: None,
2729 },
2730 };
2731 assert_eq!(thread_turns_list.serialization_scope(), None);
2732
2733 let thread_items_list = ClientRequest::ThreadItemsList {
2734 request_id: request_id(),
2735 params: v2::ThreadItemsListParams {
2736 thread_id: "thread-1".to_string(),
2737 turn_id: None,
2738 cursor: None,
2739 limit: None,
2740 sort_direction: None,
2741 },
2742 };
2743 assert_eq!(thread_items_list.serialization_scope(), None);
2744
2745 let mcp_resource_read = ClientRequest::McpResourceRead {
2746 request_id: request_id(),
2747 params: v2::McpResourceReadParams {
2748 thread_id: None,
2749 origin_call_id: None,
2750 server: "server-a".to_string(),
2751 uri: "file:///tmp/resource".to_string(),
2752 connector_id: None,
2753 target: None,
2754 },
2755 };
2756 assert_eq!(mcp_resource_read.serialization_scope(), None);
2757
2758 let remote_control_pairing_start = ClientRequest::RemoteControlPairingStart {
2759 request_id: request_id(),
2760 params: v2::RemoteControlPairingStartParams::default(),
2761 };
2762 assert_eq!(
2763 remote_control_pairing_start.serialization_scope(),
2764 Some(ClientRequestSerializationScope::Global(
2765 "remote-control-pairing"
2766 ))
2767 );
2768 let remote_control_pairing_status = ClientRequest::RemoteControlPairingStatus {
2769 request_id: request_id(),
2770 params: v2::RemoteControlPairingStatusParams {
2771 pairing_code: Some("pairing-code".to_string()),
2772 manual_pairing_code: None,
2773 },
2774 };
2775 assert_eq!(
2776 remote_control_pairing_status.serialization_scope(),
2777 Some(ClientRequestSerializationScope::GlobalSharedRead(
2778 "remote-control-pairing"
2779 ))
2780 );
2781 let remote_control_clients_list = ClientRequest::RemoteControlClientsList {
2782 request_id: request_id(),
2783 params: v2::RemoteControlClientsListParams::default(),
2784 };
2785 assert_eq!(
2786 remote_control_clients_list.serialization_scope(),
2787 Some(ClientRequestSerializationScope::GlobalSharedRead(
2788 "remote-control-clients"
2789 ))
2790 );
2791 let remote_control_clients_revoke = ClientRequest::RemoteControlClientsRevoke {
2792 request_id: request_id(),
2793 params: v2::RemoteControlClientsRevokeParams {
2794 environment_id: "environment-id".to_string(),
2795 client_id: "client-id".to_string(),
2796 },
2797 };
2798 assert_eq!(
2799 remote_control_clients_revoke.serialization_scope(),
2800 Some(ClientRequestSerializationScope::Global(
2801 "remote-control-clients"
2802 ))
2803 );
2804 }
2805
2806 #[test]
2807 fn serialize_get_conversation_summary() -> Result<()> {
2808 let request = ClientRequest::GetConversationSummary {
2809 request_id: RequestId::Integer(42),
2810 params: v1::GetConversationSummaryParams::ThreadId {
2811 conversation_id: ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8")?,
2812 },
2813 };
2814 assert_eq!(
2815 json!({
2816 "method": "getConversationSummary",
2817 "id": 42,
2818 "params": {
2819 "conversationId": "67e55044-10b1-426f-9247-bb680e5fe0c8"
2820 }
2821 }),
2822 serde_json::to_value(&request)?,
2823 );
2824 Ok(())
2825 }
2826
2827 #[test]
2828 fn serialize_initialize_capabilities() -> Result<()> {
2829 let request = ClientRequest::Initialize {
2830 request_id: RequestId::Integer(42),
2831 params: v1::InitializeParams {
2832 client_info: v1::ClientInfo {
2833 name: "codex_vscode".to_string(),
2834 title: Some("Codex VS Code Extension".to_string()),
2835 version: "0.1.0".to_string(),
2836 },
2837 capabilities: Some(v1::InitializeCapabilities {
2838 explicit_gateway_oauth: false,
2839 experimental_api: true,
2840 request_attestation: true,
2841 mcp_server_openai_form_elicitation: true,
2842 opt_out_notification_methods: Some(vec![
2843 "thread/started".to_string(),
2844 "item/agentMessage/delta".to_string(),
2845 ]),
2846 extensions: Some(std::collections::HashMap::from([(
2847 "io.modelcontextprotocol/ui".to_string(),
2848 json!({
2849 "mimeTypes": ["text/html;profile=mcp-app"],
2850 }),
2851 )])),
2852 }),
2853 },
2854 };
2855
2856 assert_eq!(
2857 json!({
2858 "method": "initialize",
2859 "id": 42,
2860 "params": {
2861 "clientInfo": {
2862 "name": "codex_vscode",
2863 "title": "Codex VS Code Extension",
2864 "version": "0.1.0"
2865 },
2866 "capabilities": {
2867 "experimentalApi": true,
2868 "requestAttestation": true,
2869 "mcpServerOpenaiFormElicitation": true,
2870 "optOutNotificationMethods": [
2871 "thread/started",
2872 "item/agentMessage/delta"
2873 ],
2874 "extensions": {
2875 "io.modelcontextprotocol/ui": {
2876 "mimeTypes": ["text/html;profile=mcp-app"]
2877 }
2878 }
2879 }
2880 }
2881 }),
2882 serde_json::to_value(&request)?,
2883 );
2884 Ok(())
2885 }
2886
2887 #[test]
2888 fn deserialize_initialize_capabilities() -> Result<()> {
2889 let request: ClientRequest = serde_json::from_value(json!({
2890 "method": "initialize",
2891 "id": 42,
2892 "params": {
2893 "clientInfo": {
2894 "name": "codex_vscode",
2895 "title": "Codex VS Code Extension",
2896 "version": "0.1.0"
2897 },
2898 "capabilities": {
2899 "experimentalApi": true,
2900 "requestAttestation": true,
2901 "mcpServerOpenaiFormElicitation": true,
2902 "optOutNotificationMethods": [
2903 "thread/started",
2904 "item/agentMessage/delta"
2905 ],
2906 "extensions": {
2907 "io.modelcontextprotocol/ui": {
2908 "mimeTypes": ["text/html;profile=mcp-app"]
2909 }
2910 }
2911 }
2912 }
2913 }))?;
2914
2915 assert_eq!(
2916 request,
2917 ClientRequest::Initialize {
2918 request_id: RequestId::Integer(42),
2919 params: v1::InitializeParams {
2920 client_info: v1::ClientInfo {
2921 name: "codex_vscode".to_string(),
2922 title: Some("Codex VS Code Extension".to_string()),
2923 version: "0.1.0".to_string(),
2924 },
2925 capabilities: Some(v1::InitializeCapabilities {
2926 explicit_gateway_oauth: false,
2927 experimental_api: true,
2928 request_attestation: true,
2929 mcp_server_openai_form_elicitation: true,
2930 opt_out_notification_methods: Some(vec![
2931 "thread/started".to_string(),
2932 "item/agentMessage/delta".to_string(),
2933 ]),
2934 extensions: Some(std::collections::HashMap::from([(
2935 "io.modelcontextprotocol/ui".to_string(),
2936 json!({
2937 "mimeTypes": ["text/html;profile=mcp-app"],
2938 }),
2939 )])),
2940 }),
2941 },
2942 }
2943 );
2944 Ok(())
2945 }
2946
2947 #[test]
2948 fn conversation_id_serializes_as_plain_string() -> Result<()> {
2949 let id = ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8")?;
2950
2951 assert_eq!(
2952 json!("67e55044-10b1-426f-9247-bb680e5fe0c8"),
2953 serde_json::to_value(id)?
2954 );
2955 Ok(())
2956 }
2957
2958 #[test]
2959 fn conversation_id_deserializes_from_plain_string() -> Result<()> {
2960 let id: ThreadId = serde_json::from_value(json!("67e55044-10b1-426f-9247-bb680e5fe0c8"))?;
2961
2962 assert_eq!(
2963 ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8")?,
2964 id,
2965 );
2966 Ok(())
2967 }
2968
2969 #[test]
2970 fn serialize_client_notification() -> Result<()> {
2971 let notification = ClientNotification::Initialized;
2972 // Note there is no "params" field for this notification.
2973 assert_eq!(
2974 json!({
2975 "method": "initialized",
2976 }),
2977 serde_json::to_value(&notification)?,
2978 );
2979 Ok(())
2980 }
2981
2982 #[test]
2983 fn serialize_server_request() -> Result<()> {
2984 let conversation_id = ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8")?;
2985 let params = v1::ExecCommandApprovalParams {
2986 conversation_id,
2987 call_id: "call-42".to_string(),
2988 approval_id: Some("approval-42".to_string()),
2989 command: vec!["echo".to_string(), "hello".to_string()],
2990 cwd: PathBuf::from("/tmp"),
2991 reason: Some("because tests".to_string()),
2992 parsed_cmd: vec![ParsedCommand::Unknown {
2993 cmd: "echo hello".to_string(),
2994 }],
2995 };
2996 let request = ServerRequest::ExecCommandApproval {
2997 request_id: RequestId::Integer(7),
2998 params: params.clone(),
2999 };
3000
3001 assert_eq!(
3002 json!({
3003 "method": "execCommandApproval",
3004 "id": 7,
3005 "params": {
3006 "conversationId": "67e55044-10b1-426f-9247-bb680e5fe0c8",
3007 "callId": "call-42",
3008 "approvalId": "approval-42",
3009 "command": ["echo", "hello"],
3010 "cwd": "/tmp",
3011 "reason": "because tests",
3012 "parsedCmd": [
3013 {
3014 "type": "unknown",
3015 "cmd": "echo hello"
3016 }
3017 ]
3018 }
3019 }),
3020 serde_json::to_value(&request)?,
3021 );
3022
3023 let payload = ServerRequestPayload::ExecCommandApproval(params);
3024 assert_eq!(request.id(), &RequestId::Integer(7));
3025 assert_eq!(payload.request_with_id(RequestId::Integer(7)), request);
3026 Ok(())
3027 }
3028
3029 #[test]
3030 fn serialize_chatgpt_auth_tokens_refresh_request() -> Result<()> {
3031 let request = ServerRequest::ChatgptAuthTokensRefresh {
3032 request_id: RequestId::Integer(8),
3033 params: v2::ChatgptAuthTokensRefreshParams {
3034 reason: v2::ChatgptAuthTokensRefreshReason::Unauthorized,
3035 previous_account_id: Some("org-123".to_string()),
3036 },
3037 };
3038 assert_eq!(
3039 json!({
3040 "method": "account/chatgptAuthTokens/refresh",
3041 "id": 8,
3042 "params": {
3043 "reason": "unauthorized",
3044 "previousAccountId": "org-123"
3045 }
3046 }),
3047 serde_json::to_value(&request)?,
3048 );
3049 Ok(())
3050 }
3051
3052 #[test]
3053 fn serialize_attestation_generate_request() -> Result<()> {
3054 let params = v2::AttestationGenerateParams {};
3055 let request = ServerRequest::AttestationGenerate {
3056 request_id: RequestId::Integer(9),
3057 params: params.clone(),
3058 };
3059 assert_eq!(
3060 json!({
3061 "method": "attestation/generate",
3062 "id": 9,
3063 "params": {}
3064 }),
3065 serde_json::to_value(&request)?,
3066 );
3067
3068 let payload = ServerRequestPayload::AttestationGenerate(params);
3069 assert_eq!(request.id(), &RequestId::Integer(9));
3070 assert_eq!(payload.request_with_id(RequestId::Integer(9)), request);
3071 Ok(())
3072 }
3073
3074 #[test]
3075 fn serialize_current_time_read_request() -> Result<()> {
3076 let params = v2::CurrentTimeReadParams {
3077 thread_id: "thread-123".to_string(),
3078 };
3079 let request = ServerRequest::CurrentTimeRead {
3080 request_id: RequestId::Integer(10),
3081 params: params.clone(),
3082 };
3083 assert_eq!(
3084 json!({
3085 "method": "currentTime/read",
3086 "id": 10,
3087 "params": {
3088 "threadId": "thread-123"
3089 }
3090 }),
3091 serde_json::to_value(&request)?,
3092 );
3093
3094 let payload = ServerRequestPayload::CurrentTimeRead(params);
3095 assert_eq!(request.id(), &RequestId::Integer(10));
3096 assert_eq!(payload.request_with_id(RequestId::Integer(10)), request);
3097 Ok(())
3098 }
3099
3100 #[test]
3101 fn serialize_server_response() -> Result<()> {
3102 let response = ServerResponse::CommandExecutionRequestApproval {
3103 request_id: RequestId::Integer(8),
3104 response: v2::CommandExecutionRequestApprovalResponse {
3105 decision: v2::CommandExecutionApprovalDecision::AcceptForSession,
3106 },
3107 };
3108
3109 assert_eq!(response.id(), &RequestId::Integer(8));
3110 assert_eq!(response.method(), "item/commandExecution/requestApproval");
3111 assert_eq!(
3112 json!({
3113 "method": "item/commandExecution/requestApproval",
3114 "id": 8,
3115 "response": {
3116 "decision": "acceptForSession"
3117 }
3118 }),
3119 serde_json::to_value(&response)?,
3120 );
3121 Ok(())
3122 }
3123
3124 #[test]
3125 fn serialize_mcp_server_elicitation_request() -> Result<()> {
3126 let requested_schema: v2::McpElicitationSchema = serde_json::from_value(json!({
3127 "type": "object",
3128 "properties": {
3129 "confirmed": {
3130 "type": "boolean"
3131 }
3132 },
3133 "required": ["confirmed"]
3134 }))?;
3135 let params = v2::McpServerElicitationRequestParams {
3136 thread_id: "thr_123".to_string(),
3137 turn_id: Some("turn_123".to_string()),
3138 server_name: "codex_apps".to_string(),
3139 request: v2::McpServerElicitationRequest::Form {
3140 meta: Some(json!({
3141 "suggestion_id": "request_plugin_install_install-github"
3142 })),
3143 message: "Allow this request?".to_string(),
3144 requested_schema,
3145 },
3146 };
3147 let request = ServerRequest::McpServerElicitationRequest {
3148 request_id: RequestId::Integer(9),
3149 params: params.clone(),
3150 };
3151
3152 assert_eq!(
3153 json!({
3154 "method": "mcpServer/elicitation/request",
3155 "id": 9,
3156 "params": {
3157 "threadId": "thr_123",
3158 "turnId": "turn_123",
3159 "serverName": "codex_apps",
3160 "mode": "form",
3161 "_meta": {
3162 "suggestion_id": "request_plugin_install_install-github"
3163 },
3164 "message": "Allow this request?",
3165 "requestedSchema": {
3166 "type": "object",
3167 "properties": {
3168 "confirmed": {
3169 "type": "boolean"
3170 }
3171 },
3172 "required": ["confirmed"]
3173 }
3174 }
3175 }),
3176 serde_json::to_value(&request)?,
3177 );
3178
3179 let payload = ServerRequestPayload::McpServerElicitationRequest(params);
3180 assert_eq!(request.id(), &RequestId::Integer(9));
3181 assert_eq!(payload.request_with_id(RequestId::Integer(9)), request);
3182 Ok(())
3183 }
3184
3185 #[test]
3186 fn serialize_get_account_rate_limits() -> Result<()> {
3187 let request = ClientRequest::GetAccountRateLimits {
3188 request_id: RequestId::Integer(1),
3189 params: None,
3190 };
3191 assert_eq!(request.id(), &RequestId::Integer(1));
3192 assert_eq!(
3193 json!({
3194 "method": "account/rateLimits/read",
3195 "id": 1,
3196 }),
3197 serde_json::to_value(&request)?,
3198 );
3199 Ok(())
3200 }
3201
3202 #[test]
3203 fn serialize_get_account_token_usage() -> Result<()> {
3204 let request = ClientRequest::GetAccountTokenUsage {
3205 request_id: RequestId::Integer(1),
3206 params: None,
3207 };
3208 assert_eq!(request.id(), &RequestId::Integer(1));
3209 assert_eq!(
3210 json!({
3211 "method": "account/usage/read",
3212 "id": 1,
3213 }),
3214 serde_json::to_value(&request)?,
3215 );
3216 Ok(())
3217 }
3218
3219 #[test]
3220 fn serialize_get_account_thread_usage() -> Result<()> {
3221 let request = ClientRequest::GetAccountTokenUsage {
3222 request_id: RequestId::Integer(1),
3223 params: Some(v2::GetAccountTokenUsageParams {
3224 thread_id: Some("thread-123".to_string()),
3225 }),
3226 };
3227 assert_eq!(
3228 json!({
3229 "method": "account/usage/read",
3230 "id": 1,
3231 "params": { "threadId": "thread-123" },
3232 }),
3233 serde_json::to_value(&request)?,
3234 );
3235 Ok(())
3236 }
3237
3238 #[test]
3239 fn deserialize_legacy_get_account_token_usage_response() -> Result<()> {
3240 let response: v2::GetAccountTokenUsageResponse = serde_json::from_value(json!({
3241 "summary": {
3242 "lifetimeTokens": null,
3243 "peakDailyTokens": null,
3244 "longestRunningTurnSec": null,
3245 "currentStreakDays": null,
3246 "longestStreakDays": null,
3247 },
3248 "dailyUsageBuckets": null,
3249 }))?;
3250
3251 assert_eq!(
3252 response,
3253 v2::GetAccountTokenUsageResponse {
3254 summary: v2::AccountTokenUsageSummary {
3255 lifetime_tokens: None,
3256 peak_daily_tokens: None,
3257 longest_running_turn_sec: None,
3258 current_streak_days: None,
3259 longest_streak_days: None,
3260 },
3261 daily_usage_buckets: None,
3262 thread_usage: None,
3263 },
3264 );
3265 assert_eq!(serde_json::to_value(response)?["threadUsage"], json!(null));
3266 Ok(())
3267 }
3268
3269 #[test]
3270 fn serialize_get_workspace_messages() -> Result<()> {
3271 let request = ClientRequest::GetWorkspaceMessages {
3272 request_id: RequestId::Integer(1),
3273 params: None,
3274 };
3275 assert_eq!(request.id(), &RequestId::Integer(1));
3276 assert_eq!(
3277 json!({
3278 "method": "account/workspaceMessages/read",
3279 "id": 1,
3280 }),
3281 serde_json::to_value(&request)?,
3282 );
3283 Ok(())
3284 }
3285
3286 #[test]
3287 fn serialize_client_response() -> Result<()> {
3288 let cwd = absolute_path("/tmp");
3289 let response = ClientResponse::ThreadStart {
3290 request_id: RequestId::Integer(7),
3291 response: v2::ThreadStartResponse {
3292 disabled_plugin_ids: Vec::new(),
3293 thread: v2::Thread {
3294 originator: None,
3295 environments: None,
3296 id: "67e55044-10b1-426f-9247-bb680e5fe0c8".to_string(),
3297 extra: None,
3298 session_id: "67e55044-10b1-426f-9247-bb680e5fe0c7".to_string(),
3299 forked_from_id: None,
3300 parent_thread_id: None,
3301 preview: "first prompt".to_string(),
3302 ephemeral: true,
3303 section: None,
3304 section_entered_at: None,
3305 project_id: None,
3306 history_mode: Default::default(),
3307 model_provider: "openai".to_string(),
3308 model: None,
3309 reasoning_effort: None,
3310 created_at: 1,
3311 updated_at: 2,
3312 recency_at: Some(3),
3313 status: v2::ThreadStatus::Idle,
3314 path: None,
3315 cwd: cwd.clone(),
3316 cli_version: "0.0.0".to_string(),
3317 source: v2::SessionSource::Exec,
3318 can_accept_direct_input: None,
3319 thread_source: None,
3320 agent_nickname: None,
3321 agent_role: None,
3322 git_info: None,
3323 name: None,
3324 daybreak_enabled: None,
3325 turns: Vec::new(),
3326 },
3327 model: "gpt-5".to_string(),
3328 model_provider: "openai".to_string(),
3329 service_tier: None,
3330 cwd,
3331 runtime_workspace_roots: Vec::new(),
3332 instruction_sources: vec![
3333 codex_utils_path_uri::LegacyAppPathString::from_abs_path(&absolute_path(
3334 "/tmp/AGENTS.md",
3335 )),
3336 ],
3337 approval_policy: v2::AskForApproval::OnRequest,
3338 approvals_reviewer: v2::ApprovalsReviewer::User,
3339 sandbox: v2::SandboxPolicy::DangerFullAccess,
3340 active_permission_profile: None,
3341 reasoning_effort: None,
3342 multi_agent_mode: MultiAgentMode::ExplicitRequestOnly,
3343 },
3344 };
3345
3346 assert_eq!(response.id(), &RequestId::Integer(7));
3347 assert_eq!(response.method(), "thread/start");
3348 assert_eq!(
3349 json!({
3350 "method": "thread/start",
3351 "id": 7,
3352 "response": {
3353 "thread": {
3354 "id": "67e55044-10b1-426f-9247-bb680e5fe0c8",
3355 "environments": null,
3356 "extra": null,
3357 "sessionId": "67e55044-10b1-426f-9247-bb680e5fe0c7",
3358 "forkedFromId": null,
3359 "parentThreadId": null,
3360 "preview": "first prompt",
3361 "ephemeral": true,
3362 "section": null,
3363 "sectionEnteredAt": null,
3364 "projectId": null,
3365 "historyMode": "legacy",
3366 "modelProvider": "openai",
3367 "model": null,
3368 "reasoningEffort": null,
3369 "createdAt": 1,
3370 "updatedAt": 2,
3371 "recencyAt": 3,
3372 "status": {
3373 "type": "idle"
3374 },
3375 "path": null,
3376 "cwd": absolute_path_string("tmp"),
3377 "cliVersion": "0.0.0",
3378 "originator": null,
3379 "source": "exec",
3380 "canAcceptDirectInput": null,
3381 "threadSource": null,
3382 "agentNickname": null,
3383 "agentRole": null,
3384 "gitInfo": null,
3385 "name": null,
3386 "daybreakEnabled": null,
3387 "turns": []
3388 },
3389 "model": "gpt-5",
3390 "modelProvider": "openai",
3391 "serviceTier": null,
3392 "disabledPluginIds": [],
3393 "cwd": absolute_path_string("tmp"),
3394 "runtimeWorkspaceRoots": [],
3395 "instructionSources": [absolute_path_string("tmp/AGENTS.md")],
3396 "approvalPolicy": "on-request",
3397 "approvalsReviewer": "user",
3398 "sandbox": {
3399 "type": "dangerFullAccess"
3400 },
3401 "activePermissionProfile": null,
3402 "reasoningEffort": null,
3403 "multiAgentMode": "explicitRequestOnly"
3404 }
3405 }),
3406 serde_json::to_value(&response)?,
3407 );
3408 Ok(())
3409 }
3410
3411 #[test]
3412 fn serialize_config_requirements_read() -> Result<()> {
3413 let request = ClientRequest::ConfigRequirementsRead {
3414 request_id: RequestId::Integer(1),
3415 params: None,
3416 };
3417 assert_eq!(
3418 json!({
3419 "method": "configRequirements/read",
3420 "id": 1,
3421 }),
3422 serde_json::to_value(&request)?,
3423 );
3424 Ok(())
3425 }
3426
3427 #[test]
3428 fn serialize_account_login_api_key() -> Result<()> {
3429 let request = ClientRequest::LoginAccount {
3430 request_id: RequestId::Integer(2),
3431 params: v2::LoginAccountParams::ApiKey {
3432 api_key: "secret".to_string(),
3433 },
3434 };
3435 assert_eq!(
3436 json!({
3437 "method": "account/login/start",
3438 "id": 2,
3439 "params": {
3440 "type": "apiKey",
3441 "apiKey": "secret"
3442 }
3443 }),
3444 serde_json::to_value(&request)?,
3445 );
3446 Ok(())
3447 }
3448
3449 #[test]
3450 fn serialize_account_login_amazon_bedrock() -> Result<()> {
3451 for (params, expected_params) in [
3452 (
3453 v2::LoginAccountParams::AmazonBedrock {
3454 api_key: "secret".to_string(),
3455 region: "us-west-2".to_string(),
3456 },
3457 json!({
3458 "type": "amazonBedrock",
3459 "apiKey": "secret",
3460 "region": "us-west-2"
3461 }),
3462 ),
3463 (
3464 v2::LoginAccountParams::AmazonBedrockAccessKeys {
3465 access_key_id: "access-key-id".to_string(),
3466 secret_access_key: "secret-access-key".to_string(),
3467 session_token: Some("session-token".to_string()),
3468 region: "us-west-2".to_string(),
3469 },
3470 json!({
3471 "type": "amazonBedrockAccessKeys",
3472 "accessKeyId": "access-key-id",
3473 "secretAccessKey": "secret-access-key",
3474 "sessionToken": "session-token",
3475 "region": "us-west-2"
3476 }),
3477 ),
3478 ] {
3479 let request = ClientRequest::LoginAccount {
3480 request_id: RequestId::Integer(2),
3481 params,
3482 };
3483 assert_eq!(
3484 json!({
3485 "method": "account/login/start",
3486 "id": 2,
3487 "params": expected_params,
3488 }),
3489 serde_json::to_value(&request)?,
3490 );
3491 }
3492 assert_eq!(
3493 json!({"type": "amazonBedrock"}),
3494 serde_json::to_value(v2::LoginAccountResponse::AmazonBedrock {})?,
3495 );
3496 Ok(())
3497 }
3498
3499 #[test]
3500 fn serialize_account_login_chatgpt() -> Result<()> {
3501 let request = ClientRequest::LoginAccount {
3502 request_id: RequestId::Integer(3),
3503 params: v2::LoginAccountParams::Chatgpt {
3504 app_brand: None,
3505 codex_streamlined_login: false,
3506 use_hosted_login_success_page: false,
3507 },
3508 };
3509 assert_eq!(
3510 json!({
3511 "method": "account/login/start",
3512 "id": 3,
3513 "params": {
3514 "type": "chatgpt",
3515 "appBrand": null
3516 }
3517 }),
3518 serde_json::to_value(&request)?,
3519 );
3520 Ok(())
3521 }
3522
3523 #[test]
3524 fn serialize_account_login_chatgpt_streamlined() -> Result<()> {
3525 let request = ClientRequest::LoginAccount {
3526 request_id: RequestId::Integer(3),
3527 params: v2::LoginAccountParams::Chatgpt {
3528 app_brand: None,
3529 codex_streamlined_login: true,
3530 use_hosted_login_success_page: false,
3531 },
3532 };
3533 assert_eq!(
3534 json!({
3535 "method": "account/login/start",
3536 "id": 3,
3537 "params": {
3538 "type": "chatgpt",
3539 "appBrand": null,
3540 "codexStreamlinedLogin": true
3541 }
3542 }),
3543 serde_json::to_value(&request)?,
3544 );
3545 Ok(())
3546 }
3547
3548 #[test]
3549 fn serialize_account_login_chatgpt_with_hosted_success_page() -> Result<()> {
3550 let request = ClientRequest::LoginAccount {
3551 request_id: RequestId::Integer(3),
3552 params: v2::LoginAccountParams::Chatgpt {
3553 app_brand: Some(v2::LoginAppBrand::Chatgpt),
3554 codex_streamlined_login: true,
3555 use_hosted_login_success_page: true,
3556 },
3557 };
3558 assert_eq!(
3559 json!({
3560 "method": "account/login/start",
3561 "id": 3,
3562 "params": {
3563 "type": "chatgpt",
3564 "appBrand": "chatgpt",
3565 "codexStreamlinedLogin": true,
3566 "useHostedLoginSuccessPage": true
3567 }
3568 }),
3569 serde_json::to_value(&request)?,
3570 );
3571 Ok(())
3572 }
3573
3574 #[test]
3575 fn serialize_account_login_chatgpt_device_code() -> Result<()> {
3576 let request = ClientRequest::LoginAccount {
3577 request_id: RequestId::Integer(4),
3578 params: v2::LoginAccountParams::ChatgptDeviceCode,
3579 };
3580 assert_eq!(
3581 json!({
3582 "method": "account/login/start",
3583 "id": 4,
3584 "params": {
3585 "type": "chatgptDeviceCode"
3586 }
3587 }),
3588 serde_json::to_value(&request)?,
3589 );
3590 Ok(())
3591 }
3592
3593 #[test]
3594 fn serialize_account_logout() -> Result<()> {
3595 let request = ClientRequest::LogoutAccount {
3596 request_id: RequestId::Integer(5),
3597 params: None,
3598 };
3599 assert_eq!(
3600 json!({
3601 "method": "account/logout",
3602 "id": 5,
3603 }),
3604 serde_json::to_value(&request)?,
3605 );
3606 Ok(())
3607 }
3608
3609 #[test]
3610 fn serialize_account_login_chatgpt_auth_tokens() -> Result<()> {
3611 let request = ClientRequest::LoginAccount {
3612 request_id: RequestId::Integer(6),
3613 params: v2::LoginAccountParams::ChatgptAuthTokens {
3614 access_token: "access-token".to_string(),
3615 chatgpt_account_id: "org-123".to_string(),
3616 chatgpt_plan_type: Some("business".to_string()),
3617 },
3618 };
3619 assert_eq!(
3620 json!({
3621 "method": "account/login/start",
3622 "id": 6,
3623 "params": {
3624 "type": "chatgptAuthTokens",
3625 "accessToken": "access-token",
3626 "chatgptAccountId": "org-123",
3627 "chatgptPlanType": "business"
3628 }
3629 }),
3630 serde_json::to_value(&request)?,
3631 );
3632 Ok(())
3633 }
3634
3635 #[test]
3636 fn serialize_get_account() -> Result<()> {
3637 let request = ClientRequest::GetAccount {
3638 request_id: RequestId::Integer(6),
3639 params: v2::GetAccountParams {
3640 refresh_token: false,
3641 },
3642 };
3643 assert_eq!(
3644 json!({
3645 "method": "account/read",
3646 "id": 6,
3647 "params": {}
3648 }),
3649 serde_json::to_value(&request)?,
3650 );
3651 let request = ClientRequest::GetAccount {
3652 request_id: RequestId::Integer(7),
3653 params: v2::GetAccountParams {
3654 refresh_token: true,
3655 },
3656 };
3657 assert_eq!(
3658 json!({
3659 "method": "account/read",
3660 "id": 7,
3661 "params": {
3662 "refreshToken": true
3663 }
3664 }),
3665 serde_json::to_value(&request)?,
3666 );
3667 Ok(())
3668 }
3669
3670 #[test]
3671 fn account_serializes_fields_in_camel_case() -> Result<()> {
3672 let api_key = v2::Account::ApiKey {};
3673 assert_eq!(
3674 json!({
3675 "type": "apiKey",
3676 }),
3677 serde_json::to_value(&api_key)?,
3678 );
3679
3680 let chatgpt = v2::Account::Chatgpt {
3681 email: Some("user@example.com".to_string()),
3682 plan_type: PlanType::Plus,
3683 workspace_name: None,
3684 };
3685 assert_eq!(
3686 json!({
3687 "type": "chatgpt",
3688 "email": "user@example.com",
3689 "planType": "plus",
3690 "workspaceName": null,
3691 }),
3692 serde_json::to_value(&chatgpt)?,
3693 );
3694
3695 let chatgpt_without_email = v2::Account::Chatgpt {
3696 email: None,
3697 plan_type: PlanType::Pro,
3698 workspace_name: None,
3699 };
3700 assert_eq!(
3701 json!({
3702 "type": "chatgpt",
3703 "email": null,
3704 "planType": "pro",
3705 "workspaceName": null,
3706 }),
3707 serde_json::to_value(&chatgpt_without_email)?,
3708 );
3709
3710 let codex_managed_bedrock = v2::Account::AmazonBedrock {
3711 uses_codex_managed_credentials: true,
3712 };
3713 assert_eq!(
3714 json!({
3715 "type": "amazonBedrock",
3716 "usesCodexManagedCredentials": true,
3717 }),
3718 serde_json::to_value(&codex_managed_bedrock)?,
3719 );
3720
3721 let externally_managed_bedrock = v2::Account::AmazonBedrock {
3722 uses_codex_managed_credentials: false,
3723 };
3724 assert_eq!(
3725 json!({
3726 "type": "amazonBedrock",
3727 "usesCodexManagedCredentials": false,
3728 }),
3729 serde_json::to_value(&externally_managed_bedrock)?,
3730 );
3731
3732 Ok(())
3733 }
3734
3735 #[test]
3736 fn account_defaults_legacy_bedrock_managed_credentials_flag() -> Result<()> {
3737 assert_eq!(
3738 v2::Account::AmazonBedrock {
3739 uses_codex_managed_credentials: false,
3740 },
3741 serde_json::from_value(json!({
3742 "type": "amazonBedrock",
3743 }))?,
3744 );
3745 Ok(())
3746 }
3747
3748 #[test]
3749 fn serialize_list_models() -> Result<()> {
3750 let request = ClientRequest::ModelList {
3751 request_id: RequestId::Integer(6),
3752 params: v2::ModelListParams::default(),
3753 };
3754 assert_eq!(
3755 json!({
3756 "method": "model/list",
3757 "id": 6,
3758 "params": {
3759 "limit": null,
3760 "cursor": null,
3761 "includeHidden": null
3762 }
3763 }),
3764 serde_json::to_value(&request)?,
3765 );
3766 Ok(())
3767 }
3768
3769 #[test]
3770 fn serialize_model_provider_capabilities_read() -> Result<()> {
3771 let request = ClientRequest::ModelProviderCapabilitiesRead {
3772 request_id: RequestId::Integer(7),
3773 params: v2::ModelProviderCapabilitiesReadParams {},
3774 };
3775 assert_eq!(
3776 json!({
3777 "method": "modelProvider/capabilities/read",
3778 "id": 7,
3779 "params": {}
3780 }),
3781 serde_json::to_value(&request)?,
3782 );
3783 Ok(())
3784 }
3785
3786 #[test]
3787 fn serialize_list_collaboration_modes() -> Result<()> {
3788 let request = ClientRequest::CollaborationModeList {
3789 request_id: RequestId::Integer(7),
3790 params: v2::CollaborationModeListParams::default(),
3791 };
3792 assert_eq!(
3793 json!({
3794 "method": "collaborationMode/list",
3795 "id": 7,
3796 "params": {}
3797 }),
3798 serde_json::to_value(&request)?,
3799 );
3800 Ok(())
3801 }
3802
3803 #[test]
3804 fn serialize_list_apps() -> Result<()> {
3805 let request = ClientRequest::AppsList {
3806 request_id: RequestId::Integer(8),
3807 params: v2::AppsListParams::default(),
3808 };
3809 assert_eq!(
3810 json!({
3811 "method": "app/list",
3812 "id": 8,
3813 "params": {
3814 "cursor": null,
3815 "limit": null,
3816 "threadId": null
3817 }
3818 }),
3819 serde_json::to_value(&request)?,
3820 );
3821 Ok(())
3822 }
3823
3824 #[test]
3825 fn serialize_installed_apps() -> Result<()> {
3826 let request = ClientRequest::AppsInstalled {
3827 request_id: RequestId::Integer(9),
3828 params: v2::AppsInstalledParams::default(),
3829 };
3830 assert_eq!(
3831 json!({
3832 "method": "app/installed",
3833 "id": 9,
3834 "params": {
3835 "threadId": null
3836 }
3837 }),
3838 serde_json::to_value(&request)?,
3839 );
3840
3841 let force_refresh_request = ClientRequest::AppsInstalled {
3842 request_id: RequestId::Integer(10),
3843 params: v2::AppsInstalledParams {
3844 thread_id: Some("thread-1".to_string()),
3845 force_refresh: true,
3846 },
3847 };
3848 assert_eq!(
3849 json!({
3850 "method": "app/installed",
3851 "id": 10,
3852 "params": {
3853 "threadId": "thread-1",
3854 "forceRefresh": true
3855 }
3856 }),
3857 serde_json::to_value(&force_refresh_request)?,
3858 );
3859 Ok(())
3860 }
3861
3862 #[test]
3863 fn serialize_installed_apps_response() -> Result<()> {
3864 let response = v2::AppsInstalledResponse {
3865 apps: vec![v2::InstalledApp {
3866 id: "demo-app".to_string(),
3867 runtime_name: Some("Demo App".to_string()),
3868 enabled: false,
3869 callable: false,
3870 }],
3871 };
3872
3873 assert_eq!(
3874 json!({
3875 "apps": [{
3876 "id": "demo-app",
3877 "runtimeName": "Demo App",
3878 "enabled": false,
3879 "callable": false
3880 }]
3881 }),
3882 serde_json::to_value(response)?,
3883 );
3884 Ok(())
3885 }
3886
3887 #[test]
3888 fn serialize_read_apps() -> Result<()> {
3889 let request = ClientRequest::AppsRead {
3890 request_id: RequestId::Integer(9),
3891 params: v2::AppsReadParams {
3892 app_ids: vec!["app-a".to_string(), "app-b".to_string()],
3893 thread_id: None,
3894 include_tools: true,
3895 },
3896 };
3897 assert_eq!(
3898 json!({
3899 "method": "app/read",
3900 "id": 9,
3901 "params": {
3902 "appIds": ["app-a", "app-b"],
3903 "threadId": null,
3904 "includeTools": true
3905 }
3906 }),
3907 serde_json::to_value(&request)?,
3908 );
3909 Ok(())
3910 }
3911
3912 #[test]
3913 fn serialize_environment_add() -> Result<()> {
3914 let request = ClientRequest::EnvironmentAdd {
3915 request_id: RequestId::Integer(9),
3916 params: v2::EnvironmentAddParams {
3917 skills: None,
3918 auth_bearer_token: Some("private-executor-token".into()),
3919 websocket_request_id: Some("caller-sample-id".to_string()),
3920 environment_id: "remote-a".to_string(),
3921 exec_server_url: "ws://127.0.0.1:8765".to_string(),
3922 connect_timeout_ms: Some(300_000),
3923 },
3924 };
3925 assert!(!format!("{request:?}").contains("private-executor-token"));
3926 assert_eq!(
3927 json!({
3928 "method": "environment/add",
3929 "id": 9,
3930 "params": {
3931 "environmentId": "remote-a",
3932 "execServerUrl": "ws://127.0.0.1:8765",
3933 "connectTimeoutMs": 300000,
3934 "authBearerToken": "private-executor-token",
3935 "websocketRequestId": "caller-sample-id",
3936 "skills": null
3937 }
3938 }),
3939 serde_json::to_value(&request)?,
3940 );
3941 Ok(())
3942 }
3943
3944 #[test]
3945 fn serialize_fs_get_metadata() -> Result<()> {
3946 let request = ClientRequest::FsGetMetadata {
3947 request_id: RequestId::Integer(10),
3948 params: v2::FsGetMetadataParams {
3949 path: absolute_path("tmp/example"),
3950 },
3951 };
3952 assert_eq!(
3953 json!({
3954 "method": "fs/getMetadata",
3955 "id": 10,
3956 "params": {
3957 "path": absolute_path_string("tmp/example")
3958 }
3959 }),
3960 serde_json::to_value(&request)?,
3961 );
3962 Ok(())
3963 }
3964
3965 #[test]
3966 fn serialize_fs_watch() -> Result<()> {
3967 let request = ClientRequest::FsWatch {
3968 request_id: RequestId::Integer(10),
3969 params: v2::FsWatchParams {
3970 watch_id: "watch-git".to_string(),
3971 path: absolute_path("tmp/repo/.git"),
3972 },
3973 };
3974 assert_eq!(
3975 json!({
3976 "method": "fs/watch",
3977 "id": 10,
3978 "params": {
3979 "watchId": "watch-git",
3980 "path": absolute_path_string("tmp/repo/.git")
3981 }
3982 }),
3983 serde_json::to_value(&request)?,
3984 );
3985 Ok(())
3986 }
3987
3988 #[test]
3989 fn serialize_list_experimental_features() -> Result<()> {
3990 let request = ClientRequest::ExperimentalFeatureList {
3991 request_id: RequestId::Integer(8),
3992 params: v2::ExperimentalFeatureListParams::default(),
3993 };
3994 assert_eq!(
3995 json!({
3996 "method": "experimentalFeature/list",
3997 "id": 8,
3998 "params": {
3999 "cursor": null,
4000 "limit": null,
4001 "threadId": null
4002 }
4003 }),
4004 serde_json::to_value(&request)?,
4005 );
4006 Ok(())
4007 }
4008
4009 #[test]
4010 fn serialize_list_experimental_features_with_thread_id() -> Result<()> {
4011 let request = ClientRequest::ExperimentalFeatureList {
4012 request_id: RequestId::Integer(8),
4013 params: v2::ExperimentalFeatureListParams {
4014 cursor: Some("3".to_string()),
4015 limit: Some(2),
4016 thread_id: Some("00000000-0000-4000-8000-000000000001".to_string()),
4017 },
4018 };
4019 assert_eq!(
4020 json!({
4021 "method": "experimentalFeature/list",
4022 "id": 8,
4023 "params": {
4024 "cursor": "3",
4025 "limit": 2,
4026 "threadId": "00000000-0000-4000-8000-000000000001"
4027 }
4028 }),
4029 serde_json::to_value(&request)?,
4030 );
4031 Ok(())
4032 }
4033
4034 #[test]
4035 fn serialize_thread_background_terminals_clean() -> Result<()> {
4036 let request = ClientRequest::ThreadBackgroundTerminalsClean {
4037 request_id: RequestId::Integer(8),
4038 params: v2::ThreadBackgroundTerminalsCleanParams {
4039 thread_id: "thr_123".to_string(),
4040 },
4041 };
4042 assert_eq!(
4043 json!({
4044 "method": "thread/backgroundTerminals/clean",
4045 "id": 8,
4046 "params": {
4047 "threadId": "thr_123"
4048 }
4049 }),
4050 serde_json::to_value(&request)?,
4051 );
4052 Ok(())
4053 }
4054
4055 #[test]
4056 fn serialize_thread_background_terminals_list() -> Result<()> {
4057 let request = ClientRequest::ThreadBackgroundTerminalsList {
4058 request_id: RequestId::Integer(8),
4059 params: v2::ThreadBackgroundTerminalsListParams {
4060 thread_id: "thr_123".to_string(),
4061 cursor: None,
4062 limit: None,
4063 },
4064 };
4065 assert_eq!(
4066 json!({
4067 "method": "thread/backgroundTerminals/list",
4068 "id": 8,
4069 "params": {
4070 "threadId": "thr_123",
4071 "cursor": null,
4072 "limit": null
4073 }
4074 }),
4075 serde_json::to_value(&request)?,
4076 );
4077 Ok(())
4078 }
4079
4080 #[test]
4081 fn serialize_thread_background_terminals_terminate() -> Result<()> {
4082 let request = ClientRequest::ThreadBackgroundTerminalsTerminate {
4083 request_id: RequestId::Integer(8),
4084 params: v2::ThreadBackgroundTerminalsTerminateParams {
4085 thread_id: "thr_123".to_string(),
4086 process_id: "42".to_string(),
4087 },
4088 };
4089 assert_eq!(
4090 json!({
4091 "method": "thread/backgroundTerminals/terminate",
4092 "id": 8,
4093 "params": {
4094 "threadId": "thr_123",
4095 "processId": "42"
4096 }
4097 }),
4098 serde_json::to_value(&request)?,
4099 );
4100 Ok(())
4101 }
4102
4103 #[test]
4104 fn serialize_thread_realtime_start() -> Result<()> {
4105 let request = ClientRequest::ThreadRealtimeStart {
4106 request_id: RequestId::Integer(9),
4107 params: v2::ThreadRealtimeStartParams {
4108 client_managed_handoffs: Some(true),
4109 delegation_ack_filler: Some(false),
4110 flush_transcript_tail_on_session_end: Some(true),
4111 codex_responses_as_items: None,
4112 codex_response_item_prefix: None,
4113 codex_response_handoff_mode: Some(CodexResponseHandoffMode::BemTags),
4114 backend_reasoning_status: false,
4115 codex_response_handoff_channel_prefixes: Some(std::collections::BTreeMap::from([
4116 ("analysis".to_string(), vec!["[THINKING]".to_string()]),
4117 (
4118 "commentary".to_string(),
4119 vec!["[PROGRESS]".to_string(), "[UPDATE]".to_string()],
4120 ),
4121 ("final".to_string(), vec!["[DONE]".to_string()]),
4122 ])),
4123 thread_id: "thr_123".to_string(),
4124 model: Some("realtime-treatment-model".to_string()),
4125 output_modality: RealtimeOutputModality::Audio,
4126 include_startup_context: Some(false),
4127 initial_items: Some(vec![
4128 v2::ThreadRealtimeInitialItem {
4129 role: ConversationTextRole::Developer,
4130 text: "Remember this.".to_string(),
4131 },
4132 v2::ThreadRealtimeInitialItem {
4133 role: ConversationTextRole::Assistant,
4134 text: "Understood.".to_string(),
4135 },
4136 ]),
4137 realtime_start_instructions: Some("Use realtime output channels.".to_string()),
4138 realtime_end_instructions: Some("Resume normal text responses.".to_string()),
4139 prompt: Some(Some("You are on a call".to_string())),
4140 realtime_session_id: Some("sess_456".to_string()),
4141 voice_session_id: Some("voice_789".to_string()),
4142 transport: None,
4143 version: Some(RealtimeConversationVersion::V3),
4144 voice: Some(RealtimeVoice::Marin),
4145 },
4146 };
4147 assert_eq!(
4148 json!({
4149 "method": "thread/realtime/start",
4150 "id": 9,
4151 "params": {
4152 "threadId": "thr_123",
4153 "clientManagedHandoffs": true,
4154 "delegationAckFiller": false,
4155 "flushTranscriptTailOnSessionEnd": true,
4156 "codexResponsesAsItems": null,
4157 "codexResponseItemPrefix": null,
4158 "codexResponseHandoffMode": "bemTags",
4159 "codexResponseHandoffChannelPrefixes": {
4160 "analysis": ["[THINKING]"],
4161 "commentary": ["[PROGRESS]", "[UPDATE]"],
4162 "final": ["[DONE]"]
4163 },
4164 "model": "realtime-treatment-model",
4165 "outputModality": "audio",
4166 "includeStartupContext": false,
4167 "initialItems": [
4168 {
4169 "role": "developer",
4170 "text": "Remember this."
4171 },
4172 {
4173 "role": "assistant",
4174 "text": "Understood."
4175 }
4176 ],
4177 "realtimeStartInstructions": "Use realtime output channels.",
4178 "realtimeEndInstructions": "Resume normal text responses.",
4179 "prompt": "You are on a call",
4180 "realtimeSessionId": "sess_456",
4181 "voiceSessionId": "voice_789",
4182 "transport": null,
4183 "version": "v3",
4184 "voice": "marin"
4185 }
4186 }),
4187 serde_json::to_value(&request)?,
4188 );
4189 Ok(())
4190 }
4191
4192 #[test]
4193 fn serialize_thread_realtime_start_prompt_default_and_null() -> Result<()> {
4194 let default_prompt_request = ClientRequest::ThreadRealtimeStart {
4195 request_id: RequestId::Integer(9),
4196 params: v2::ThreadRealtimeStartParams {
4197 client_managed_handoffs: None,
4198 delegation_ack_filler: None,
4199 flush_transcript_tail_on_session_end: None,
4200 codex_responses_as_items: None,
4201 codex_response_item_prefix: None,
4202 codex_response_handoff_mode: None,
4203 backend_reasoning_status: false,
4204 codex_response_handoff_channel_prefixes: None,
4205 thread_id: "thr_123".to_string(),
4206 model: None,
4207 output_modality: RealtimeOutputModality::Audio,
4208 include_startup_context: None,
4209 initial_items: None,
4210 realtime_start_instructions: None,
4211 realtime_end_instructions: None,
4212 prompt: None,
4213 realtime_session_id: None,
4214 voice_session_id: None,
4215 transport: None,
4216 version: None,
4217 voice: None,
4218 },
4219 };
4220 assert_eq!(
4221 json!({
4222 "method": "thread/realtime/start",
4223 "id": 9,
4224 "params": {
4225 "threadId": "thr_123",
4226 "clientManagedHandoffs": null,
4227 "delegationAckFiller": null,
4228 "flushTranscriptTailOnSessionEnd": null,
4229 "codexResponsesAsItems": null,
4230 "codexResponseItemPrefix": null,
4231 "codexResponseHandoffMode": null,
4232 "codexResponseHandoffChannelPrefixes": null,
4233 "model": null,
4234 "outputModality": "audio",
4235 "includeStartupContext": null,
4236 "initialItems": null,
4237 "realtimeStartInstructions": null,
4238 "realtimeEndInstructions": null,
4239 "realtimeSessionId": null,
4240 "voiceSessionId": null,
4241 "transport": null,
4242 "version": null,
4243 "voice": null
4244 }
4245 }),
4246 serde_json::to_value(&default_prompt_request)?,
4247 );
4248
4249 let null_prompt_request = ClientRequest::ThreadRealtimeStart {
4250 request_id: RequestId::Integer(9),
4251 params: v2::ThreadRealtimeStartParams {
4252 client_managed_handoffs: None,
4253 delegation_ack_filler: None,
4254 flush_transcript_tail_on_session_end: None,
4255 codex_responses_as_items: None,
4256 codex_response_item_prefix: None,
4257 codex_response_handoff_mode: None,
4258 backend_reasoning_status: false,
4259 codex_response_handoff_channel_prefixes: None,
4260 thread_id: "thr_123".to_string(),
4261 model: None,
4262 output_modality: RealtimeOutputModality::Audio,
4263 include_startup_context: None,
4264 initial_items: None,
4265 realtime_start_instructions: None,
4266 realtime_end_instructions: None,
4267 prompt: Some(None),
4268 realtime_session_id: None,
4269 voice_session_id: None,
4270 transport: None,
4271 version: None,
4272 voice: None,
4273 },
4274 };
4275 assert_eq!(
4276 json!({
4277 "method": "thread/realtime/start",
4278 "id": 9,
4279 "params": {
4280 "threadId": "thr_123",
4281 "clientManagedHandoffs": null,
4282 "delegationAckFiller": null,
4283 "flushTranscriptTailOnSessionEnd": null,
4284 "codexResponsesAsItems": null,
4285 "codexResponseItemPrefix": null,
4286 "codexResponseHandoffMode": null,
4287 "codexResponseHandoffChannelPrefixes": null,
4288 "model": null,
4289 "outputModality": "audio",
4290 "includeStartupContext": null,
4291 "initialItems": null,
4292 "realtimeStartInstructions": null,
4293 "realtimeEndInstructions": null,
4294 "prompt": null,
4295 "realtimeSessionId": null,
4296 "voiceSessionId": null,
4297 "transport": null,
4298 "version": null,
4299 "voice": null
4300 }
4301 }),
4302 serde_json::to_value(&null_prompt_request)?,
4303 );
4304
4305 let default_prompt_value = json!({
4306 "method": "thread/realtime/start",
4307 "id": 9,
4308 "params": {
4309 "threadId": "thr_123",
4310 // Retain runtime compatibility with clients that have not yet removed this field.
4311 "codexResponseHandoffPrefix": "",
4312 "outputModality": "audio",
4313 "realtimeSessionId": null,
4314 "transport": null,
4315 "voice": null
4316 }
4317 });
4318 assert_eq!(
4319 serde_json::from_value::<ClientRequest>(default_prompt_value)?,
4320 default_prompt_request,
4321 );
4322
4323 let null_prompt_value = json!({
4324 "method": "thread/realtime/start",
4325 "id": 9,
4326 "params": {
4327 "threadId": "thr_123",
4328 "outputModality": "audio",
4329 "prompt": null,
4330 "realtimeSessionId": null,
4331 "transport": null,
4332 "voice": null
4333 }
4334 });
4335 assert_eq!(
4336 serde_json::from_value::<ClientRequest>(null_prompt_value)?,
4337 null_prompt_request,
4338 );
4339
4340 Ok(())
4341 }
4342
4343 #[test]
4344 fn serialize_thread_realtime_append_speech() -> Result<()> {
4345 let request = ClientRequest::ThreadRealtimeAppendSpeech {
4346 request_id: RequestId::Integer(10),
4347 params: v2::ThreadRealtimeAppendSpeechParams {
4348 thread_id: "thr_123".to_string(),
4349 text: "Short voice update".to_string(),
4350 },
4351 };
4352 assert_eq!(
4353 json!({
4354 "method": "thread/realtime/appendSpeech",
4355 "id": 10,
4356 "params": {
4357 "threadId": "thr_123",
4358 "text": "Short voice update"
4359 }
4360 }),
4361 serde_json::to_value(&request)?,
4362 );
4363 Ok(())
4364 }
4365
4366 #[test]
4367 fn serialize_thread_status_changed_notification() -> Result<()> {
4368 let notification =
4369 ServerNotification::ThreadStatusChanged(v2::ThreadStatusChangedNotification {
4370 thread_id: "thr_123".to_string(),
4371 status: v2::ThreadStatus::Idle,
4372 });
4373 assert_eq!(
4374 json!({
4375 "method": "thread/status/changed",
4376 "params": {
4377 "threadId": "thr_123",
4378 "status": {
4379 "type": "idle"
4380 },
4381 }
4382 }),
4383 serde_json::to_value(&notification)?,
4384 );
4385 Ok(())
4386 }
4387
4388 #[test]
4389 fn serialize_model_safety_buffering_updated_notification() -> Result<()> {
4390 let notification = ServerNotification::ModelSafetyBufferingUpdated(
4391 v2::ModelSafetyBufferingUpdatedNotification {
4392 thread_id: "thr_123".to_string(),
4393 turn_id: "turn_123".to_string(),
4394 model: "current-model".to_string(),
4395 use_cases: vec!["cyber".to_string()],
4396 reasons: vec!["user_risk".to_string()],
4397 show_buffering_ui: true,
4398 faster_model: Some("faster-model".to_string()),
4399 },
4400 );
4401 assert_eq!(
4402 json!({
4403 "method": "model/safetyBuffering/updated",
4404 "params": {
4405 "threadId": "thr_123",
4406 "turnId": "turn_123",
4407 "model": "current-model",
4408 "useCases": ["cyber"],
4409 "reasons": ["user_risk"],
4410 "showBufferingUi": true,
4411 "fasterModel": "faster-model"
4412 }
4413 }),
4414 serde_json::to_value(&notification)?,
4415 );
4416 Ok(())
4417 }
4418
4419 #[test]
4420 fn serialize_thread_realtime_output_audio_delta_notification() -> Result<()> {
4421 let notification = ServerNotification::ThreadRealtimeOutputAudioDelta(
4422 v2::ThreadRealtimeOutputAudioDeltaNotification {
4423 thread_id: "thr_123".to_string(),
4424 audio: v2::ThreadRealtimeAudioChunk {
4425 data: "AQID".to_string(),
4426 sample_rate: 24_000,
4427 num_channels: 1,
4428 samples_per_channel: Some(512),
4429 item_id: None,
4430 },
4431 },
4432 );
4433 assert_eq!(
4434 json!({
4435 "method": "thread/realtime/outputAudio/delta",
4436 "params": {
4437 "threadId": "thr_123",
4438 "audio": {
4439 "data": "AQID",
4440 "sampleRate": 24000,
4441 "numChannels": 1,
4442 "samplesPerChannel": 512,
4443 "itemId": null
4444 }
4445 }
4446 }),
4447 serde_json::to_value(&notification)?,
4448 );
4449 Ok(())
4450 }
4451
4452 #[test]
4453 fn environment_add_is_marked_experimental() {
4454 let request = ClientRequest::EnvironmentAdd {
4455 request_id: RequestId::Integer(1),
4456 params: v2::EnvironmentAddParams {
4457 skills: None,
4458 auth_bearer_token: None,
4459 websocket_request_id: None,
4460 environment_id: "remote-a".to_string(),
4461 exec_server_url: "ws://127.0.0.1:8765".to_string(),
4462 connect_timeout_ms: None,
4463 },
4464 };
4465 let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request);
4466 assert_eq!(reason, Some("environment/add"));
4467 }
4468
4469 #[test]
4470 fn command_exec_permission_profile_is_marked_experimental() {
4471 let request = ClientRequest::OneOffCommandExec {
4472 request_id: RequestId::Integer(1),
4473 params: v2::CommandExecParams {
4474 command: vec!["pwd".to_string()],
4475 process_id: None,
4476 tty: false,
4477 stream_stdin: false,
4478 stream_stdout_stderr: false,
4479 output_bytes_cap: None,
4480 disable_output_cap: false,
4481 disable_timeout: false,
4482 timeout_ms: None,
4483 cwd: None,
4484 env: None,
4485 size: None,
4486 sandbox_policy: None,
4487 permission_profile: Some(BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string()),
4488 },
4489 };
4490
4491 let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request);
4492 assert_eq!(reason, Some("command/exec.permissionProfile"));
4493 }
4494
4495 #[test]
4496 fn thread_goal_methods_are_not_marked_experimental() {
4497 let set_request = ClientRequest::ThreadGoalSet {
4498 request_id: RequestId::Integer(1),
4499 params: v2::ThreadGoalSetParams {
4500 origin: None,
4501 thread_id: "thr_123".to_string(),
4502 objective: Some("ship goal mode".to_string()),
4503 status: Some(v2::ThreadGoalStatus::Active),
4504 token_budget: Some(Some(10_000)),
4505 },
4506 };
4507 let get_request = ClientRequest::ThreadGoalGet {
4508 request_id: RequestId::Integer(2),
4509 params: v2::ThreadGoalGetParams {
4510 thread_id: "thr_123".to_string(),
4511 },
4512 };
4513 let clear_request = ClientRequest::ThreadGoalClear {
4514 request_id: RequestId::Integer(3),
4515 params: v2::ThreadGoalClearParams {
4516 origin: None,
4517 thread_id: "thr_123".to_string(),
4518 },
4519 };
4520
4521 assert_eq!(
4522 crate::experimental_api::ExperimentalApi::experimental_reason(&set_request),
4523 None
4524 );
4525 assert_eq!(
4526 crate::experimental_api::ExperimentalApi::experimental_reason(&get_request),
4527 None
4528 );
4529 assert_eq!(
4530 crate::experimental_api::ExperimentalApi::experimental_reason(&clear_request),
4531 None
4532 );
4533 }
4534
4535 #[test]
4536 fn thread_goal_notifications_are_not_marked_experimental() {
4537 let goal = v2::ThreadGoal {
4538 thread_id: "thr_123".to_string(),
4539 objective: "ship goal mode".to_string(),
4540 status: v2::ThreadGoalStatus::Active,
4541 token_budget: Some(10_000),
4542 tokens_used: 123,
4543 time_used_seconds: 45,
4544 created_at: 1_700_000_000,
4545 updated_at: 1_700_000_123,
4546 };
4547 let updated = ServerNotification::ThreadGoalUpdated(v2::ThreadGoalUpdatedNotification {
4548 thread_id: "thr_123".to_string(),
4549 turn_id: None,
4550 goal,
4551 });
4552 let cleared = ServerNotification::ThreadGoalCleared(v2::ThreadGoalClearedNotification {
4553 thread_id: "thr_123".to_string(),
4554 });
4555
4556 assert_eq!(
4557 crate::experimental_api::ExperimentalApi::experimental_reason(&updated),
4558 None
4559 );
4560 assert_eq!(
4561 crate::experimental_api::ExperimentalApi::experimental_reason(&cleared),
4562 None
4563 );
4564 }
4565
4566 #[test]
4567 fn thread_settings_updated_notification_is_marked_experimental() {
4568 let notification =
4569 ServerNotification::ThreadSettingsUpdated(v2::ThreadSettingsUpdatedNotification {
4570 thread_id: "thr_123".to_string(),
4571 thread_settings: v2::ThreadSettings {
4572 disabled_plugin_ids: Vec::new(),
4573 cwd: absolute_path("/tmp/repo"),
4574 approval_policy: v2::AskForApproval::Never,
4575 approvals_reviewer: v2::ApprovalsReviewer::User,
4576 sandbox_policy: v2::SandboxPolicy::DangerFullAccess,
4577 active_permission_profile: None,
4578 model: "gpt-5.4".to_string(),
4579 model_provider: "openai".to_string(),
4580 service_tier: None,
4581 effort: None,
4582 summary: None,
4583 collaboration_mode: codex_protocol::config_types::CollaborationMode {
4584 mode: codex_protocol::config_types::ModeKind::Default,
4585 settings: codex_protocol::config_types::Settings {
4586 model: "gpt-5.4".to_string(),
4587 reasoning_effort: None,
4588 developer_instructions: None,
4589 },
4590 },
4591 multi_agent_mode: Default::default(),
4592 personality: None,
4593 },
4594 });
4595
4596 assert_eq!(
4597 crate::experimental_api::ExperimentalApi::experimental_reason(&notification),
4598 Some("thread/settings/updated")
4599 );
4600 }
4601
4602 #[test]
4603 fn turn_moderation_metadata_notification_is_marked_experimental() {
4604 let notification =
4605 ServerNotification::TurnModerationMetadata(v2::TurnModerationMetadataNotification {
4606 thread_id: "thr_123".to_string(),
4607 turn_id: "turn_123".to_string(),
4608 metadata: json!({"presentation": "inline"}),
4609 });
4610
4611 assert_eq!(
4612 crate::experimental_api::ExperimentalApi::experimental_reason(&notification),
4613 Some("turn/moderationMetadata")
4614 );
4615 }
4616
4617 #[test]
4618 fn thread_realtime_started_notification_is_marked_experimental() {
4619 let notification =
4620 ServerNotification::ThreadRealtimeStarted(v2::ThreadRealtimeStartedNotification {
4621 thread_id: "thr_123".to_string(),
4622 realtime_session_id: Some("sess_456".to_string()),
4623 version: RealtimeConversationVersion::V1,
4624 });
4625 let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&notification);
4626 assert_eq!(reason, Some("thread/realtime/started"));
4627 }
4628
4629 #[test]
4630 fn thread_realtime_output_audio_delta_notification_is_marked_experimental() {
4631 let notification = ServerNotification::ThreadRealtimeOutputAudioDelta(
4632 v2::ThreadRealtimeOutputAudioDeltaNotification {
4633 thread_id: "thr_123".to_string(),
4634 audio: v2::ThreadRealtimeAudioChunk {
4635 data: "AQID".to_string(),
4636 sample_rate: 24_000,
4637 num_channels: 1,
4638 samples_per_channel: Some(512),
4639 item_id: None,
4640 },
4641 },
4642 );
4643 let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&notification);
4644 assert_eq!(reason, Some("thread/realtime/outputAudio/delta"));
4645 }
4646
4647 #[test]
4648 fn command_execution_request_approval_additional_permissions_is_marked_experimental() {
4649 let params = v2::CommandExecutionRequestApprovalParams {
4650 kind: Default::default(),
4651 thread_id: "thr_123".to_string(),
4652 turn_id: "turn_123".to_string(),
4653 item_id: "call_123".to_string(),
4654 started_at_ms: 0,
4655 approval_id: None,
4656 environment_id: None,
4657 reason: None,
4658 network_approval_context: None,
4659 command: Some("cat file".to_string()),
4660 cwd: None,
4661 command_actions: None,
4662 additional_permissions: Some(v2::AdditionalPermissionProfile {
4663 network: None,
4664 file_system: Some(v2::AdditionalFileSystemPermissions {
4665 read: Some(vec![absolute_path("/tmp/allowed").into()]),
4666 write: None,
4667 glob_scan_max_depth: None,
4668 entries: None,
4669 }),
4670 }),
4671 proposed_execpolicy_amendment: None,
4672 proposed_network_policy_amendments: None,
4673 available_decisions: None,
4674 };
4675 let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&params);
4676 assert_eq!(
4677 reason,
4678 Some("item/commandExecution/requestApproval.additionalPermissions")
4679 );
4680 }
4681 }
4682
4683 #[cfg(test)]
4684 #[path = "common_tests.rs"]
4685 mod common_tests;
4686
4686 lines RUST