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    let can_collect_data = false;
175    let git_info = None;
176    cx.update(|cx| {
177        gather_context(
178            project.as_ref(),
179            full_path_str,
180            &snapshot,
181            clipped_cursor,
182            move || events,
183            can_collect_data,
184            git_info,
185            cx,
186        )
187    })?
188    .await
189}
190
191pub async fn open_buffer_with_language_server(
192    worktree_path: &Path,
193    path: &Path,
194    app_state: &Arc<ZetaCliAppState>,
195    cx: &mut AsyncApp,
196) -> Result<(Entity<Project>, Entity<Entity<Buffer>>, Entity<Buffer>)> {
197    let project = cx.update(|cx| {
198        Project::local(
199            app_state.client.clone(),
200            app_state.node_runtime.clone(),
201            app_state.user_store.clone(),
202            app_state.languages.clone(),
203            app_state.fs.clone(),
204            None,
205            cx,
206        )
207    })?;
208
209    let worktree = project
210        .update(cx, |project, cx| {
211            project.create_worktree(worktree_path, true, cx)
212        })?
213        .await?;
214
215    let project_path = worktree.read_with(cx, |worktree, _cx| ProjectPath {
216        worktree_id: worktree.id(),
217        path: path.to_path_buf().into(),
218    })?;
219
220    let buffer = project
221        .update(cx, |project, cx| project.open_buffer(project_path, cx))?
222        .await?;
223
224    let lsp_open_handle = project.update(cx, |project, cx| {
225        project.register_buffer_with_language_servers(&buffer, cx)
226    })?;
227
228    let log_prefix = path.to_string_lossy().to_string();
229    wait_for_lang_server(&project, &buffer, log_prefix, cx).await?;
230
231    Ok((project, lsp_open_handle, buffer))
232}
233
234// TODO: Dedupe with similar function in crates/eval/src/instance.rs
235pub fn wait_for_lang_server(
236    project: &Entity<Project>,
237    buffer: &Entity<Buffer>,
238    log_prefix: String,
239    cx: &mut AsyncApp,
240) -> Task<Result<()>> {
241    println!("{}⏵ Waiting for language server", log_prefix);
242
243    let (mut tx, mut rx) = mpsc::channel(1);
244
245    let lsp_store = project
246        .read_with(cx, |project, _| project.lsp_store())
247        .unwrap();
248
249    let has_lang_server = buffer
250        .update(cx, |buffer, cx| {
251            lsp_store.update(cx, |lsp_store, cx| {
252                lsp_store
253                    .language_servers_for_local_buffer(&buffer, cx)
254                    .next()
255                    .is_some()
256            })
257        })
258        .unwrap_or(false);
259
260    if has_lang_server {
261        project
262            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
263            .unwrap()
264            .detach();
265    }
266
267    let subscriptions = [
268        cx.subscribe(&lsp_store, {
269            let log_prefix = log_prefix.clone();
270            move |_, event, _| match event {
271                project::LspStoreEvent::LanguageServerUpdate {
272                    message:
273                        client::proto::update_language_server::Variant::WorkProgress(
274                            client::proto::LspWorkProgress {
275                                message: Some(message),
276                                ..
277                            },
278                        ),
279                    ..
280                } => println!("{}{message}", log_prefix),
281                _ => {}
282            }
283        }),
284        cx.subscribe(&project, {
285            let buffer = buffer.clone();
286            move |project, event, cx| match event {
287                project::Event::LanguageServerAdded(_, _, _) => {
288                    let buffer = buffer.clone();
289                    project
290                        .update(cx, |project, cx| project.save_buffer(buffer, cx))
291                        .detach();
292                }
293                project::Event::DiskBasedDiagnosticsFinished { .. } => {
294                    tx.try_send(()).ok();
295                }
296                _ => {}
297            }
298        }),
299    ];
300
301    cx.spawn(async move |cx| {
302        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
303        let result = futures::select! {
304            _ = rx.next() => {
305                println!("{}⚑ Language server idle", log_prefix);
306                anyhow::Ok(())
307            },
308            _ = timeout.fuse() => {
309                anyhow::bail!("LSP wait timed out after 5 minutes");
310            }
311        };
312        drop(subscriptions);
313        result
314    })
315}
316
317fn main() {
318    let args = ZetaCliArgs::parse();
319    let http_client = Arc::new(ReqwestClient::new());
320    let app = Application::headless().with_http_client(http_client);
321
322    app.run(move |cx| {
323        let app_state = Arc::new(headless::init(cx));
324        cx.spawn(async move |cx| {
325            let result = match args.command {
326                Commands::Context(context_args) => get_context(context_args, &app_state, cx)
327                    .await
328                    .map(|output| serde_json::to_string_pretty(&output.body).unwrap()),
329                Commands::Predict {
330                    predict_edits_body,
331                    context_args,
332                } => {
333                    cx.spawn(async move |cx| {
334                        let app_version = cx.update(|cx| AppVersion::global(cx))?;
335                        app_state.client.sign_in(true, cx).await?;
336                        let llm_token = LlmApiToken::default();
337                        llm_token.refresh(&app_state.client).await?;
338
339                        let predict_edits_body =
340                            if let Some(predict_edits_body) = predict_edits_body {
341                                serde_json::from_str(&predict_edits_body.read_to_string().await?)?
342                            } else if let Some(context_args) = context_args {
343                                get_context(context_args, &app_state, cx).await?.body
344                            } else {
345                                return Err(anyhow!(
346                                    "Expected either --predict-edits-body-file \
347                                    or the required args of the `context` command."
348                                ));
349                            };
350
351                        let (response, _usage) =
352                            Zeta::perform_predict_edits(PerformPredictEditsParams {
353                                client: app_state.client.clone(),
354                                llm_token,
355                                app_version,
356                                body: predict_edits_body,
357                            })
358                            .await?;
359
360                        Ok(response.output_excerpt)
361                    })
362                    .await
363                }
364            };
365            match result {
366                Ok(output) => {
367                    println!("{}", output);
368                    let _ = cx.update(|cx| cx.quit());
369                }
370                Err(e) => {
371                    eprintln!("Failed: {:?}", e);
372                    exit(1);
373                }
374            }
375        })
376        .detach();
377    });
378}