extension_api.rs

  1//! The Zed Rust Extension API allows you write extensions for [Zed](https://zed.dev/) in Rust.
  2
  3pub mod http_client;
  4pub mod process;
  5pub mod settings;
  6
  7use core::fmt;
  8
  9use wit::*;
 10
 11pub use serde_json;
 12
 13// WIT re-exports.
 14//
 15// We explicitly enumerate the symbols we want to re-export, as there are some
 16// that we may want to shadow to provide a cleaner Rust API.
 17pub use wit::{
 18    CodeLabel, CodeLabelSpan, CodeLabelSpanLiteral, Command, DownloadedFileType, EnvVars,
 19    KeyValueStore, LanguageServerInstallationStatus, Project, Range, Worktree, download_file,
 20    make_file_executable,
 21    zed::extension::context_server::ContextServerConfiguration,
 22    zed::extension::dap::{
 23        AttachRequest, BuildTaskDefinition, BuildTaskDefinitionTemplatePayload, BuildTaskTemplate,
 24        DebugAdapterBinary, DebugConfig, DebugRequest, DebugScenario, DebugTaskDefinition,
 25        LaunchRequest, StartDebuggingRequestArguments, StartDebuggingRequestArgumentsRequest,
 26        TaskTemplate, TcpArguments, TcpArgumentsTemplate, resolve_tcp_template,
 27    },
 28    zed::extension::github::{
 29        GithubRelease, GithubReleaseAsset, GithubReleaseOptions, github_release_by_tag_name,
 30        latest_github_release,
 31    },
 32    zed::extension::llm_provider::{
 33        CacheConfiguration as LlmCacheConfiguration, CompletionEvent as LlmCompletionEvent,
 34        CompletionRequest as LlmCompletionRequest, CustomModelConfig as LlmCustomModelConfig,
 35        DeviceFlowPromptInfo as LlmDeviceFlowPromptInfo, ImageData as LlmImageData,
 36        MessageContent as LlmMessageContent, MessageRole as LlmMessageRole,
 37        ModelCapabilities as LlmModelCapabilities, ModelInfo as LlmModelInfo,
 38        OauthWebAuthConfig as LlmOauthWebAuthConfig,
 39        OauthWebAuthResult as LlmOauthWebAuthResult, ProviderInfo as LlmProviderInfo,
 40        ProviderSettings as LlmProviderSettings, RequestMessage as LlmRequestMessage,
 41        StopReason as LlmStopReason, ThinkingContent as LlmThinkingContent,
 42        TokenUsage as LlmTokenUsage, ToolChoice as LlmToolChoice,
 43        ToolDefinition as LlmToolDefinition, ToolInputFormat as LlmToolInputFormat,
 44        ToolResult as LlmToolResult, ToolResultContent as LlmToolResultContent,
 45        ToolUse as LlmToolUse, ToolUseJsonParseError as LlmToolUseJsonParseError,
 46        delete_credential as llm_delete_credential, get_credential as llm_get_credential,
 47        get_env_var as llm_get_env_var, get_provider_settings as llm_get_provider_settings,
 48        oauth_open_browser as llm_oauth_open_browser,
 49        oauth_send_http_request as llm_oauth_send_http_request,
 50        oauth_start_web_auth as llm_oauth_start_web_auth,
 51        store_credential as llm_store_credential,
 52    },
 53    zed::extension::nodejs::{
 54        node_binary_path, npm_install_package, npm_package_installed_version,
 55        npm_package_latest_version,
 56    },
 57    zed::extension::platform::{Architecture, Os, current_platform},
 58    zed::extension::slash_command::{
 59        SlashCommand, SlashCommandArgumentCompletion, SlashCommandOutput, SlashCommandOutputSection,
 60    },
 61};
 62
 63// Undocumented WIT re-exports.
 64//
 65// These are symbols that need to be public for the purposes of implementing
 66// the extension host, but aren't relevant to extension authors.
 67#[doc(hidden)]
 68pub use wit::Guest;
 69
 70/// Constructs for interacting with language servers over the
 71/// Language Server Protocol (LSP).
 72pub mod lsp {
 73    pub use crate::wit::zed::extension::lsp::{
 74        Completion, CompletionKind, InsertTextFormat, Symbol, SymbolKind,
 75    };
 76}
 77
 78/// A result returned from a Zed extension.
 79pub type Result<T, E = String> = core::result::Result<T, E>;
 80
 81/// Updates the installation status for the given language server.
 82pub fn set_language_server_installation_status(
 83    language_server_id: &LanguageServerId,
 84    status: &LanguageServerInstallationStatus,
 85) {
 86    wit::set_language_server_installation_status(&language_server_id.0, status)
 87}
 88
 89/// A Zed extension.
 90pub trait Extension: Send + Sync {
 91    /// Returns a new instance of the extension.
 92    fn new() -> Self
 93    where
 94        Self: Sized;
 95
 96    /// Returns the command used to start the language server for the specified
 97    /// language.
 98    fn language_server_command(
 99        &mut self,
100        _language_server_id: &LanguageServerId,
101        _worktree: &Worktree,
102    ) -> Result<Command> {
103        Err("`language_server_command` not implemented".to_string())
104    }
105
106    /// Returns the initialization options to pass to the specified language server.
107    fn language_server_initialization_options(
108        &mut self,
109        _language_server_id: &LanguageServerId,
110        _worktree: &Worktree,
111    ) -> Result<Option<serde_json::Value>> {
112        Ok(None)
113    }
114
115    /// Returns the workspace configuration options to pass to the language server.
116    fn language_server_workspace_configuration(
117        &mut self,
118        _language_server_id: &LanguageServerId,
119        _worktree: &Worktree,
120    ) -> Result<Option<serde_json::Value>> {
121        Ok(None)
122    }
123
124    /// Returns the initialization options to pass to the other language server.
125    fn language_server_additional_initialization_options(
126        &mut self,
127        _language_server_id: &LanguageServerId,
128        _target_language_server_id: &LanguageServerId,
129        _worktree: &Worktree,
130    ) -> Result<Option<serde_json::Value>> {
131        Ok(None)
132    }
133
134    /// Returns the workspace configuration options to pass to the other language server.
135    fn language_server_additional_workspace_configuration(
136        &mut self,
137        _language_server_id: &LanguageServerId,
138        _target_language_server_id: &LanguageServerId,
139        _worktree: &Worktree,
140    ) -> Result<Option<serde_json::Value>> {
141        Ok(None)
142    }
143
144    /// Returns the label for the given completion.
145    fn label_for_completion(
146        &self,
147        _language_server_id: &LanguageServerId,
148        _completion: Completion,
149    ) -> Option<CodeLabel> {
150        None
151    }
152
153    /// Returns the label for the given symbol.
154    fn label_for_symbol(
155        &self,
156        _language_server_id: &LanguageServerId,
157        _symbol: Symbol,
158    ) -> Option<CodeLabel> {
159        None
160    }
161
162    /// Returns the completions that should be shown when completing the provided slash command with the given query.
163    fn complete_slash_command_argument(
164        &self,
165        _command: SlashCommand,
166        _args: Vec<String>,
167    ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
168        Ok(Vec::new())
169    }
170
171    /// Returns the output from running the provided slash command.
172    fn run_slash_command(
173        &self,
174        _command: SlashCommand,
175        _args: Vec<String>,
176        _worktree: Option<&Worktree>,
177    ) -> Result<SlashCommandOutput, String> {
178        Err("`run_slash_command` not implemented".to_string())
179    }
180
181    /// Returns the command used to start a context server.
182    fn context_server_command(
183        &mut self,
184        _context_server_id: &ContextServerId,
185        _project: &Project,
186    ) -> Result<Command> {
187        Err("`context_server_command` not implemented".to_string())
188    }
189
190    /// Returns the configuration options for the specified context server.
191    fn context_server_configuration(
192        &mut self,
193        _context_server_id: &ContextServerId,
194        _project: &Project,
195    ) -> Result<Option<ContextServerConfiguration>> {
196        Ok(None)
197    }
198
199    /// Returns a list of package names as suggestions to be included in the
200    /// search results of the `/docs` slash command.
201    ///
202    /// This can be used to provide completions for known packages (e.g., from the
203    /// local project or a registry) before a package has been indexed.
204    fn suggest_docs_packages(&self, _provider: String) -> Result<Vec<String>, String> {
205        Ok(Vec::new())
206    }
207
208    /// Indexes the docs for the specified package.
209    fn index_docs(
210        &self,
211        _provider: String,
212        _package: String,
213        _database: &KeyValueStore,
214    ) -> Result<(), String> {
215        Err("`index_docs` not implemented".to_string())
216    }
217
218    /// Returns the debug adapter binary for the specified adapter name and configuration.
219    fn get_dap_binary(
220        &mut self,
221        _adapter_name: String,
222        _config: DebugTaskDefinition,
223        _user_provided_debug_adapter_path: Option<String>,
224        _worktree: &Worktree,
225    ) -> Result<DebugAdapterBinary, String> {
226        Err("`get_dap_binary` not implemented".to_string())
227    }
228
229    /// Determines whether the specified adapter configuration should *launch* a new debuggee process
230    /// or *attach* to an existing one. This function should not perform any further validation (outside of determining the kind of a request).
231    /// This function should return an error when the kind cannot be determined (rather than fall back to a known default).
232    fn dap_request_kind(
233        &mut self,
234        _adapter_name: String,
235        _config: serde_json::Value,
236    ) -> Result<StartDebuggingRequestArgumentsRequest, String> {
237        Err("`dap_request_kind` not implemented".to_string())
238    }
239    /// Converts a high-level definition of a debug scenario (originating in a new session UI) to a "low-level" configuration suitable for a particular adapter.
240    ///
241    /// In layman's terms: given a program, list of arguments, current working directory and environment variables,
242    /// create a configuration that can be used to start a debug session.
243    fn dap_config_to_scenario(&mut self, _config: DebugConfig) -> Result<DebugScenario, String> {
244        Err("`dap_config_to_scenario` not implemented".to_string())
245    }
246
247    /// Locators are entities that convert a Zed task into a debug scenario.
248    ///
249    /// They can be provided even by extensions that don't provide a debug adapter.
250    /// For all tasks applicable to a given buffer, Zed will query all locators to find one that can turn the task into a debug scenario.
251    /// A converted debug scenario can include a build task (it shouldn't contain any configuration in such case); a build task result will later
252    /// be resolved with [`Extension::run_dap_locator`].
253    ///
254    /// To work through a real-world example, take a `cargo run` task and a hypothetical `cargo` locator:
255    /// 1. We may need to modify the task; in this case, it is problematic that `cargo run` spawns a binary. We should turn `cargo run` into a debug scenario with
256    ///    `cargo build` task. This is the decision we make at `dap_locator_create_scenario` scope.
257    /// 2. Then, after the build task finishes, we will run `run_dap_locator` of the locator that produced the build task to find the program to be debugged. This function
258    ///    should give us a debugger-agnostic configuration for launching a debug target (that we end up resolving with [`Extension::dap_config_to_scenario`]). It's almost as if the user
259    ///    found the artifact path by themselves.
260    ///
261    /// Note that you're not obliged to use build tasks with locators. Specifically, it is sufficient to provide a debug configuration directly in the return value of
262    /// `dap_locator_create_scenario` if you're able to do that. Make sure to not fill out `build` field in that case, as that will prevent Zed from running second phase of resolution in such case.
263    /// This might be of particular relevance to interpreted languages.
264    fn dap_locator_create_scenario(
265        &mut self,
266        _locator_name: String,
267        _build_task: TaskTemplate,
268        _resolved_label: String,
269        _debug_adapter_name: String,
270    ) -> Option<DebugScenario> {
271        None
272    }
273
274    /// Runs the second phase of locator resolution.
275    /// See [`Extension::dap_locator_create_scenario`] for a hefty comment on locators.
276    fn run_dap_locator(
277        &mut self,
278        _locator_name: String,
279        _build_task: TaskTemplate,
280    ) -> Result<DebugRequest, String> {
281        Err("`run_dap_locator` not implemented".to_string())
282    }
283
284    /// Returns information about language model providers offered by this extension.
285    fn llm_providers(&self) -> Vec<LlmProviderInfo> {
286        Vec::new()
287    }
288
289    /// Returns the models available for a provider.
290    fn llm_provider_models(&self, _provider_id: &str) -> Result<Vec<LlmModelInfo>, String> {
291        Ok(Vec::new())
292    }
293
294    /// Returns markdown content to display in the provider's settings UI.
295    /// This can include setup instructions, links to documentation, etc.
296    fn llm_provider_settings_markdown(&self, _provider_id: &str) -> Option<String> {
297        None
298    }
299
300    /// Check if the provider is authenticated.
301    fn llm_provider_is_authenticated(&self, _provider_id: &str) -> bool {
302        false
303    }
304
305    /// Start an OAuth device flow sign-in.
306    /// This is called when the user explicitly clicks "Sign in with GitHub" or similar.
307    /// Returns information needed to display the device flow prompt modal to the user.
308    fn llm_provider_start_device_flow_sign_in(
309        &mut self,
310        _provider_id: &str,
311    ) -> Result<LlmDeviceFlowPromptInfo, String> {
312        Err("`llm_provider_start_device_flow_sign_in` not implemented".to_string())
313    }
314
315    /// Poll for device flow sign-in completion.
316    /// This is called after llm_provider_start_device_flow_sign_in returns the user code.
317    /// The extension should poll the OAuth provider until the user authorizes or the flow times out.
318    fn llm_provider_poll_device_flow_sign_in(&mut self, _provider_id: &str) -> Result<(), String> {
319        Err("`llm_provider_poll_device_flow_sign_in` not implemented".to_string())
320    }
321
322    /// Reset credentials for the provider.
323    fn llm_provider_reset_credentials(&mut self, _provider_id: &str) -> Result<(), String> {
324        Err("`llm_provider_reset_credentials` not implemented".to_string())
325    }
326
327    /// Count tokens for a request.
328    fn llm_count_tokens(
329        &self,
330        _provider_id: &str,
331        _model_id: &str,
332        _request: &LlmCompletionRequest,
333    ) -> Result<u64, String> {
334        Err("`llm_count_tokens` not implemented".to_string())
335    }
336
337    /// Start streaming a completion from the model.
338    /// Returns a stream ID that can be used with `llm_stream_completion_next` and `llm_stream_completion_close`.
339    fn llm_stream_completion_start(
340        &mut self,
341        _provider_id: &str,
342        _model_id: &str,
343        _request: &LlmCompletionRequest,
344    ) -> Result<String, String> {
345        Err("`llm_stream_completion_start` not implemented".to_string())
346    }
347
348    /// Get the next event from a completion stream.
349    /// Returns `Ok(None)` when the stream is complete.
350    fn llm_stream_completion_next(
351        &mut self,
352        _stream_id: &str,
353    ) -> Result<Option<LlmCompletionEvent>, String> {
354        Err("`llm_stream_completion_next` not implemented".to_string())
355    }
356
357    /// Close a completion stream and release its resources.
358    fn llm_stream_completion_close(&mut self, _stream_id: &str) {
359        // Default implementation does nothing
360    }
361
362    /// Get cache configuration for a model (if prompt caching is supported).
363    fn llm_cache_configuration(
364        &self,
365        _provider_id: &str,
366        _model_id: &str,
367    ) -> Option<LlmCacheConfiguration> {
368        None
369    }
370}
371
372/// Registers the provided type as a Zed extension.
373///
374/// The type must implement the [`Extension`] trait.
375#[macro_export]
376macro_rules! register_extension {
377    ($extension_type:ty) => {
378        #[cfg(target_os = "wasi")]
379        mod wasi_ext {
380            unsafe extern "C" {
381                static mut errno: i32;
382                pub static mut __wasilibc_cwd: *mut std::ffi::c_char;
383            }
384
385            pub fn init_cwd() {
386                unsafe {
387                    // Ensure that our chdir function is linked, instead of the
388                    // one from wasi-libc in the chdir.o translation unit. Otherwise
389                    // we risk linking in `__wasilibc_find_relpath_alloc` which
390                    // is a weak symbol and is being used by
391                    // `__wasilibc_find_relpath`, which we do not want on
392                    // Windows.
393                    chdir(std::ptr::null());
394
395                    __wasilibc_cwd = std::ffi::CString::new(std::env::var("PWD").unwrap())
396                        .unwrap()
397                        .into_raw()
398                        .cast();
399                }
400            }
401
402            #[unsafe(no_mangle)]
403            pub unsafe extern "C" fn chdir(raw_path: *const std::ffi::c_char) -> i32 {
404                // Forbid extensions from changing CWD and so return an appropriate error code.
405                errno = 58; // NOTSUP
406                return -1;
407            }
408        }
409
410        #[unsafe(export_name = "init-extension")]
411        pub extern "C" fn __init_extension() {
412            #[cfg(target_os = "wasi")]
413            wasi_ext::init_cwd();
414
415            zed_extension_api::register_extension(|| {
416                Box::new(<$extension_type as zed_extension_api::Extension>::new())
417            });
418        }
419    };
420}
421
422#[doc(hidden)]
423pub fn register_extension(build_extension: fn() -> Box<dyn Extension>) {
424    unsafe { EXTENSION = Some((build_extension)()) }
425}
426
427fn extension() -> &'static mut dyn Extension {
428    #[expect(static_mut_refs)]
429    unsafe {
430        EXTENSION.as_deref_mut().unwrap()
431    }
432}
433
434static mut EXTENSION: Option<Box<dyn Extension>> = None;
435
436#[cfg(target_arch = "wasm32")]
437#[unsafe(link_section = "zed:api-version")]
438#[doc(hidden)]
439pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
440
441mod wit {
442
443    wit_bindgen::generate!({
444        skip: ["init-extension"],
445        path: "./wit/since_v0.8.0",
446    });
447}
448
449wit::export!(Component);
450
451struct Component;
452
453impl wit::Guest for Component {
454    fn language_server_command(
455        language_server_id: String,
456        worktree: &wit::Worktree,
457    ) -> Result<wit::Command> {
458        let language_server_id = LanguageServerId(language_server_id);
459        extension().language_server_command(&language_server_id, worktree)
460    }
461
462    fn language_server_initialization_options(
463        language_server_id: String,
464        worktree: &Worktree,
465    ) -> Result<Option<String>, String> {
466        let language_server_id = LanguageServerId(language_server_id);
467        Ok(extension()
468            .language_server_initialization_options(&language_server_id, worktree)?
469            .and_then(|value| serde_json::to_string(&value).ok()))
470    }
471
472    fn language_server_workspace_configuration(
473        language_server_id: String,
474        worktree: &Worktree,
475    ) -> Result<Option<String>, String> {
476        let language_server_id = LanguageServerId(language_server_id);
477        Ok(extension()
478            .language_server_workspace_configuration(&language_server_id, worktree)?
479            .and_then(|value| serde_json::to_string(&value).ok()))
480    }
481
482    fn language_server_additional_initialization_options(
483        language_server_id: String,
484        target_language_server_id: String,
485        worktree: &Worktree,
486    ) -> Result<Option<String>, String> {
487        let language_server_id = LanguageServerId(language_server_id);
488        let target_language_server_id = LanguageServerId(target_language_server_id);
489        Ok(extension()
490            .language_server_additional_initialization_options(
491                &language_server_id,
492                &target_language_server_id,
493                worktree,
494            )?
495            .and_then(|value| serde_json::to_string(&value).ok()))
496    }
497
498    fn language_server_additional_workspace_configuration(
499        language_server_id: String,
500        target_language_server_id: String,
501        worktree: &Worktree,
502    ) -> Result<Option<String>, String> {
503        let language_server_id = LanguageServerId(language_server_id);
504        let target_language_server_id = LanguageServerId(target_language_server_id);
505        Ok(extension()
506            .language_server_additional_workspace_configuration(
507                &language_server_id,
508                &target_language_server_id,
509                worktree,
510            )?
511            .and_then(|value| serde_json::to_string(&value).ok()))
512    }
513
514    fn labels_for_completions(
515        language_server_id: String,
516        completions: Vec<Completion>,
517    ) -> Result<Vec<Option<CodeLabel>>, String> {
518        let language_server_id = LanguageServerId(language_server_id);
519        let mut labels = Vec::new();
520        for (ix, completion) in completions.into_iter().enumerate() {
521            let label = extension().label_for_completion(&language_server_id, completion);
522            if let Some(label) = label {
523                labels.resize(ix + 1, None);
524                *labels.last_mut().unwrap() = Some(label);
525            }
526        }
527        Ok(labels)
528    }
529
530    fn labels_for_symbols(
531        language_server_id: String,
532        symbols: Vec<Symbol>,
533    ) -> Result<Vec<Option<CodeLabel>>, String> {
534        let language_server_id = LanguageServerId(language_server_id);
535        let mut labels = Vec::new();
536        for (ix, symbol) in symbols.into_iter().enumerate() {
537            let label = extension().label_for_symbol(&language_server_id, symbol);
538            if let Some(label) = label {
539                labels.resize(ix + 1, None);
540                *labels.last_mut().unwrap() = Some(label);
541            }
542        }
543        Ok(labels)
544    }
545
546    fn complete_slash_command_argument(
547        command: SlashCommand,
548        args: Vec<String>,
549    ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
550        extension().complete_slash_command_argument(command, args)
551    }
552
553    fn run_slash_command(
554        command: SlashCommand,
555        args: Vec<String>,
556        worktree: Option<&Worktree>,
557    ) -> Result<SlashCommandOutput, String> {
558        extension().run_slash_command(command, args, worktree)
559    }
560
561    fn context_server_command(
562        context_server_id: String,
563        project: &Project,
564    ) -> Result<wit::Command> {
565        let context_server_id = ContextServerId(context_server_id);
566        extension().context_server_command(&context_server_id, project)
567    }
568
569    fn context_server_configuration(
570        context_server_id: String,
571        project: &Project,
572    ) -> Result<Option<ContextServerConfiguration>, String> {
573        let context_server_id = ContextServerId(context_server_id);
574        extension().context_server_configuration(&context_server_id, project)
575    }
576
577    fn suggest_docs_packages(provider: String) -> Result<Vec<String>, String> {
578        extension().suggest_docs_packages(provider)
579    }
580
581    fn index_docs(
582        provider: String,
583        package: String,
584        database: &KeyValueStore,
585    ) -> Result<(), String> {
586        extension().index_docs(provider, package, database)
587    }
588
589    fn get_dap_binary(
590        adapter_name: String,
591        config: DebugTaskDefinition,
592        user_installed_path: Option<String>,
593        worktree: &Worktree,
594    ) -> Result<wit::DebugAdapterBinary, String> {
595        extension().get_dap_binary(adapter_name, config, user_installed_path, worktree)
596    }
597
598    fn dap_request_kind(
599        adapter_name: String,
600        config: String,
601    ) -> Result<StartDebuggingRequestArgumentsRequest, String> {
602        extension().dap_request_kind(
603            adapter_name,
604            serde_json::from_str(&config).map_err(|e| format!("Failed to parse config: {e}"))?,
605        )
606    }
607    fn dap_config_to_scenario(config: DebugConfig) -> Result<DebugScenario, String> {
608        extension().dap_config_to_scenario(config)
609    }
610    fn dap_locator_create_scenario(
611        locator_name: String,
612        build_task: TaskTemplate,
613        resolved_label: String,
614        debug_adapter_name: String,
615    ) -> Option<DebugScenario> {
616        extension().dap_locator_create_scenario(
617            locator_name,
618            build_task,
619            resolved_label,
620            debug_adapter_name,
621        )
622    }
623    fn run_dap_locator(
624        locator_name: String,
625        build_task: TaskTemplate,
626    ) -> Result<DebugRequest, String> {
627        extension().run_dap_locator(locator_name, build_task)
628    }
629
630    fn llm_providers() -> Vec<LlmProviderInfo> {
631        extension().llm_providers()
632    }
633
634    fn llm_provider_models(provider_id: String) -> Result<Vec<LlmModelInfo>, String> {
635        extension().llm_provider_models(&provider_id)
636    }
637
638    fn llm_provider_settings_markdown(provider_id: String) -> Option<String> {
639        extension().llm_provider_settings_markdown(&provider_id)
640    }
641
642    fn llm_provider_is_authenticated(provider_id: String) -> bool {
643        extension().llm_provider_is_authenticated(&provider_id)
644    }
645
646    fn llm_provider_start_device_flow_sign_in(
647        provider_id: String,
648    ) -> Result<LlmDeviceFlowPromptInfo, String> {
649        extension().llm_provider_start_device_flow_sign_in(&provider_id)
650    }
651
652    fn llm_provider_poll_device_flow_sign_in(provider_id: String) -> Result<(), String> {
653        extension().llm_provider_poll_device_flow_sign_in(&provider_id)
654    }
655
656    fn llm_provider_reset_credentials(provider_id: String) -> Result<(), String> {
657        extension().llm_provider_reset_credentials(&provider_id)
658    }
659
660    fn llm_count_tokens(
661        provider_id: String,
662        model_id: String,
663        request: LlmCompletionRequest,
664    ) -> Result<u64, String> {
665        extension().llm_count_tokens(&provider_id, &model_id, &request)
666    }
667
668    fn llm_stream_completion_start(
669        provider_id: String,
670        model_id: String,
671        request: LlmCompletionRequest,
672    ) -> Result<String, String> {
673        extension().llm_stream_completion_start(&provider_id, &model_id, &request)
674    }
675
676    fn llm_stream_completion_next(stream_id: String) -> Result<Option<LlmCompletionEvent>, String> {
677        extension().llm_stream_completion_next(&stream_id)
678    }
679
680    fn llm_stream_completion_close(stream_id: String) {
681        extension().llm_stream_completion_close(&stream_id)
682    }
683
684    fn llm_cache_configuration(
685        provider_id: String,
686        model_id: String,
687    ) -> Option<LlmCacheConfiguration> {
688        extension().llm_cache_configuration(&provider_id, &model_id)
689    }
690}
691
692/// The ID of a language server.
693#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
694pub struct LanguageServerId(String);
695
696impl AsRef<str> for LanguageServerId {
697    fn as_ref(&self) -> &str {
698        &self.0
699    }
700}
701
702impl fmt::Display for LanguageServerId {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        write!(f, "{}", self.0)
705    }
706}
707
708/// The ID of a context server.
709#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
710pub struct ContextServerId(String);
711
712impl AsRef<str> for ContextServerId {
713    fn as_ref(&self) -> &str {
714        &self.0
715    }
716}
717
718impl fmt::Display for ContextServerId {
719    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720        write!(f, "{}", self.0)
721    }
722}
723
724impl CodeLabelSpan {
725    /// Returns a [`CodeLabelSpan::CodeRange`].
726    pub fn code_range(range: impl Into<wit::Range>) -> Self {
727        Self::CodeRange(range.into())
728    }
729
730    /// Returns a [`CodeLabelSpan::Literal`].
731    pub fn literal(text: impl Into<String>, highlight_name: Option<String>) -> Self {
732        Self::Literal(CodeLabelSpanLiteral {
733            text: text.into(),
734            highlight_name,
735        })
736    }
737}
738
739impl From<std::ops::Range<u32>> for wit::Range {
740    fn from(value: std::ops::Range<u32>) -> Self {
741        Self {
742            start: value.start,
743            end: value.end,
744        }
745    }
746}
747
748impl From<std::ops::Range<usize>> for wit::Range {
749    fn from(value: std::ops::Range<usize>) -> Self {
750        Self {
751            start: value.start as u32,
752            end: value.end as u32,
753        }
754    }
755}