main.rs

  1mod headless;
  2
  3use anyhow::{Result, anyhow};
  4use clap::{Args, Parser, Subcommand};
  5use futures::channel::mpsc;
  6use futures::{FutureExt as _, StreamExt as _};
  7use gpui::{AppContext, Application, AsyncApp};
  8use gpui::{Entity, Task};
  9use language::Bias;
 10use language::Buffer;
 11use language::Point;
 12use language_model::LlmApiToken;
 13use project::{Project, ProjectPath};
 14use release_channel::AppVersion;
 15use reqwest_client::ReqwestClient;
 16use std::path::{Path, PathBuf};
 17use std::process::exit;
 18use std::str::FromStr;
 19use std::sync::Arc;
 20use std::time::Duration;
 21use zeta::{GatherContextOutput, PerformPredictEditsParams, Zeta, gather_context};
 22
 23use crate::headless::ZetaCliAppState;
 24
 25#[derive(Parser, Debug)]
 26#[command(name = "zeta")]
 27struct ZetaCliArgs {
 28    #[command(subcommand)]
 29    command: Commands,
 30}
 31
 32#[derive(Subcommand, Debug)]
 33enum Commands {
 34    Context(ContextArgs),
 35    Predict {
 36        #[arg(long)]
 37        predict_edits_body: Option<FileOrStdin>,
 38        #[clap(flatten)]
 39        context_args: Option<ContextArgs>,
 40    },
 41}
 42
 43#[derive(Debug, Args)]
 44#[group(requires = "worktree")]
 45struct ContextArgs {
 46    #[arg(long)]
 47    worktree: PathBuf,
 48    #[arg(long)]
 49    cursor: CursorPosition,
 50    #[arg(long)]
 51    use_language_server: bool,
 52    #[arg(long)]
 53    events: Option<FileOrStdin>,
 54}
 55
 56#[derive(Debug, Clone)]
 57enum FileOrStdin {
 58    File(PathBuf),
 59    Stdin,
 60}
 61
 62impl FileOrStdin {
 63    async fn read_to_string(&self) -> Result<String, std::io::Error> {
 64        match self {
 65            FileOrStdin::File(path) => smol::fs::read_to_string(path).await,
 66            FileOrStdin::Stdin => smol::unblock(|| std::io::read_to_string(std::io::stdin())).await,
 67        }
 68    }
 69}
 70
 71impl FromStr for FileOrStdin {
 72    type Err = <PathBuf as FromStr>::Err;
 73
 74    fn from_str(s: &str) -> Result<Self, Self::Err> {
 75        match s {
 76            "-" => Ok(Self::Stdin),
 77            _ => Ok(Self::File(PathBuf::from_str(s)?)),
 78        }
 79    }
 80}
 81
 82#[derive(Debug, Clone)]
 83struct CursorPosition {
 84    path: PathBuf,
 85    point: Point,
 86}
 87
 88impl FromStr for CursorPosition {
 89    type Err = anyhow::Error;
 90
 91    fn from_str(s: &str) -> Result<Self> {
 92        let parts: Vec<&str> = s.split(':').collect();
 93        if parts.len() != 3 {
 94            return Err(anyhow!(
 95                "Invalid cursor format. Expected 'file.rs:line:column', got '{}'",
 96                s
 97            ));
 98        }
 99
100        let path = PathBuf::from(parts[0]);
101        let line: u32 = parts[1]
102            .parse()
103            .map_err(|_| anyhow!("Invalid line number: '{}'", parts[1]))?;
104        let column: u32 = parts[2]
105            .parse()
106            .map_err(|_| anyhow!("Invalid column number: '{}'", parts[2]))?;
107
108        // Convert from 1-based to 0-based indexing
109        let point = Point::new(line.saturating_sub(1), column.saturating_sub(1));
110
111        Ok(CursorPosition { path, point })
112    }
113}
114
115async fn get_context(
116    args: ContextArgs,
117    app_state: &Arc<ZetaCliAppState>,
118    cx: &mut AsyncApp,
119) -> Result<GatherContextOutput> {
120    let ContextArgs {
121        worktree: worktree_path,
122        cursor,
123        use_language_server,
124        events,
125    } = args;
126
127    let worktree_path = worktree_path.canonicalize()?;
128    if cursor.path.is_absolute() {
129        return Err(anyhow!("Absolute paths are not supported in --cursor"));
130    }
131
132    let (project, _lsp_open_handle, buffer) = if use_language_server {
133        let (project, lsp_open_handle, buffer) =
134            open_buffer_with_language_server(&worktree_path, &cursor.path, &app_state, cx).await?;
135        (Some(project), Some(lsp_open_handle), buffer)
136    } else {
137        let abs_path = worktree_path.join(&cursor.path);
138        let content = smol::fs::read_to_string(&abs_path).await?;
139        let buffer = cx.new(|cx| Buffer::local(content, cx))?;
140        (None, None, buffer)
141    };
142
143    let worktree_name = worktree_path
144        .file_name()
145        .ok_or_else(|| anyhow!("--worktree path must end with a folder name"))?;
146    let full_path_str = PathBuf::from(worktree_name)
147        .join(&cursor.path)
148        .to_string_lossy()
149        .to_string();
150
151    let snapshot = cx.update(|cx| buffer.read(cx).snapshot())?;
152    let clipped_cursor = snapshot.clip_point(cursor.point, Bias::Left);
153    if clipped_cursor != cursor.point {
154        let max_row = snapshot.max_point().row;
155        if cursor.point.row < max_row {
156            return Err(anyhow!(
157                "Cursor position {:?} is out of bounds (line length is {})",
158                cursor.point,
159                snapshot.line_len(cursor.point.row)
160            ));
161        } else {
162            return Err(anyhow!(
163                "Cursor position {:?} is out of bounds (max row is {})",
164                cursor.point,
165                max_row
166            ));
167        }
168    }
169
170    let events = match events {
171        Some(events) => events.read_to_string().await?,
172        None => String::new(),
173    };
174    // Enable gathering extra data not currently needed for edit predictions
175    let can_collect_data = true;
176    let git_info = None;
177    let mut gather_context_output = cx
178        .update(|cx| {
179            gather_context(
180                project.as_ref(),
181                full_path_str,
182                &snapshot,
183                clipped_cursor,
184                move || events,
185                can_collect_data,
186                git_info,
187                cx,
188            )
189        })?
190        .await;
191
192    // Disable data collection for these requests, as this is currently just used for evals
193    match gather_context_output.as_mut() {
194        Ok(gather_context_output) => gather_context_output.body.can_collect_data = false,
195        Err(_) => {}
196    }
197
198    gather_context_output
199}
200
201pub async fn open_buffer_with_language_server(
202    worktree_path: &Path,
203    path: &Path,
204    app_state: &Arc<ZetaCliAppState>,
205    cx: &mut AsyncApp,
206) -> Result<(Entity<Project>, Entity<Entity<Buffer>>, Entity<Buffer>)> {
207    let project = cx.update(|cx| {
208        Project::local(
209            app_state.client.clone(),
210            app_state.node_runtime.clone(),
211            app_state.user_store.clone(),
212            app_state.languages.clone(),
213            app_state.fs.clone(),
214            None,
215            cx,
216        )
217    })?;
218
219    let worktree = project
220        .update(cx, |project, cx| {
221            project.create_worktree(worktree_path, true, cx)
222        })?
223        .await?;
224
225    let project_path = worktree.read_with(cx, |worktree, _cx| ProjectPath {
226        worktree_id: worktree.id(),
227        path: path.to_path_buf().into(),
228    })?;
229
230    let buffer = project
231        .update(cx, |project, cx| project.open_buffer(project_path, cx))?
232        .await?;
233
234    let lsp_open_handle = project.update(cx, |project, cx| {
235        project.register_buffer_with_language_servers(&buffer, cx)
236    })?;
237
238    let log_prefix = path.to_string_lossy().to_string();
239    wait_for_lang_server(&project, &buffer, log_prefix, cx).await?;
240
241    Ok((project, lsp_open_handle, buffer))
242}
243
244// TODO: Dedupe with similar function in crates/eval/src/instance.rs
245pub fn wait_for_lang_server(
246    project: &Entity<Project>,
247    buffer: &Entity<Buffer>,
248    log_prefix: String,
249    cx: &mut AsyncApp,
250) -> Task<Result<()>> {
251    println!("{}⏵ Waiting for language server", log_prefix);
252
253    let (mut tx, mut rx) = mpsc::channel(1);
254
255    let lsp_store = project
256        .read_with(cx, |project, _| project.lsp_store())
257        .unwrap();
258
259    let has_lang_server = buffer
260        .update(cx, |buffer, cx| {
261            lsp_store.update(cx, |lsp_store, cx| {
262                lsp_store
263                    .language_servers_for_local_buffer(&buffer, cx)
264                    .next()
265                    .is_some()
266            })
267        })
268        .unwrap_or(false);
269
270    if has_lang_server {
271        project
272            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
273            .unwrap()
274            .detach();
275    }
276
277    let subscriptions = [
278        cx.subscribe(&lsp_store, {
279            let log_prefix = log_prefix.clone();
280            move |_, event, _| match event {
281                project::LspStoreEvent::LanguageServerUpdate {
282                    message:
283                        client::proto::update_language_server::Variant::WorkProgress(
284                            client::proto::LspWorkProgress {
285                                message: Some(message),
286                                ..
287                            },
288                        ),
289                    ..
290                } => println!("{}{message}", log_prefix),
291                _ => {}
292            }
293        }),
294        cx.subscribe(&project, {
295            let buffer = buffer.clone();
296            move |project, event, cx| match event {
297                project::Event::LanguageServerAdded(_, _, _) => {
298                    let buffer = buffer.clone();
299                    project
300                        .update(cx, |project, cx| project.save_buffer(buffer, cx))
301                        .detach();
302                }
303                project::Event::DiskBasedDiagnosticsFinished { .. } => {
304                    tx.try_send(()).ok();
305                }
306                _ => {}
307            }
308        }),
309    ];
310
311    cx.spawn(async move |cx| {
312        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
313        let result = futures::select! {
314            _ = rx.next() => {
315                println!("{}⚑ Language server idle", log_prefix);
316                anyhow::Ok(())
317            },
318            _ = timeout.fuse() => {
319                anyhow::bail!("LSP wait timed out after 5 minutes");
320            }
321        };
322        drop(subscriptions);
323        result
324    })
325}
326
327fn main() {
328    let args = ZetaCliArgs::parse();
329    let http_client = Arc::new(ReqwestClient::new());
330    let app = Application::headless().with_http_client(http_client);
331
332    app.run(move |cx| {
333        let app_state = Arc::new(headless::init(cx));
334        cx.spawn(async move |cx| {
335            let result = match args.command {
336                Commands::Context(context_args) => get_context(context_args, &app_state, cx)
337                    .await
338                    .map(|output| serde_json::to_string_pretty(&output.body).unwrap()),
339                Commands::Predict {
340                    predict_edits_body,
341                    context_args,
342                } => {
343                    cx.spawn(async move |cx| {
344                        let app_version = cx.update(|cx| AppVersion::global(cx))?;
345                        app_state.client.sign_in(true, cx).await?;
346                        let llm_token = LlmApiToken::default();
347                        llm_token.refresh(&app_state.client).await?;
348
349                        let predict_edits_body =
350                            if let Some(predict_edits_body) = predict_edits_body {
351                                serde_json::from_str(&predict_edits_body.read_to_string().await?)?
352                            } else if let Some(context_args) = context_args {
353                                get_context(context_args, &app_state, cx).await?.body
354                            } else {
355                                return Err(anyhow!(
356                                    "Expected either --predict-edits-body-file \
357                                    or the required args of the `context` command."
358                                ));
359                            };
360
361                        let (response, _usage) =
362                            Zeta::perform_predict_edits(PerformPredictEditsParams {
363                                client: app_state.client.clone(),
364                                llm_token,
365                                app_version,
366                                body: predict_edits_body,
367                            })
368                            .await?;
369
370                        Ok(response.output_excerpt)
371                    })
372                    .await
373                }
374            };
375            match result {
376                Ok(output) => {
377                    println!("{}", output);
378                    let _ = cx.update(|cx| cx.quit());
379                }
380                Err(e) => {
381                    eprintln!("Failed: {:?}", e);
382                    exit(1);
383                }
384            }
385        })
386        .detach();
387    });
388}