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