agentic-coding-protocol 0.0.11

A protocol for standardizing communication between code editors and AI coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
use std::{collections::HashMap, fmt::Display, ops::Deref, path::PathBuf};

use derive_more::{Deref, Display, FromStr};
use schemars::JsonSchema;
use semver::Version;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Error {
    pub code: i32,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

impl Error {
    pub fn new(code: impl Into<(i32, String)>) -> Self {
        let (code, message) = code.into();
        Error {
            code,
            message,
            data: None,
        }
    }

    pub fn with_data(mut self, data: impl Into<serde_json::Value>) -> Self {
        self.data = Some(data.into());
        self
    }

    /// Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
    pub fn parse_error() -> Self {
        Error::new(ErrorCode::PARSE_ERROR)
    }

    /// The JSON sent is not a valid Request object.
    pub fn invalid_request() -> Self {
        Error::new(ErrorCode::INVALID_REQUEST)
    }

    /// The method does not exist / is not available.
    pub fn method_not_found() -> Self {
        Error::new(ErrorCode::METHOD_NOT_FOUND)
    }

    /// Invalid method parameter(s).
    pub fn invalid_params() -> Self {
        Error::new(ErrorCode::INVALID_PARAMS)
    }

    /// Internal JSON-RPC error.
    pub fn internal_error() -> Self {
        Error::new(ErrorCode::INTERNAL_ERROR)
    }

    pub fn into_internal_error(err: impl std::error::Error) -> Self {
        Error::internal_error().with_data(err.to_string())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ErrorCode {
    code: i32,
    message: &'static str,
}

impl ErrorCode {
    pub const PARSE_ERROR: ErrorCode = ErrorCode {
        code: -32700,
        message: "Parse error",
    };

    pub const INVALID_REQUEST: ErrorCode = ErrorCode {
        code: -32600,
        message: "Invalid Request",
    };

    pub const METHOD_NOT_FOUND: ErrorCode = ErrorCode {
        code: -32601,
        message: "Method not found",
    };

    pub const INVALID_PARAMS: ErrorCode = ErrorCode {
        code: -32602,
        message: "Invalid params",
    };

    pub const INTERNAL_ERROR: ErrorCode = ErrorCode {
        code: -32603,
        message: "Internal error",
    };
}

impl From<ErrorCode> for (i32, String) {
    fn from(error_code: ErrorCode) -> Self {
        (error_code.code, error_code.message.to_string())
    }
}

impl From<ErrorCode> for Error {
    fn from(error_code: ErrorCode) -> Self {
        Error::new(error_code)
    }
}

impl std::error::Error for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.message.is_empty() {
            write!(f, "{}", self.code)?;
        } else {
            write!(f, "{}", self.message)?;
        }

        if let Some(data) = &self.data {
            write!(f, ": {data}")?;
        }

        Ok(())
    }
}

impl From<anyhow::Error> for Error {
    fn from(error: anyhow::Error) -> Self {
        Error::into_internal_error(error.deref())
    }
}

#[derive(Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Method {
    pub name: &'static str,
    pub request_type: &'static str,
    pub param_payload: bool,
    pub response_type: &'static str,
    pub response_payload: bool,
}

pub trait AnyRequest: Serialize + Sized + std::fmt::Debug + 'static {
    type Response: Serialize + 'static;
    fn from_method_and_params(method: &str, params: &RawValue) -> Result<Self, Error>;
    fn response_from_method_and_result(
        method: &str,
        params: &RawValue,
    ) -> Result<Self::Response, Error>;
}

macro_rules! acp_peer {
    (
        $handler_trait_name:ident,
        $request_trait_name:ident,
        $request_enum_name:ident,
        $response_enum_name:ident,
        $method_map_name:ident,
        $(($request_method:ident, $request_method_string:expr, $request_name:ident, $param_payload: tt, $response_name:ident, $response_payload: tt)),*
        $(,)?
    ) => {
        macro_rules! handler_trait_call_req {
            ($self: ident, $method: ident, false, $resp_name: ident, false, $params: ident) => {
                {
                    $self.$method().await?;
                    Ok($response_enum_name::$resp_name($resp_name))
                }
            };
            ($self: ident, $method: ident, false, $resp_name: ident, true, $params: ident) => {
                {
                    let resp = $self.$method().await?;
                    Ok($response_enum_name::$resp_name(resp))
                }
            };
            ($self: ident, $method: ident, true, $resp_name: ident, false, $params: ident) => {
                {
                    $self.$method($params).await?;
                    Ok($response_enum_name::$resp_name($resp_name))
                }
            };
            ($self: ident, $method: ident, true, $resp_name: ident, true, $params: ident) => {
                {
                    let resp = $self.$method($params).await?;
                    Ok($response_enum_name::$resp_name(resp))
                }
            }
        }

        macro_rules! handler_trait_req_method {
            ($method: ident, $req: ident, false, $resp: tt, false) => {
                fn $method(&self) -> impl Future<Output = Result<(), Error>>;
            };
            ($method: ident, $req: ident, false, $resp: tt, true) => {
                fn $method(&self) -> impl Future<Output = Result<$resp, Error>>;
            };
            ($method: ident, $req: ident, true, $resp: tt, false) => {
                fn $method(&self, request: $req) -> impl Future<Output = Result<(), Error>>;
            };
            ($method: ident, $req: ident, true, $resp: tt, true) => {
                fn $method(&self, request: $req) -> impl Future<Output = Result<$resp, Error>>;
            }
        }

        pub trait $handler_trait_name {
            fn call(&self, params: $request_enum_name) -> impl Future<Output = Result<$response_enum_name, Error>> {
                async move {
                    match params {
                        $(#[allow(unused_variables)]
                        $request_enum_name::$request_name(params) => {
                            handler_trait_call_req!(self, $request_method, $param_payload, $response_name, $response_payload, params)
                        }),*
                    }
                }
            }

            $(
                handler_trait_req_method!($request_method, $request_name, $param_payload, $response_name, $response_payload);
            )*
        }

        pub trait $request_trait_name {
            type Response;
            fn into_any(self) -> $request_enum_name;
            fn response_from_any(any: $response_enum_name) -> Result<Self::Response, Error>;
        }

        #[derive(Serialize, JsonSchema, Debug)]
        #[serde(untagged)]
        pub enum $request_enum_name {
            $(
                $request_name($request_name),
            )*
        }

        #[derive(Serialize, Deserialize, JsonSchema)]
        #[serde(untagged)]
        pub enum $response_enum_name {
            $(
                $response_name($response_name),
            )*
        }

        macro_rules! request_from_method_and_params {
            ($req_name: ident, false, $params: tt) => {
                Ok($request_enum_name::$req_name($req_name))
            };
            ($req_name: ident, true, $params: tt) => {
                match serde_json::from_str($params.get()) {
                    Ok(params) => Ok($request_enum_name::$req_name(params)),
                    Err(e) => Err(Error::parse_error().with_data(e.to_string())),
                }
            };
        }

        macro_rules! response_from_method_and_result {
            ($resp_name: ident, false, $result: tt) => {
                Ok($response_enum_name::$resp_name($resp_name))
            };
            ($resp_name: ident, true, $result: tt) => {
                match serde_json::from_str($result.get()) {
                    Ok(result) => Ok($response_enum_name::$resp_name(result)),
                    Err(e) => Err(Error::parse_error().with_data(e.to_string())),
                }
            };
        }

        impl AnyRequest for $request_enum_name {
            type Response = $response_enum_name;

            fn from_method_and_params(method: &str, params: &RawValue) -> Result<Self, Error> {
                match method {
                    $(
                        $request_method_string => {
                            request_from_method_and_params!($request_name, $param_payload, params)
                        }
                    )*
                    _ => Err(Error::method_not_found()),
                }
            }

            fn response_from_method_and_result(method: &str, params: &RawValue) -> Result<Self::Response, Error> {
                match method {
                    $(
                        $request_method_string => {
                            response_from_method_and_result!($response_name, $response_payload, params)
                        }
                    )*
                    _ => Err(Error::method_not_found()),
                }
            }
        }

        impl $request_enum_name {
            pub fn method_name(&self) -> &'static str {
                match self {
                    $(
                        $request_enum_name::$request_name(_) => $request_method_string,
                    )*
                }
            }
        }



        pub static $method_map_name: &[Method] = &[
            $(
                Method {
                    name: $request_method_string,
                    request_type: stringify!($request_name),
                    param_payload: $param_payload,
                    response_type: stringify!($response_name),
                    response_payload: $response_payload,
                },
            )*
        ];

        macro_rules! req_into_any {
            ($self: ident, $req_name: ident, false) => {
                $request_enum_name::$req_name($req_name)
            };
            ($self: ident, $req_name: ident, true) => {
                $request_enum_name::$req_name($self)
            };
        }

        macro_rules! resp_type {
            ($resp_name: ident, false) => {
                ()
            };
            ($resp_name: ident, true) => {
                $resp_name
            };
        }

        macro_rules! resp_from_any {
            ($any: ident, $resp_name: ident, false) => {
                match $any {
                    $response_enum_name::$resp_name(_) => Ok(()),
                    _ => Err(Error::internal_error().with_data("Unexpected Response"))
                }
            };
            ($any: ident, $resp_name: ident, true) => {
                match $any {
                    $response_enum_name::$resp_name(this) => Ok(this),
                    _ => Err(Error::internal_error().with_data("Unexpected Response"))
                }
            };
        }

        $(
            impl $request_trait_name for $request_name {
                type Response = resp_type!($response_name, $response_payload);

                fn into_any(self) -> $request_enum_name {
                    req_into_any!(self, $request_name, $param_payload)
                }

                fn response_from_any(any: $response_enum_name) -> Result<Self::Response, Error> {
                    resp_from_any!(any, $response_name, $response_payload)
                }
            }
        )*
    };
}

// requests sent from the client (the IDE) to the agent
acp_peer!(
    Client,
    ClientRequest,
    AnyClientRequest,
    AnyClientResult,
    CLIENT_METHODS,
    (
        stream_assistant_message_chunk,
        "streamAssistantMessageChunk",
        StreamAssistantMessageChunkParams,
        true,
        StreamAssistantMessageChunkResponse,
        false
    ),
    (
        request_tool_call_confirmation,
        "requestToolCallConfirmation",
        RequestToolCallConfirmationParams,
        true,
        RequestToolCallConfirmationResponse,
        true
    ),
    (
        push_tool_call,
        "pushToolCall",
        PushToolCallParams,
        true,
        PushToolCallResponse,
        true
    ),
    (
        update_tool_call,
        "updateToolCall",
        UpdateToolCallParams,
        true,
        UpdateToolCallResponse,
        false
    ),
    (
        update_plan,
        "updatePlan",
        UpdatePlanParams,
        true,
        UpdatePlanResponse,
        false
    ),
    (
        write_text_file,
        "writeTextFile",
        WriteTextFileParams,
        true,
        WriteTextFileResponse,
        false
    ),
    (
        read_text_file,
        "readTextFile",
        ReadTextFileParams,
        true,
        ReadTextFileResponse,
        true
    ),
);

// requests sent from the agent to the client (the IDE)
acp_peer!(
    Agent,
    AgentRequest,
    AnyAgentRequest,
    AnyAgentResult,
    AGENT_METHODS,
    (
        initialize,
        "initialize",
        InitializeParams,
        true,
        InitializeResponse,
        true
    ),
    (
        authenticate,
        "authenticate",
        AuthenticateParams,
        false,
        AuthenticateResponse,
        false
    ),
    (
        send_user_message,
        "sendUserMessage",
        SendUserMessageParams,
        true,
        SendUserMessageResponse,
        false
    ),
    (
        cancel_send_message,
        "cancelSendMessage",
        CancelSendMessageParams,
        false,
        CancelSendMessageResponse,
        false
    )
);

// --- Messages sent from the client to the agent --- \\

/// Initialize sets up the agent's state. It should be called before any other method,
/// and no other methods should be called until it has completed.
///
/// If the agent is not authenticated, then the client should prompt the user to authenticate,
/// and then call the `authenticate` method.
/// Otherwise the client can send other messages to the agent.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct InitializeParams {
    /// The version of the protocol that the client supports.
    /// This should be the latest version supported by the client.
    pub protocol_version: ProtocolVersion,
    /// The version of the protocol that the client supports.
    /// This should be the latest version supported by the client.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub context_servers: HashMap<String, ContextServer>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum ContextServer {
    Stdio {
        command: String,
        args: Vec<String>,
        env: HashMap<String, String>,
    },
    Http {
        url: String,
        headers: HashMap<String, String>,
    },
}

#[derive(Clone, Debug, Deref, Display, FromStr, Serialize, Deserialize, JsonSchema)]
#[serde(transparent)]
pub struct ProtocolVersion(Version);

impl ProtocolVersion {
    pub fn latest() -> Self {
        Self(env!("CARGO_PKG_VERSION").parse().expect("Invalid version"))
    }
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResponse {
    /// The version of the protocol that the agent supports.
    /// If the agent supports the requested version, it should respond with the same version.
    /// Otherwise, the agent should respond with the latest version it supports.
    pub protocol_version: ProtocolVersion,
    /// Indicates whether the agent is authenticated and
    /// ready to handle requests.
    pub is_authenticated: bool,
}

/// Triggers authentication on the agent side.
///
/// This method should only be called if the initialize response indicates the user isn't already authenticated.
/// If this succceeds then the client can send other messasges to the agent,
/// If it fails then the error message should be shown and the user prompted to authenticate.
///
/// The implementation of authentication is left up to the agent, typically an oauth
/// flow is run by opening a browser window in the background.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticateParams;

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticateResponse;

/// sendUserMessage allows the user to send a message to the agent.
/// This method should complete after the agent is finished, during
/// which time the agent may update the client by calling
/// streamAssistantMessageChunk and other methods.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct SendUserMessageParams {
    pub chunks: Vec<UserMessageChunk>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct SendUserMessageResponse;

/// A part in a user message
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(untagged, rename_all = "camelCase")]
pub enum UserMessageChunk {
    /// A chunk of text in user message
    Text { text: String },
    /// A file path mention in a user message
    Path { path: PathBuf },
}

/// cancelSendMessage allows the client to request that the agent
/// stop running. The agent should resolve or reject the current sendUserMessage call.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CancelSendMessageParams;

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CancelSendMessageResponse;

// --- Messages sent from the agent to the client --- \\

/// Streams part of an assistant response to the client
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct StreamAssistantMessageChunkParams {
    pub chunk: AssistantMessageChunk,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct StreamAssistantMessageChunkResponse;

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(untagged, rename_all = "camelCase")]
pub enum AssistantMessageChunk {
    Text { text: String },
    Thought { thought: String },
}

/// Request confirmation before running a tool
///
/// When allowed, the client returns a [`ToolCallId`] which can be used
/// to update the tool call's `status` and `content` as it runs.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RequestToolCallConfirmationParams {
    #[serde(flatten)]
    pub tool_call: PushToolCallParams,
    pub confirmation: ToolCallConfirmation,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
// todo? make this `pub enum ToolKind { Edit, Search, Read, Fetch, ...}?`
// avoids being to UI centric.
pub enum Icon {
    FileSearch,
    Folder,
    Globe,
    Hammer,
    LightBulb,
    Pencil,
    Regex,
    Terminal,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ToolCallConfirmation {
    #[serde(rename_all = "camelCase")]
    Edit {
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
    },
    #[serde(rename_all = "camelCase")]
    Execute {
        command: String,
        root_command: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
    },
    #[serde(rename_all = "camelCase")]
    Mcp {
        server_name: String,
        tool_name: String,
        tool_display_name: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
    },
    #[serde(rename_all = "camelCase")]
    Fetch {
        urls: Vec<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
    },
    #[serde(rename_all = "camelCase")]
    Other { description: String },
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub struct RequestToolCallConfirmationResponse {
    pub id: ToolCallId,
    pub outcome: ToolCallConfirmationOutcome,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ToolCallConfirmationOutcome {
    /// Allow this one call
    Allow,
    /// Always allow this kind of operation
    AlwaysAllow,
    /// Always allow any tool from this MCP server
    AlwaysAllowMcpServer,
    /// Always allow this tool from this MCP server
    AlwaysAllowTool,
    /// Reject this tool call
    Reject,
    /// The generation was canceled before a confirming
    Cancel,
}

/// pushToolCall allows the agent to start a tool call
/// when it does not need to request permission to do so.
///
/// The returned id can be used to update the UI for the tool
/// call as needed.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct PushToolCallParams {
    pub label: String,
    pub icon: Icon,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<ToolCallContent>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub locations: Vec<ToolCallLocation>,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub struct ToolCallLocation {
    pub path: PathBuf,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u32>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub struct PushToolCallResponse {
    pub id: ToolCallId,
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Hash)]
#[serde(rename_all = "camelCase")]
pub struct ToolCallId(pub u64);

/// updateToolCall allows the agent to update the content and status of the tool call.
///
/// The new content replaces what is currently displayed in the UI.
///
/// The [`ToolCallId`] is included in the response of
/// `pushToolCall` or `requestToolCallConfirmation` respectively.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct UpdateToolCallParams {
    pub tool_call_id: ToolCallId,
    pub status: ToolCallStatus,
    pub content: Option<ToolCallContent>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct UpdateToolCallResponse;

/// Parameters for updating the current execution plan.
///
/// This allows the assistant to communicate its high-level plan
/// for completing the user's request.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct UpdatePlanParams {
    /// The list of plan entries representing the current execution plan.
    pub entries: Vec<PlanEntry>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct UpdatePlanResponse;

/// A single entry in the execution plan.
///
/// Represents a task or goal that the assistant intends to accomplish
/// as part of fulfilling the user's request.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct PlanEntry {
    /// Description of what this task aims to accomplish
    pub content: String,
    /// Relative importance of this task
    pub priority: PlanEntryPriority,
    /// Current progress of this task
    pub status: PlanEntryStatus,
}

/// Priority levels for plan entries.
///
/// Used to indicate the relative importance or urgency of different
/// tasks in the execution plan.
#[derive(Deserialize, Serialize, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum PlanEntryPriority {
    High,
    Medium,
    Low,
}

/// Status of a plan entry in the execution flow.
///
/// Tracks the lifecycle of each task from planning through completion.
#[derive(Deserialize, Serialize, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum PlanEntryStatus {
    Pending,
    InProgress,
    Completed,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum ToolCallStatus {
    /// The tool call is currently running
    Running,
    /// The tool call completed successfully
    Finished,
    /// The tool call failed
    Error,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ToolCallContent {
    #[serde(rename_all = "camelCase")]
    Markdown { markdown: String },
    #[serde(rename_all = "camelCase")]
    Diff {
        #[serde(flatten)]
        diff: Diff,
    },
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Diff {
    pub path: PathBuf,
    pub old_text: Option<String>,
    pub new_text: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct WriteTextFileParams {
    pub path: PathBuf,
    pub content: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct WriteTextFileResponse;

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ReadTextFileParams {
    pub path: PathBuf,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct ReadTextFileResponse {
    pub content: String,
}