1use std::str::FromStr;
2use std::sync::Arc;
3
4use anyhow::Context as _;
5use serde::{Deserialize, Serialize};
6use strum::{Display, EnumIter, EnumString};
7use uuid::Uuid;
8
9/// The name of the header used to indicate which version of Zed the client is running.
10pub const ZED_VERSION_HEADER_NAME: &str = "x-zed-version";
11
12/// The name of the header used to indicate when a request failed due to an
13/// expired LLM token.
14///
15/// The client may use this as a signal to refresh the token.
16pub const EXPIRED_LLM_TOKEN_HEADER_NAME: &str = "x-zed-expired-token";
17
18/// The name of the header used to indicate what plan the user is currently on.
19pub const CURRENT_PLAN_HEADER_NAME: &str = "x-zed-plan";
20
21/// The name of the header used to indicate the usage limit for model requests.
22pub const MODEL_REQUESTS_USAGE_LIMIT_HEADER_NAME: &str = "x-zed-model-requests-usage-limit";
23
24/// The name of the header used to indicate the usage amount for model requests.
25pub const MODEL_REQUESTS_USAGE_AMOUNT_HEADER_NAME: &str = "x-zed-model-requests-usage-amount";
26
27/// The name of the header used to indicate the usage limit for edit predictions.
28pub const EDIT_PREDICTIONS_USAGE_LIMIT_HEADER_NAME: &str = "x-zed-edit-predictions-usage-limit";
29
30/// The name of the header used to indicate the usage amount for edit predictions.
31pub const EDIT_PREDICTIONS_USAGE_AMOUNT_HEADER_NAME: &str = "x-zed-edit-predictions-usage-amount";
32
33/// The name of the header used to indicate the resource for which the subscription limit has been reached.
34pub const SUBSCRIPTION_LIMIT_RESOURCE_HEADER_NAME: &str = "x-zed-subscription-limit-resource";
35
36pub const MODEL_REQUESTS_RESOURCE_HEADER_VALUE: &str = "model_requests";
37pub const EDIT_PREDICTIONS_RESOURCE_HEADER_VALUE: &str = "edit_predictions";
38
39/// The name of the header used to indicate that the maximum number of consecutive tool uses has been reached.
40pub const TOOL_USE_LIMIT_REACHED_HEADER_NAME: &str = "x-zed-tool-use-limit-reached";
41
42/// The name of the header used to indicate the the minimum required Zed version.
43///
44/// This can be used to force a Zed upgrade in order to continue communicating
45/// with the LLM service.
46pub const MINIMUM_REQUIRED_VERSION_HEADER_NAME: &str = "x-zed-minimum-required-version";
47
48/// The name of the header used by the client to indicate to the server that it supports receiving status messages.
49pub const CLIENT_SUPPORTS_STATUS_MESSAGES_HEADER_NAME: &str =
50 "x-zed-client-supports-status-messages";
51
52/// The name of the header used by the server to indicate to the client that it supports sending status messages.
53pub const SERVER_SUPPORTS_STATUS_MESSAGES_HEADER_NAME: &str =
54 "x-zed-server-supports-status-messages";
55
56#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
57#[serde(rename_all = "snake_case")]
58pub enum UsageLimit {
59 Limited(i32),
60 Unlimited,
61}
62
63impl FromStr for UsageLimit {
64 type Err = anyhow::Error;
65
66 fn from_str(value: &str) -> Result<Self, Self::Err> {
67 match value {
68 "unlimited" => Ok(Self::Unlimited),
69 limit => limit
70 .parse::<i32>()
71 .map(Self::Limited)
72 .context("failed to parse limit"),
73 }
74 }
75}
76
77#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
78#[serde(rename_all = "snake_case")]
79pub enum Plan {
80 #[default]
81 #[serde(alias = "Free")]
82 ZedFree,
83 #[serde(alias = "ZedPro")]
84 ZedPro,
85 #[serde(alias = "ZedProTrial")]
86 ZedProTrial,
87}
88
89impl Plan {
90 pub fn as_str(&self) -> &'static str {
91 match self {
92 Plan::ZedFree => "zed_free",
93 Plan::ZedPro => "zed_pro",
94 Plan::ZedProTrial => "zed_pro_trial",
95 }
96 }
97
98 pub fn model_requests_limit(&self) -> UsageLimit {
99 match self {
100 Plan::ZedPro => UsageLimit::Limited(500),
101 Plan::ZedProTrial => UsageLimit::Limited(150),
102 Plan::ZedFree => UsageLimit::Limited(50),
103 }
104 }
105
106 pub fn edit_predictions_limit(&self) -> UsageLimit {
107 match self {
108 Plan::ZedPro => UsageLimit::Unlimited,
109 Plan::ZedProTrial => UsageLimit::Unlimited,
110 Plan::ZedFree => UsageLimit::Limited(2_000),
111 }
112 }
113}
114
115impl FromStr for Plan {
116 type Err = anyhow::Error;
117
118 fn from_str(value: &str) -> Result<Self, Self::Err> {
119 match value {
120 "zed_free" => Ok(Plan::ZedFree),
121 "zed_pro" => Ok(Plan::ZedPro),
122 "zed_pro_trial" => Ok(Plan::ZedProTrial),
123 plan => Err(anyhow::anyhow!("invalid plan: {plan:?}")),
124 }
125 }
126}
127
128#[derive(
129 Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize, EnumString, EnumIter, Display,
130)]
131#[serde(rename_all = "snake_case")]
132#[strum(serialize_all = "snake_case")]
133pub enum LanguageModelProvider {
134 Anthropic,
135 OpenAi,
136 Google,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct PredictEditsBody {
141 #[serde(skip_serializing_if = "Option::is_none", default)]
142 pub outline: Option<String>,
143 pub input_events: String,
144 pub input_excerpt: String,
145 #[serde(skip_serializing_if = "Option::is_none", default)]
146 pub speculated_output: Option<String>,
147 /// Whether the user provided consent for sampling this interaction.
148 #[serde(default, alias = "data_collection_permission")]
149 pub can_collect_data: bool,
150 #[serde(skip_serializing_if = "Option::is_none", default)]
151 pub diagnostic_groups: Option<Vec<(String, serde_json::Value)>>,
152 /// Info about the git repository state, only present when can_collect_data is true.
153 #[serde(skip_serializing_if = "Option::is_none", default)]
154 pub git_info: Option<PredictEditsGitInfo>,
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct PredictEditsGitInfo {
159 /// SHA of git HEAD commit at time of prediction.
160 #[serde(skip_serializing_if = "Option::is_none", default)]
161 pub head_sha: Option<String>,
162 /// URL of the remote called `origin`.
163 #[serde(skip_serializing_if = "Option::is_none", default)]
164 pub remote_origin_url: Option<String>,
165 /// URL of the remote called `upstream`.
166 #[serde(skip_serializing_if = "Option::is_none", default)]
167 pub remote_upstream_url: Option<String>,
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct PredictEditsResponse {
172 pub request_id: Uuid,
173 pub output_excerpt: String,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct AcceptEditPredictionBody {
178 pub request_id: Uuid,
179}
180
181#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
182#[serde(rename_all = "snake_case")]
183pub enum CompletionMode {
184 Normal,
185 Max,
186}
187
188#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
189#[serde(rename_all = "snake_case")]
190pub enum CompletionIntent {
191 UserPrompt,
192 ToolResults,
193 ThreadSummarization,
194 ThreadContextSummarization,
195 CreateFile,
196 EditFile,
197 InlineAssist,
198 TerminalInlineAssist,
199 GenerateGitCommitMessage,
200}
201
202#[derive(Debug, Serialize, Deserialize)]
203pub struct CompletionBody {
204 #[serde(skip_serializing_if = "Option::is_none", default)]
205 pub thread_id: Option<String>,
206 #[serde(skip_serializing_if = "Option::is_none", default)]
207 pub prompt_id: Option<String>,
208 #[serde(skip_serializing_if = "Option::is_none", default)]
209 pub intent: Option<CompletionIntent>,
210 #[serde(skip_serializing_if = "Option::is_none", default)]
211 pub mode: Option<CompletionMode>,
212 pub provider: LanguageModelProvider,
213 pub model: String,
214 pub provider_request: serde_json::Value,
215}
216
217#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
218#[serde(rename_all = "snake_case")]
219pub enum CompletionRequestStatus {
220 Queued {
221 position: usize,
222 },
223 Started,
224 Failed {
225 code: String,
226 message: String,
227 request_id: Uuid,
228 /// Retry duration in seconds.
229 retry_after: Option<f64>,
230 },
231 UsageUpdated {
232 amount: usize,
233 limit: UsageLimit,
234 },
235 ToolUseLimitReached,
236}
237
238#[derive(Serialize, Deserialize)]
239#[serde(rename_all = "snake_case")]
240pub enum CompletionEvent<T> {
241 Status(CompletionRequestStatus),
242 Event(T),
243}
244
245impl<T> CompletionEvent<T> {
246 pub fn into_status(self) -> Option<CompletionRequestStatus> {
247 match self {
248 Self::Status(status) => Some(status),
249 Self::Event(_) => None,
250 }
251 }
252
253 pub fn into_event(self) -> Option<T> {
254 match self {
255 Self::Event(event) => Some(event),
256 Self::Status(_) => None,
257 }
258 }
259}
260
261#[derive(Serialize, Deserialize)]
262pub struct WebSearchBody {
263 pub query: String,
264}
265
266#[derive(Debug, Serialize, Deserialize, Clone)]
267pub struct WebSearchResponse {
268 pub results: Vec<WebSearchResult>,
269}
270
271#[derive(Debug, Serialize, Deserialize, Clone)]
272pub struct WebSearchResult {
273 pub title: String,
274 pub url: String,
275 pub text: String,
276}
277
278#[derive(Serialize, Deserialize)]
279pub struct CountTokensBody {
280 pub provider: LanguageModelProvider,
281 pub model: String,
282 pub provider_request: serde_json::Value,
283}
284
285#[derive(Serialize, Deserialize)]
286pub struct CountTokensResponse {
287 pub tokens: usize,
288}
289
290#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
291pub struct LanguageModelId(pub Arc<str>);
292
293impl std::fmt::Display for LanguageModelId {
294 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295 write!(f, "{}", self.0)
296 }
297}
298
299#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
300pub struct LanguageModel {
301 pub provider: LanguageModelProvider,
302 pub id: LanguageModelId,
303 pub display_name: String,
304 pub max_token_count: usize,
305 pub max_token_count_in_max_mode: Option<usize>,
306 pub max_output_tokens: usize,
307 pub supports_tools: bool,
308 pub supports_images: bool,
309 pub supports_thinking: bool,
310 pub supports_max_mode: bool,
311}
312
313#[derive(Debug, Serialize, Deserialize)]
314pub struct ListModelsResponse {
315 pub models: Vec<LanguageModel>,
316 pub default_model: LanguageModelId,
317 pub default_fast_model: LanguageModelId,
318 pub recommended_models: Vec<LanguageModelId>,
319}
320
321#[derive(Debug, Serialize, Deserialize)]
322pub struct GetSubscriptionResponse {
323 pub plan: Plan,
324 pub usage: Option<CurrentUsage>,
325}
326
327#[derive(Debug, PartialEq, Serialize, Deserialize)]
328pub struct CurrentUsage {
329 pub model_requests: UsageData,
330 pub edit_predictions: UsageData,
331}
332
333#[derive(Debug, PartialEq, Serialize, Deserialize)]
334pub struct UsageData {
335 pub used: u32,
336 pub limit: UsageLimit,
337}
338
339#[cfg(test)]
340mod tests {
341 use pretty_assertions::assert_eq;
342 use serde_json::json;
343
344 use super::*;
345
346 #[test]
347 fn test_plan_deserialize_snake_case() {
348 let plan = serde_json::from_value::<Plan>(json!("zed_free")).unwrap();
349 assert_eq!(plan, Plan::ZedFree);
350
351 let plan = serde_json::from_value::<Plan>(json!("zed_pro")).unwrap();
352 assert_eq!(plan, Plan::ZedPro);
353
354 let plan = serde_json::from_value::<Plan>(json!("zed_pro_trial")).unwrap();
355 assert_eq!(plan, Plan::ZedProTrial);
356 }
357
358 #[test]
359 fn test_plan_deserialize_aliases() {
360 let plan = serde_json::from_value::<Plan>(json!("Free")).unwrap();
361 assert_eq!(plan, Plan::ZedFree);
362
363 let plan = serde_json::from_value::<Plan>(json!("ZedPro")).unwrap();
364 assert_eq!(plan, Plan::ZedPro);
365
366 let plan = serde_json::from_value::<Plan>(json!("ZedProTrial")).unwrap();
367 assert_eq!(plan, Plan::ZedProTrial);
368 }
369
370 #[test]
371 fn test_usage_limit_from_str() {
372 let limit = UsageLimit::from_str("unlimited").unwrap();
373 assert!(matches!(limit, UsageLimit::Unlimited));
374
375 let limit = UsageLimit::from_str(&0.to_string()).unwrap();
376 assert!(matches!(limit, UsageLimit::Limited(0)));
377
378 let limit = UsageLimit::from_str(&50.to_string()).unwrap();
379 assert!(matches!(limit, UsageLimit::Limited(50)));
380
381 for value in ["not_a_number", "50xyz"] {
382 let limit = UsageLimit::from_str(value);
383 assert!(limit.is_err());
384 }
385 }
386}