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, CredentialType as LlmCredentialType,
 35        ImageData as LlmImageData, MessageContent as LlmMessageContent,
 36        MessageRole as LlmMessageRole, ModelCapabilities as LlmModelCapabilities,
 37        ModelInfo as LlmModelInfo, OauthHttpRequest as LlmOauthHttpRequest,
 38        OauthHttpResponse as LlmOauthHttpResponse, OauthWebAuthConfig as LlmOauthWebAuthConfig,
 39        OauthWebAuthResult as LlmOauthWebAuthResult, ProviderInfo as LlmProviderInfo,
 40        RequestMessage as LlmRequestMessage, StopReason as LlmStopReason,
 41        ThinkingContent as LlmThinkingContent, TokenUsage as LlmTokenUsage,
 42        ToolChoice as LlmToolChoice, ToolDefinition as LlmToolDefinition,
 43        ToolInputFormat as LlmToolInputFormat, ToolResult as LlmToolResult,
 44        ToolResultContent as LlmToolResultContent, ToolUse as LlmToolUse,
 45        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, oauth_open_browser as llm_oauth_open_browser,
 48        oauth_start_web_auth as llm_oauth_start_web_auth,
 49        request_credential as llm_request_credential,
 50        send_oauth_http_request as llm_oauth_http_request,
 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    /// Opens the browser to the verification URL and returns the user code that should
308    /// be displayed to the user.
309    fn llm_provider_start_device_flow_sign_in(
310        &mut self,
311        _provider_id: &str,
312    ) -> Result<String, String> {
313        Err("`llm_provider_start_device_flow_sign_in` not implemented".to_string())
314    }
315
316    /// Poll for device flow sign-in completion.
317    /// This is called after llm_provider_start_device_flow_sign_in returns the user code.
318    /// The extension should poll the OAuth provider until the user authorizes or the flow times out.
319    fn llm_provider_poll_device_flow_sign_in(&mut self, _provider_id: &str) -> Result<(), String> {
320        Err("`llm_provider_poll_device_flow_sign_in` not implemented".to_string())
321    }
322
323    /// Reset credentials for the provider.
324    fn llm_provider_reset_credentials(&mut self, _provider_id: &str) -> Result<(), String> {
325        Err("`llm_provider_reset_credentials` not implemented".to_string())
326    }
327
328    /// Count tokens for a request.
329    fn llm_count_tokens(
330        &self,
331        _provider_id: &str,
332        _model_id: &str,
333        _request: &LlmCompletionRequest,
334    ) -> Result<u64, String> {
335        Err("`llm_count_tokens` not implemented".to_string())
336    }
337
338    /// Start streaming a completion from the model.
339    /// Returns a stream ID that can be used with `llm_stream_completion_next` and `llm_stream_completion_close`.
340    fn llm_stream_completion_start(
341        &mut self,
342        _provider_id: &str,
343        _model_id: &str,
344        _request: &LlmCompletionRequest,
345    ) -> Result<String, String> {
346        Err("`llm_stream_completion_start` not implemented".to_string())
347    }
348
349    /// Get the next event from a completion stream.
350    /// Returns `Ok(None)` when the stream is complete.
351    fn llm_stream_completion_next(
352        &mut self,
353        _stream_id: &str,
354    ) -> Result<Option<LlmCompletionEvent>, String> {
355        Err("`llm_stream_completion_next` not implemented".to_string())
356    }
357
358    /// Close a completion stream and release its resources.
359    fn llm_stream_completion_close(&mut self, _stream_id: &str) {
360        // Default implementation does nothing
361    }
362
363    /// Get cache configuration for a model (if prompt caching is supported).
364    fn llm_cache_configuration(
365        &self,
366        _provider_id: &str,
367        _model_id: &str,
368    ) -> Option<LlmCacheConfiguration> {
369        None
370    }
371}
372
373/// Registers the provided type as a Zed extension.
374///
375/// The type must implement the [`Extension`] trait.
376#[macro_export]
377macro_rules! register_extension {
378    ($extension_type:ty) => {
379        #[cfg(target_os = "wasi")]
380        mod wasi_ext {
381            unsafe extern "C" {
382                static mut errno: i32;
383                pub static mut __wasilibc_cwd: *mut std::ffi::c_char;
384            }
385
386            pub fn init_cwd() {
387                unsafe {
388                    // Ensure that our chdir function is linked, instead of the
389                    // one from wasi-libc in the chdir.o translation unit. Otherwise
390                    // we risk linking in `__wasilibc_find_relpath_alloc` which
391                    // is a weak symbol and is being used by
392                    // `__wasilibc_find_relpath`, which we do not want on
393                    // Windows.
394                    chdir(std::ptr::null());
395
396                    __wasilibc_cwd = std::ffi::CString::new(std::env::var("PWD").unwrap())
397                        .unwrap()
398                        .into_raw()
399                        .cast();
400                }
401            }
402
403            #[unsafe(no_mangle)]
404            pub unsafe extern "C" fn chdir(raw_path: *const std::ffi::c_char) -> i32 {
405                // Forbid extensions from changing CWD and so return an appropriate error code.
406                errno = 58; // NOTSUP
407                return -1;
408            }
409        }
410
411        #[unsafe(export_name = "init-extension")]
412        pub extern "C" fn __init_extension() {
413            #[cfg(target_os = "wasi")]
414            wasi_ext::init_cwd();
415
416            zed_extension_api::register_extension(|| {
417                Box::new(<$extension_type as zed_extension_api::Extension>::new())
418            });
419        }
420    };
421}
422
423#[doc(hidden)]
424pub fn register_extension(build_extension: fn() -> Box<dyn Extension>) {
425    unsafe { EXTENSION = Some((build_extension)()) }
426}
427
428fn extension() -> &'static mut dyn Extension {
429    #[expect(static_mut_refs)]
430    unsafe {
431        EXTENSION.as_deref_mut().unwrap()
432    }
433}
434
435static mut EXTENSION: Option<Box<dyn Extension>> = None;
436
437#[cfg(target_arch = "wasm32")]
438#[unsafe(link_section = "zed:api-version")]
439#[doc(hidden)]
440pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
441
442mod wit {
443
444    wit_bindgen::generate!({
445        skip: ["init-extension"],
446        path: "./wit/since_v0.8.0",
447    });
448}
449
450wit::export!(Component);
451
452struct Component;
453
454impl wit::Guest for Component {
455    fn language_server_command(
456        language_server_id: String,
457        worktree: &wit::Worktree,
458    ) -> Result<wit::Command> {
459        let language_server_id = LanguageServerId(language_server_id);
460        extension().language_server_command(&language_server_id, worktree)
461    }
462
463    fn language_server_initialization_options(
464        language_server_id: String,
465        worktree: &Worktree,
466    ) -> Result<Option<String>, String> {
467        let language_server_id = LanguageServerId(language_server_id);
468        Ok(extension()
469            .language_server_initialization_options(&language_server_id, worktree)?
470            .and_then(|value| serde_json::to_string(&value).ok()))
471    }
472
473    fn language_server_workspace_configuration(
474        language_server_id: String,
475        worktree: &Worktree,
476    ) -> Result<Option<String>, String> {
477        let language_server_id = LanguageServerId(language_server_id);
478        Ok(extension()
479            .language_server_workspace_configuration(&language_server_id, worktree)?
480            .and_then(|value| serde_json::to_string(&value).ok()))
481    }
482
483    fn language_server_additional_initialization_options(
484        language_server_id: String,
485        target_language_server_id: String,
486        worktree: &Worktree,
487    ) -> Result<Option<String>, String> {
488        let language_server_id = LanguageServerId(language_server_id);
489        let target_language_server_id = LanguageServerId(target_language_server_id);
490        Ok(extension()
491            .language_server_additional_initialization_options(
492                &language_server_id,
493                &target_language_server_id,
494                worktree,
495            )?
496            .and_then(|value| serde_json::to_string(&value).ok()))
497    }
498
499    fn language_server_additional_workspace_configuration(
500        language_server_id: String,
501        target_language_server_id: String,
502        worktree: &Worktree,
503    ) -> Result<Option<String>, String> {
504        let language_server_id = LanguageServerId(language_server_id);
505        let target_language_server_id = LanguageServerId(target_language_server_id);
506        Ok(extension()
507            .language_server_additional_workspace_configuration(
508                &language_server_id,
509                &target_language_server_id,
510                worktree,
511            )?
512            .and_then(|value| serde_json::to_string(&value).ok()))
513    }
514
515    fn labels_for_completions(
516        language_server_id: String,
517        completions: Vec<Completion>,
518    ) -> Result<Vec<Option<CodeLabel>>, String> {
519        let language_server_id = LanguageServerId(language_server_id);
520        let mut labels = Vec::new();
521        for (ix, completion) in completions.into_iter().enumerate() {
522            let label = extension().label_for_completion(&language_server_id, completion);
523            if let Some(label) = label {
524                labels.resize(ix + 1, None);
525                *labels.last_mut().unwrap() = Some(label);
526            }
527        }
528        Ok(labels)
529    }
530
531    fn labels_for_symbols(
532        language_server_id: String,
533        symbols: Vec<Symbol>,
534    ) -> Result<Vec<Option<CodeLabel>>, String> {
535        let language_server_id = LanguageServerId(language_server_id);
536        let mut labels = Vec::new();
537        for (ix, symbol) in symbols.into_iter().enumerate() {
538            let label = extension().label_for_symbol(&language_server_id, symbol);
539            if let Some(label) = label {
540                labels.resize(ix + 1, None);
541                *labels.last_mut().unwrap() = Some(label);
542            }
543        }
544        Ok(labels)
545    }
546
547    fn complete_slash_command_argument(
548        command: SlashCommand,
549        args: Vec<String>,
550    ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
551        extension().complete_slash_command_argument(command, args)
552    }
553
554    fn run_slash_command(
555        command: SlashCommand,
556        args: Vec<String>,
557        worktree: Option<&Worktree>,
558    ) -> Result<SlashCommandOutput, String> {
559        extension().run_slash_command(command, args, worktree)
560    }
561
562    fn context_server_command(
563        context_server_id: String,
564        project: &Project,
565    ) -> Result<wit::Command> {
566        let context_server_id = ContextServerId(context_server_id);
567        extension().context_server_command(&context_server_id, project)
568    }
569
570    fn context_server_configuration(
571        context_server_id: String,
572        project: &Project,
573    ) -> Result<Option<ContextServerConfiguration>, String> {
574        let context_server_id = ContextServerId(context_server_id);
575        extension().context_server_configuration(&context_server_id, project)
576    }
577
578    fn suggest_docs_packages(provider: String) -> Result<Vec<String>, String> {
579        extension().suggest_docs_packages(provider)
580    }
581
582    fn index_docs(
583        provider: String,
584        package: String,
585        database: &KeyValueStore,
586    ) -> Result<(), String> {
587        extension().index_docs(provider, package, database)
588    }
589
590    fn get_dap_binary(
591        adapter_name: String,
592        config: DebugTaskDefinition,
593        user_installed_path: Option<String>,
594        worktree: &Worktree,
595    ) -> Result<wit::DebugAdapterBinary, String> {
596        extension().get_dap_binary(adapter_name, config, user_installed_path, worktree)
597    }
598
599    fn dap_request_kind(
600        adapter_name: String,
601        config: String,
602    ) -> Result<StartDebuggingRequestArgumentsRequest, String> {
603        extension().dap_request_kind(
604            adapter_name,
605            serde_json::from_str(&config).map_err(|e| format!("Failed to parse config: {e}"))?,
606        )
607    }
608    fn dap_config_to_scenario(config: DebugConfig) -> Result<DebugScenario, String> {
609        extension().dap_config_to_scenario(config)
610    }
611    fn dap_locator_create_scenario(
612        locator_name: String,
613        build_task: TaskTemplate,
614        resolved_label: String,
615        debug_adapter_name: String,
616    ) -> Option<DebugScenario> {
617        extension().dap_locator_create_scenario(
618            locator_name,
619            build_task,
620            resolved_label,
621            debug_adapter_name,
622        )
623    }
624    fn run_dap_locator(
625        locator_name: String,
626        build_task: TaskTemplate,
627    ) -> Result<DebugRequest, String> {
628        extension().run_dap_locator(locator_name, build_task)
629    }
630
631    fn llm_providers() -> Vec<LlmProviderInfo> {
632        extension().llm_providers()
633    }
634
635    fn llm_provider_models(provider_id: String) -> Result<Vec<LlmModelInfo>, String> {
636        extension().llm_provider_models(&provider_id)
637    }
638
639    fn llm_provider_settings_markdown(provider_id: String) -> Option<String> {
640        extension().llm_provider_settings_markdown(&provider_id)
641    }
642
643    fn llm_provider_is_authenticated(provider_id: String) -> bool {
644        extension().llm_provider_is_authenticated(&provider_id)
645    }
646
647    fn llm_provider_start_device_flow_sign_in(provider_id: String) -> Result<String, String> {
648        extension().llm_provider_start_device_flow_sign_in(&provider_id)
649    }
650
651    fn llm_provider_poll_device_flow_sign_in(provider_id: String) -> Result<(), String> {
652        extension().llm_provider_poll_device_flow_sign_in(&provider_id)
653    }
654
655    fn llm_provider_reset_credentials(provider_id: String) -> Result<(), String> {
656        extension().llm_provider_reset_credentials(&provider_id)
657    }
658
659    fn llm_count_tokens(
660        provider_id: String,
661        model_id: String,
662        request: LlmCompletionRequest,
663    ) -> Result<u64, String> {
664        extension().llm_count_tokens(&provider_id, &model_id, &request)
665    }
666
667    fn llm_stream_completion_start(
668        provider_id: String,
669        model_id: String,
670        request: LlmCompletionRequest,
671    ) -> Result<String, String> {
672        extension().llm_stream_completion_start(&provider_id, &model_id, &request)
673    }
674
675    fn llm_stream_completion_next(stream_id: String) -> Result<Option<LlmCompletionEvent>, String> {
676        extension().llm_stream_completion_next(&stream_id)
677    }
678
679    fn llm_stream_completion_close(stream_id: String) {
680        extension().llm_stream_completion_close(&stream_id)
681    }
682
683    fn llm_cache_configuration(
684        provider_id: String,
685        model_id: String,
686    ) -> Option<LlmCacheConfiguration> {
687        extension().llm_cache_configuration(&provider_id, &model_id)
688    }
689}
690
691/// The ID of a language server.
692#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
693pub struct LanguageServerId(String);
694
695impl AsRef<str> for LanguageServerId {
696    fn as_ref(&self) -> &str {
697        &self.0
698    }
699}
700
701impl fmt::Display for LanguageServerId {
702    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
703        write!(f, "{}", self.0)
704    }
705}
706
707/// The ID of a context server.
708#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
709pub struct ContextServerId(String);
710
711impl AsRef<str> for ContextServerId {
712    fn as_ref(&self) -> &str {
713        &self.0
714    }
715}
716
717impl fmt::Display for ContextServerId {
718    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719        write!(f, "{}", self.0)
720    }
721}
722
723impl CodeLabelSpan {
724    /// Returns a [`CodeLabelSpan::CodeRange`].
725    pub fn code_range(range: impl Into<wit::Range>) -> Self {
726        Self::CodeRange(range.into())
727    }
728
729    /// Returns a [`CodeLabelSpan::Literal`].
730    pub fn literal(text: impl Into<String>, highlight_name: Option<String>) -> Self {
731        Self::Literal(CodeLabelSpanLiteral {
732            text: text.into(),
733            highlight_name,
734        })
735    }
736}
737
738impl From<std::ops::Range<u32>> for wit::Range {
739    fn from(value: std::ops::Range<u32>) -> Self {
740        Self {
741            start: value.start,
742            end: value.end,
743        }
744    }
745}
746
747impl From<std::ops::Range<usize>> for wit::Range {
748    fn from(value: std::ops::Range<usize>) -> Self {
749        Self {
750            start: value.start as u32,
751            end: value.end as u32,
752        }
753    }
754}