1use crate::wasm_host::wit::since_v0_8_0::{
2 dap::{
3 AttachRequest, BuildTaskDefinition, BuildTaskDefinitionTemplatePayload, LaunchRequest,
4 StartDebuggingRequestArguments, TcpArguments, TcpArgumentsTemplate,
5 },
6 lsp::{CompletionKind, CompletionLabelDetails, InsertTextFormat, SymbolKind},
7 slash_command::SlashCommandOutputSection,
8};
9use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
10use ::http_client::{AsyncBody, HttpRequestExt};
11use ::settings::{Settings, WorktreeId};
12use anyhow::{Context as _, Result, bail};
13use async_compression::futures::bufread::GzipDecoder;
14use async_tar::Archive;
15use async_trait::async_trait;
16use credentials_provider::CredentialsProvider;
17use extension::{
18 ExtensionLanguageServerProxy, KeyValueStoreDelegate, ProjectDelegate, WorktreeDelegate,
19};
20use futures::{AsyncReadExt, lock::Mutex};
21use futures::{FutureExt as _, io::BufReader};
22use gpui::{BackgroundExecutor, SharedString};
23use language::{BinaryStatus, LanguageName, language_settings::AllLanguageSettings};
24use project::project_settings::ProjectSettings;
25use semver::Version;
26use smol::net::TcpListener;
27use std::{
28 env,
29 net::Ipv4Addr,
30 path::{Path, PathBuf},
31 str::FromStr,
32 sync::{Arc, OnceLock},
33 time::Duration,
34};
35use task::{SpawnInTerminal, ZedDebugConfig};
36use url::Url;
37use util::{
38 archive::extract_zip, fs::make_file_executable, maybe, paths::PathStyle, rel_path::RelPath,
39};
40use wasmtime::component::{Linker, Resource};
41
42pub const MIN_VERSION: Version = Version::new(0, 8, 0);
43pub const MAX_VERSION: Version = Version::new(0, 8, 0);
44
45wasmtime::component::bindgen!({
46 async: true,
47 trappable_imports: true,
48 path: "../extension_api/wit/since_v0.8.0",
49 with: {
50 "worktree": ExtensionWorktree,
51 "project": ExtensionProject,
52 "key-value-store": ExtensionKeyValueStore,
53 "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
54 },
55});
56
57pub use self::zed::extension::*;
58
59mod settings {
60 #![allow(dead_code)]
61 include!(concat!(env!("OUT_DIR"), "/since_v0.8.0/settings.rs"));
62}
63
64pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
65pub type ExtensionProject = Arc<dyn ProjectDelegate>;
66pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
67pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
68
69pub fn linker(executor: &BackgroundExecutor) -> &'static Linker<WasmState> {
70 static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
71 LINKER.get_or_init(|| super::new_linker(executor, Extension::add_to_linker))
72}
73
74impl From<Range> for std::ops::Range<usize> {
75 fn from(range: Range) -> Self {
76 let start = range.start as usize;
77 let end = range.end as usize;
78 start..end
79 }
80}
81
82impl From<Command> for extension::Command {
83 fn from(value: Command) -> Self {
84 Self {
85 command: value.command.into(),
86 args: value.args,
87 env: value.env,
88 }
89 }
90}
91
92impl From<StartDebuggingRequestArgumentsRequest>
93 for extension::StartDebuggingRequestArgumentsRequest
94{
95 fn from(value: StartDebuggingRequestArgumentsRequest) -> Self {
96 match value {
97 StartDebuggingRequestArgumentsRequest::Launch => Self::Launch,
98 StartDebuggingRequestArgumentsRequest::Attach => Self::Attach,
99 }
100 }
101}
102impl TryFrom<StartDebuggingRequestArguments> for extension::StartDebuggingRequestArguments {
103 type Error = anyhow::Error;
104
105 fn try_from(value: StartDebuggingRequestArguments) -> Result<Self, Self::Error> {
106 Ok(Self {
107 configuration: serde_json::from_str(&value.configuration)?,
108 request: value.request.into(),
109 })
110 }
111}
112impl From<TcpArguments> for extension::TcpArguments {
113 fn from(value: TcpArguments) -> Self {
114 Self {
115 host: value.host.into(),
116 port: value.port,
117 timeout: value.timeout,
118 }
119 }
120}
121
122impl From<extension::TcpArgumentsTemplate> for TcpArgumentsTemplate {
123 fn from(value: extension::TcpArgumentsTemplate) -> Self {
124 Self {
125 host: value.host.map(Ipv4Addr::to_bits),
126 port: value.port,
127 timeout: value.timeout,
128 }
129 }
130}
131
132impl From<TcpArgumentsTemplate> for extension::TcpArgumentsTemplate {
133 fn from(value: TcpArgumentsTemplate) -> Self {
134 Self {
135 host: value.host.map(Ipv4Addr::from_bits),
136 port: value.port,
137 timeout: value.timeout,
138 }
139 }
140}
141
142impl TryFrom<extension::DebugTaskDefinition> for DebugTaskDefinition {
143 type Error = anyhow::Error;
144 fn try_from(value: extension::DebugTaskDefinition) -> Result<Self, Self::Error> {
145 Ok(Self {
146 label: value.label.to_string(),
147 adapter: value.adapter.to_string(),
148 config: value.config.to_string(),
149 tcp_connection: value.tcp_connection.map(Into::into),
150 })
151 }
152}
153
154impl From<task::DebugRequest> for DebugRequest {
155 fn from(value: task::DebugRequest) -> Self {
156 match value {
157 task::DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
158 task::DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
159 }
160 }
161}
162
163impl From<DebugRequest> for task::DebugRequest {
164 fn from(value: DebugRequest) -> Self {
165 match value {
166 DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
167 DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
168 }
169 }
170}
171
172impl From<task::LaunchRequest> for LaunchRequest {
173 fn from(value: task::LaunchRequest) -> Self {
174 Self {
175 program: value.program,
176 cwd: value.cwd.map(|p| p.to_string_lossy().into_owned()),
177 args: value.args,
178 envs: value.env.into_iter().collect(),
179 }
180 }
181}
182
183impl From<task::AttachRequest> for AttachRequest {
184 fn from(value: task::AttachRequest) -> Self {
185 Self {
186 process_id: value.process_id,
187 }
188 }
189}
190
191impl From<LaunchRequest> for task::LaunchRequest {
192 fn from(value: LaunchRequest) -> Self {
193 Self {
194 program: value.program,
195 cwd: value.cwd.map(|p| p.into()),
196 args: value.args,
197 env: value.envs.into_iter().collect(),
198 }
199 }
200}
201impl From<AttachRequest> for task::AttachRequest {
202 fn from(value: AttachRequest) -> Self {
203 Self {
204 process_id: value.process_id,
205 }
206 }
207}
208
209impl From<ZedDebugConfig> for DebugConfig {
210 fn from(value: ZedDebugConfig) -> Self {
211 Self {
212 label: value.label.into(),
213 adapter: value.adapter.into(),
214 request: value.request.into(),
215 stop_on_entry: value.stop_on_entry,
216 }
217 }
218}
219impl TryFrom<DebugAdapterBinary> for extension::DebugAdapterBinary {
220 type Error = anyhow::Error;
221 fn try_from(value: DebugAdapterBinary) -> Result<Self, Self::Error> {
222 Ok(Self {
223 command: value.command,
224 arguments: value.arguments,
225 envs: value.envs.into_iter().collect(),
226 cwd: value.cwd.map(|s| s.into()),
227 connection: value.connection.map(Into::into),
228 request_args: value.request_args.try_into()?,
229 })
230 }
231}
232
233impl From<BuildTaskDefinition> for extension::BuildTaskDefinition {
234 fn from(value: BuildTaskDefinition) -> Self {
235 match value {
236 BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
237 BuildTaskDefinition::Template(build_task_template) => Self::Template {
238 task_template: build_task_template.template.into(),
239 locator_name: build_task_template.locator_name.map(SharedString::from),
240 },
241 }
242 }
243}
244
245impl From<extension::BuildTaskDefinition> for BuildTaskDefinition {
246 fn from(value: extension::BuildTaskDefinition) -> Self {
247 match value {
248 extension::BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
249 extension::BuildTaskDefinition::Template {
250 task_template,
251 locator_name,
252 } => Self::Template(BuildTaskDefinitionTemplatePayload {
253 template: task_template.into(),
254 locator_name: locator_name.map(String::from),
255 }),
256 }
257 }
258}
259impl From<BuildTaskTemplate> for extension::BuildTaskTemplate {
260 fn from(value: BuildTaskTemplate) -> Self {
261 Self {
262 label: value.label,
263 command: value.command,
264 args: value.args,
265 env: value.env.into_iter().collect(),
266 cwd: value.cwd,
267 ..Default::default()
268 }
269 }
270}
271impl From<extension::BuildTaskTemplate> for BuildTaskTemplate {
272 fn from(value: extension::BuildTaskTemplate) -> Self {
273 Self {
274 label: value.label,
275 command: value.command,
276 args: value.args,
277 env: value.env.into_iter().collect(),
278 cwd: value.cwd,
279 }
280 }
281}
282
283impl TryFrom<DebugScenario> for extension::DebugScenario {
284 type Error = anyhow::Error;
285
286 fn try_from(value: DebugScenario) -> std::result::Result<Self, Self::Error> {
287 Ok(Self {
288 adapter: value.adapter.into(),
289 label: value.label.into(),
290 build: value.build.map(Into::into),
291 config: serde_json::Value::from_str(&value.config)?,
292 tcp_connection: value.tcp_connection.map(Into::into),
293 })
294 }
295}
296
297impl From<extension::DebugScenario> for DebugScenario {
298 fn from(value: extension::DebugScenario) -> Self {
299 Self {
300 adapter: value.adapter.into(),
301 label: value.label.into(),
302 build: value.build.map(Into::into),
303 config: value.config.to_string(),
304 tcp_connection: value.tcp_connection.map(Into::into),
305 }
306 }
307}
308
309impl TryFrom<SpawnInTerminal> for ResolvedTask {
310 type Error = anyhow::Error;
311
312 fn try_from(value: SpawnInTerminal) -> Result<Self, Self::Error> {
313 Ok(Self {
314 label: value.label,
315 command: value.command.context("missing command")?,
316 args: value.args,
317 env: value.env.into_iter().collect(),
318 cwd: value.cwd.map(|s| {
319 let s = s.to_string_lossy();
320 if cfg!(target_os = "windows") {
321 s.replace('\\', "/")
322 } else {
323 s.into_owned()
324 }
325 }),
326 })
327 }
328}
329
330impl From<CodeLabel> for extension::CodeLabel {
331 fn from(value: CodeLabel) -> Self {
332 Self {
333 code: value.code,
334 spans: value.spans.into_iter().map(Into::into).collect(),
335 filter_range: value.filter_range.into(),
336 }
337 }
338}
339
340impl From<CodeLabelSpan> for extension::CodeLabelSpan {
341 fn from(value: CodeLabelSpan) -> Self {
342 match value {
343 CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
344 CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
345 }
346 }
347}
348
349impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
350 fn from(value: CodeLabelSpanLiteral) -> Self {
351 Self {
352 text: value.text,
353 highlight_name: value.highlight_name,
354 }
355 }
356}
357
358impl From<extension::Completion> for Completion {
359 fn from(value: extension::Completion) -> Self {
360 Self {
361 label: value.label,
362 label_details: value.label_details.map(Into::into),
363 detail: value.detail,
364 kind: value.kind.map(Into::into),
365 insert_text_format: value.insert_text_format.map(Into::into),
366 }
367 }
368}
369
370impl From<extension::CompletionLabelDetails> for CompletionLabelDetails {
371 fn from(value: extension::CompletionLabelDetails) -> Self {
372 Self {
373 detail: value.detail,
374 description: value.description,
375 }
376 }
377}
378
379impl From<extension::CompletionKind> for CompletionKind {
380 fn from(value: extension::CompletionKind) -> Self {
381 match value {
382 extension::CompletionKind::Text => Self::Text,
383 extension::CompletionKind::Method => Self::Method,
384 extension::CompletionKind::Function => Self::Function,
385 extension::CompletionKind::Constructor => Self::Constructor,
386 extension::CompletionKind::Field => Self::Field,
387 extension::CompletionKind::Variable => Self::Variable,
388 extension::CompletionKind::Class => Self::Class,
389 extension::CompletionKind::Interface => Self::Interface,
390 extension::CompletionKind::Module => Self::Module,
391 extension::CompletionKind::Property => Self::Property,
392 extension::CompletionKind::Unit => Self::Unit,
393 extension::CompletionKind::Value => Self::Value,
394 extension::CompletionKind::Enum => Self::Enum,
395 extension::CompletionKind::Keyword => Self::Keyword,
396 extension::CompletionKind::Snippet => Self::Snippet,
397 extension::CompletionKind::Color => Self::Color,
398 extension::CompletionKind::File => Self::File,
399 extension::CompletionKind::Reference => Self::Reference,
400 extension::CompletionKind::Folder => Self::Folder,
401 extension::CompletionKind::EnumMember => Self::EnumMember,
402 extension::CompletionKind::Constant => Self::Constant,
403 extension::CompletionKind::Struct => Self::Struct,
404 extension::CompletionKind::Event => Self::Event,
405 extension::CompletionKind::Operator => Self::Operator,
406 extension::CompletionKind::TypeParameter => Self::TypeParameter,
407 extension::CompletionKind::Other(value) => Self::Other(value),
408 }
409 }
410}
411
412impl From<extension::InsertTextFormat> for InsertTextFormat {
413 fn from(value: extension::InsertTextFormat) -> Self {
414 match value {
415 extension::InsertTextFormat::PlainText => Self::PlainText,
416 extension::InsertTextFormat::Snippet => Self::Snippet,
417 extension::InsertTextFormat::Other(value) => Self::Other(value),
418 }
419 }
420}
421
422impl From<extension::Symbol> for Symbol {
423 fn from(value: extension::Symbol) -> Self {
424 Self {
425 kind: value.kind.into(),
426 name: value.name,
427 }
428 }
429}
430
431impl From<extension::SymbolKind> for SymbolKind {
432 fn from(value: extension::SymbolKind) -> Self {
433 match value {
434 extension::SymbolKind::File => Self::File,
435 extension::SymbolKind::Module => Self::Module,
436 extension::SymbolKind::Namespace => Self::Namespace,
437 extension::SymbolKind::Package => Self::Package,
438 extension::SymbolKind::Class => Self::Class,
439 extension::SymbolKind::Method => Self::Method,
440 extension::SymbolKind::Property => Self::Property,
441 extension::SymbolKind::Field => Self::Field,
442 extension::SymbolKind::Constructor => Self::Constructor,
443 extension::SymbolKind::Enum => Self::Enum,
444 extension::SymbolKind::Interface => Self::Interface,
445 extension::SymbolKind::Function => Self::Function,
446 extension::SymbolKind::Variable => Self::Variable,
447 extension::SymbolKind::Constant => Self::Constant,
448 extension::SymbolKind::String => Self::String,
449 extension::SymbolKind::Number => Self::Number,
450 extension::SymbolKind::Boolean => Self::Boolean,
451 extension::SymbolKind::Array => Self::Array,
452 extension::SymbolKind::Object => Self::Object,
453 extension::SymbolKind::Key => Self::Key,
454 extension::SymbolKind::Null => Self::Null,
455 extension::SymbolKind::EnumMember => Self::EnumMember,
456 extension::SymbolKind::Struct => Self::Struct,
457 extension::SymbolKind::Event => Self::Event,
458 extension::SymbolKind::Operator => Self::Operator,
459 extension::SymbolKind::TypeParameter => Self::TypeParameter,
460 extension::SymbolKind::Other(value) => Self::Other(value),
461 }
462 }
463}
464
465impl From<extension::SlashCommand> for SlashCommand {
466 fn from(value: extension::SlashCommand) -> Self {
467 Self {
468 name: value.name,
469 description: value.description,
470 tooltip_text: value.tooltip_text,
471 requires_argument: value.requires_argument,
472 }
473 }
474}
475
476impl From<SlashCommandOutput> for extension::SlashCommandOutput {
477 fn from(value: SlashCommandOutput) -> Self {
478 Self {
479 text: value.text,
480 sections: value.sections.into_iter().map(Into::into).collect(),
481 }
482 }
483}
484
485impl From<SlashCommandOutputSection> for extension::SlashCommandOutputSection {
486 fn from(value: SlashCommandOutputSection) -> Self {
487 Self {
488 range: value.range.start as usize..value.range.end as usize,
489 label: value.label,
490 }
491 }
492}
493
494impl From<SlashCommandArgumentCompletion> for extension::SlashCommandArgumentCompletion {
495 fn from(value: SlashCommandArgumentCompletion) -> Self {
496 Self {
497 label: value.label,
498 new_text: value.new_text,
499 run_command: value.run_command,
500 }
501 }
502}
503
504impl TryFrom<ContextServerConfiguration> for extension::ContextServerConfiguration {
505 type Error = anyhow::Error;
506
507 fn try_from(value: ContextServerConfiguration) -> Result<Self, Self::Error> {
508 let settings_schema: serde_json::Value = serde_json::from_str(&value.settings_schema)
509 .context("Failed to parse settings_schema")?;
510
511 Ok(Self {
512 installation_instructions: value.installation_instructions,
513 default_settings: value.default_settings,
514 settings_schema,
515 })
516 }
517}
518
519impl HostKeyValueStore for WasmState {
520 async fn insert(
521 &mut self,
522 kv_store: Resource<ExtensionKeyValueStore>,
523 key: String,
524 value: String,
525 ) -> wasmtime::Result<Result<(), String>> {
526 let kv_store = self.table.get(&kv_store)?;
527 kv_store.insert(key, value).await.to_wasmtime_result()
528 }
529
530 async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
531 // We only ever hand out borrows of key-value stores.
532 Ok(())
533 }
534}
535
536impl HostProject for WasmState {
537 async fn worktree_ids(
538 &mut self,
539 project: Resource<ExtensionProject>,
540 ) -> wasmtime::Result<Vec<u64>> {
541 let project = self.table.get(&project)?;
542 Ok(project.worktree_ids())
543 }
544
545 async fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
546 // We only ever hand out borrows of projects.
547 Ok(())
548 }
549}
550
551impl HostWorktree for WasmState {
552 async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
553 let delegate = self.table.get(&delegate)?;
554 Ok(delegate.id())
555 }
556
557 async fn root_path(
558 &mut self,
559 delegate: Resource<Arc<dyn WorktreeDelegate>>,
560 ) -> wasmtime::Result<String> {
561 let delegate = self.table.get(&delegate)?;
562 Ok(delegate.root_path())
563 }
564
565 async fn read_text_file(
566 &mut self,
567 delegate: Resource<Arc<dyn WorktreeDelegate>>,
568 path: String,
569 ) -> wasmtime::Result<Result<String, String>> {
570 let delegate = self.table.get(&delegate)?;
571 Ok(delegate
572 .read_text_file(&RelPath::new(Path::new(&path), PathStyle::Posix)?)
573 .await
574 .map_err(|error| error.to_string()))
575 }
576
577 async fn shell_env(
578 &mut self,
579 delegate: Resource<Arc<dyn WorktreeDelegate>>,
580 ) -> wasmtime::Result<EnvVars> {
581 let delegate = self.table.get(&delegate)?;
582 Ok(delegate.shell_env().await.into_iter().collect())
583 }
584
585 async fn which(
586 &mut self,
587 delegate: Resource<Arc<dyn WorktreeDelegate>>,
588 binary_name: String,
589 ) -> wasmtime::Result<Option<String>> {
590 let delegate = self.table.get(&delegate)?;
591 Ok(delegate.which(binary_name).await)
592 }
593
594 async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
595 // We only ever hand out borrows of worktrees.
596 Ok(())
597 }
598}
599
600impl common::Host for WasmState {}
601
602impl http_client::Host for WasmState {
603 async fn fetch(
604 &mut self,
605 request: http_client::HttpRequest,
606 ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
607 maybe!(async {
608 let url = &request.url;
609 let request = convert_request(&request)?;
610 let mut response = self.host.http_client.send(request).await?;
611
612 if response.status().is_client_error() || response.status().is_server_error() {
613 bail!("failed to fetch '{url}': status code {}", response.status())
614 }
615 convert_response(&mut response).await
616 })
617 .await
618 .to_wasmtime_result()
619 }
620
621 async fn fetch_stream(
622 &mut self,
623 request: http_client::HttpRequest,
624 ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
625 let request = convert_request(&request)?;
626 let response = self.host.http_client.send(request);
627 maybe!(async {
628 let response = response.await?;
629 let stream = Arc::new(Mutex::new(response));
630 let resource = self.table.push(stream)?;
631 Ok(resource)
632 })
633 .await
634 .to_wasmtime_result()
635 }
636}
637
638impl http_client::HostHttpResponseStream for WasmState {
639 async fn next_chunk(
640 &mut self,
641 resource: Resource<ExtensionHttpResponseStream>,
642 ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
643 let stream = self.table.get(&resource)?.clone();
644 maybe!(async move {
645 let mut response = stream.lock().await;
646 let mut buffer = vec![0; 8192]; // 8KB buffer
647 let bytes_read = response.body_mut().read(&mut buffer).await?;
648 if bytes_read == 0 {
649 Ok(None)
650 } else {
651 buffer.truncate(bytes_read);
652 Ok(Some(buffer))
653 }
654 })
655 .await
656 .to_wasmtime_result()
657 }
658
659 async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
660 Ok(())
661 }
662}
663
664impl From<http_client::HttpMethod> for ::http_client::Method {
665 fn from(value: http_client::HttpMethod) -> Self {
666 match value {
667 http_client::HttpMethod::Get => Self::GET,
668 http_client::HttpMethod::Post => Self::POST,
669 http_client::HttpMethod::Put => Self::PUT,
670 http_client::HttpMethod::Delete => Self::DELETE,
671 http_client::HttpMethod::Head => Self::HEAD,
672 http_client::HttpMethod::Options => Self::OPTIONS,
673 http_client::HttpMethod::Patch => Self::PATCH,
674 }
675 }
676}
677
678fn convert_request(
679 extension_request: &http_client::HttpRequest,
680) -> anyhow::Result<::http_client::Request<AsyncBody>> {
681 let mut request = ::http_client::Request::builder()
682 .method(::http_client::Method::from(extension_request.method))
683 .uri(&extension_request.url)
684 .follow_redirects(match extension_request.redirect_policy {
685 http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
686 http_client::RedirectPolicy::FollowLimit(limit) => {
687 ::http_client::RedirectPolicy::FollowLimit(limit)
688 }
689 http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
690 });
691 for (key, value) in &extension_request.headers {
692 request = request.header(key, value);
693 }
694 let body = extension_request
695 .body
696 .clone()
697 .map(AsyncBody::from)
698 .unwrap_or_default();
699 request.body(body).map_err(anyhow::Error::from)
700}
701
702async fn convert_response(
703 response: &mut ::http_client::Response<AsyncBody>,
704) -> anyhow::Result<http_client::HttpResponse> {
705 let mut extension_response = http_client::HttpResponse {
706 body: Vec::new(),
707 headers: Vec::new(),
708 };
709
710 for (key, value) in response.headers() {
711 extension_response
712 .headers
713 .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
714 }
715
716 response
717 .body_mut()
718 .read_to_end(&mut extension_response.body)
719 .await?;
720
721 Ok(extension_response)
722}
723
724impl nodejs::Host for WasmState {
725 async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
726 self.host
727 .node_runtime
728 .binary_path()
729 .await
730 .map(|path| path.to_string_lossy().into_owned())
731 .to_wasmtime_result()
732 }
733
734 async fn npm_package_latest_version(
735 &mut self,
736 package_name: String,
737 ) -> wasmtime::Result<Result<String, String>> {
738 self.host
739 .node_runtime
740 .npm_package_latest_version(&package_name)
741 .await
742 .to_wasmtime_result()
743 }
744
745 async fn npm_package_installed_version(
746 &mut self,
747 package_name: String,
748 ) -> wasmtime::Result<Result<Option<String>, String>> {
749 self.host
750 .node_runtime
751 .npm_package_installed_version(&self.work_dir(), &package_name)
752 .await
753 .to_wasmtime_result()
754 }
755
756 async fn npm_install_package(
757 &mut self,
758 package_name: String,
759 version: String,
760 ) -> wasmtime::Result<Result<(), String>> {
761 self.capability_granter
762 .grant_npm_install_package(&package_name)?;
763
764 self.host
765 .node_runtime
766 .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
767 .await
768 .to_wasmtime_result()
769 }
770}
771
772#[async_trait]
773impl lsp::Host for WasmState {}
774
775impl From<::http_client::github::GithubRelease> for github::GithubRelease {
776 fn from(value: ::http_client::github::GithubRelease) -> Self {
777 Self {
778 version: value.tag_name,
779 assets: value.assets.into_iter().map(Into::into).collect(),
780 }
781 }
782}
783
784impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
785 fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
786 Self {
787 name: value.name,
788 download_url: value.browser_download_url,
789 }
790 }
791}
792
793impl github::Host for WasmState {
794 async fn latest_github_release(
795 &mut self,
796 repo: String,
797 options: github::GithubReleaseOptions,
798 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
799 maybe!(async {
800 let release = ::http_client::github::latest_github_release(
801 &repo,
802 options.require_assets,
803 options.pre_release,
804 self.host.http_client.clone(),
805 )
806 .await?;
807 Ok(release.into())
808 })
809 .await
810 .to_wasmtime_result()
811 }
812
813 async fn github_release_by_tag_name(
814 &mut self,
815 repo: String,
816 tag: String,
817 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
818 maybe!(async {
819 let release = ::http_client::github::get_release_by_tag_name(
820 &repo,
821 &tag,
822 self.host.http_client.clone(),
823 )
824 .await?;
825 Ok(release.into())
826 })
827 .await
828 .to_wasmtime_result()
829 }
830}
831
832impl platform::Host for WasmState {
833 async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
834 Ok((
835 match env::consts::OS {
836 "macos" => platform::Os::Mac,
837 "linux" => platform::Os::Linux,
838 "windows" => platform::Os::Windows,
839 _ => panic!("unsupported os"),
840 },
841 match env::consts::ARCH {
842 "aarch64" => platform::Architecture::Aarch64,
843 "x86" => platform::Architecture::X86,
844 "x86_64" => platform::Architecture::X8664,
845 _ => panic!("unsupported architecture"),
846 },
847 ))
848 }
849}
850
851impl From<std::process::Output> for process::Output {
852 fn from(output: std::process::Output) -> Self {
853 Self {
854 status: output.status.code(),
855 stdout: output.stdout,
856 stderr: output.stderr,
857 }
858 }
859}
860
861impl process::Host for WasmState {
862 async fn run_command(
863 &mut self,
864 command: process::Command,
865 ) -> wasmtime::Result<Result<process::Output, String>> {
866 maybe!(async {
867 self.capability_granter
868 .grant_exec(&command.command, &command.args)?;
869
870 let output = util::command::new_smol_command(command.command.as_str())
871 .args(&command.args)
872 .envs(command.env)
873 .output()
874 .await?;
875
876 Ok(output.into())
877 })
878 .await
879 .to_wasmtime_result()
880 }
881}
882
883#[async_trait]
884impl slash_command::Host for WasmState {}
885
886#[async_trait]
887impl context_server::Host for WasmState {}
888
889impl dap::Host for WasmState {
890 async fn resolve_tcp_template(
891 &mut self,
892 template: TcpArgumentsTemplate,
893 ) -> wasmtime::Result<Result<TcpArguments, String>> {
894 maybe!(async {
895 let (host, port, timeout) =
896 ::dap::configure_tcp_connection(task::TcpArgumentsTemplate {
897 port: template.port,
898 host: template.host.map(Ipv4Addr::from_bits),
899 timeout: template.timeout,
900 })
901 .await?;
902 Ok(TcpArguments {
903 port,
904 host: host.to_bits(),
905 timeout,
906 })
907 })
908 .await
909 .to_wasmtime_result()
910 }
911}
912
913impl ExtensionImports for WasmState {
914 async fn get_settings(
915 &mut self,
916 location: Option<self::SettingsLocation>,
917 category: String,
918 key: Option<String>,
919 ) -> wasmtime::Result<Result<String, String>> {
920 self.on_main_thread(|cx| {
921 async move {
922 let path = location.as_ref().and_then(|location| {
923 RelPath::new(Path::new(&location.path), PathStyle::Posix).ok()
924 });
925 let location = path
926 .as_ref()
927 .zip(location.as_ref())
928 .map(|(path, location)| ::settings::SettingsLocation {
929 worktree_id: WorktreeId::from_proto(location.worktree_id),
930 path,
931 });
932
933 cx.update(|cx| match category.as_str() {
934 "language" => {
935 let key = key.map(|k| LanguageName::new(&k));
936 let settings = AllLanguageSettings::get(location, cx).language(
937 location,
938 key.as_ref(),
939 cx,
940 );
941 Ok(serde_json::to_string(&settings::LanguageSettings {
942 tab_size: settings.tab_size,
943 })?)
944 }
945 "lsp" => {
946 let settings = key
947 .and_then(|key| {
948 ProjectSettings::get(location, cx)
949 .lsp
950 .get(&::lsp::LanguageServerName::from_proto(key))
951 })
952 .cloned()
953 .unwrap_or_default();
954 Ok(serde_json::to_string(&settings::LspSettings {
955 binary: settings.binary.map(|binary| settings::CommandSettings {
956 path: binary.path,
957 arguments: binary.arguments,
958 env: binary.env.map(|env| env.into_iter().collect()),
959 }),
960 settings: settings.settings,
961 initialization_options: settings.initialization_options,
962 })?)
963 }
964 "context_servers" => {
965 let settings = key
966 .and_then(|key| {
967 ProjectSettings::get(location, cx)
968 .context_servers
969 .get(key.as_str())
970 })
971 .cloned()
972 .unwrap_or_else(|| {
973 project::project_settings::ContextServerSettings::default_extension(
974 )
975 });
976
977 match settings {
978 project::project_settings::ContextServerSettings::Stdio {
979 enabled: _,
980 command,
981 } => Ok(serde_json::to_string(&settings::ContextServerSettings {
982 command: Some(settings::CommandSettings {
983 path: command.path.to_str().map(|path| path.to_string()),
984 arguments: Some(command.args),
985 env: command.env.map(|env| env.into_iter().collect()),
986 }),
987 settings: None,
988 })?),
989 project::project_settings::ContextServerSettings::Extension {
990 enabled: _,
991 settings,
992 } => Ok(serde_json::to_string(&settings::ContextServerSettings {
993 command: None,
994 settings: Some(settings),
995 })?),
996 project::project_settings::ContextServerSettings::Http { .. } => {
997 bail!("remote context server settings not supported in 0.6.0")
998 }
999 }
1000 }
1001 _ => {
1002 bail!("Unknown settings category: {}", category);
1003 }
1004 })
1005 }
1006 .boxed_local()
1007 })
1008 .await?
1009 .to_wasmtime_result()
1010 }
1011
1012 async fn set_language_server_installation_status(
1013 &mut self,
1014 server_name: String,
1015 status: LanguageServerInstallationStatus,
1016 ) -> wasmtime::Result<()> {
1017 let status = match status {
1018 LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
1019 LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
1020 LanguageServerInstallationStatus::None => BinaryStatus::None,
1021 LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
1022 };
1023
1024 self.host
1025 .proxy
1026 .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
1027
1028 Ok(())
1029 }
1030
1031 async fn download_file(
1032 &mut self,
1033 url: String,
1034 path: String,
1035 file_type: DownloadedFileType,
1036 ) -> wasmtime::Result<Result<(), String>> {
1037 maybe!(async {
1038 let parsed_url = Url::parse(&url)?;
1039 self.capability_granter.grant_download_file(&parsed_url)?;
1040
1041 let path = PathBuf::from(path);
1042 let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
1043
1044 self.host.fs.create_dir(&extension_work_dir).await?;
1045
1046 let destination_path = self
1047 .host
1048 .writeable_path_from_extension(&self.manifest.id, &path)?;
1049
1050 let mut response = self
1051 .host
1052 .http_client
1053 .get(&url, Default::default(), true)
1054 .await
1055 .context("downloading release")?;
1056
1057 anyhow::ensure!(
1058 response.status().is_success(),
1059 "download failed with status {}",
1060 response.status()
1061 );
1062 let body = BufReader::new(response.body_mut());
1063
1064 match file_type {
1065 DownloadedFileType::Uncompressed => {
1066 futures::pin_mut!(body);
1067 self.host
1068 .fs
1069 .create_file_with(&destination_path, body)
1070 .await?;
1071 }
1072 DownloadedFileType::Gzip => {
1073 let body = GzipDecoder::new(body);
1074 futures::pin_mut!(body);
1075 self.host
1076 .fs
1077 .create_file_with(&destination_path, body)
1078 .await?;
1079 }
1080 DownloadedFileType::GzipTar => {
1081 let body = GzipDecoder::new(body);
1082 futures::pin_mut!(body);
1083 self.host
1084 .fs
1085 .extract_tar_file(&destination_path, Archive::new(body))
1086 .await?;
1087 }
1088 DownloadedFileType::Zip => {
1089 futures::pin_mut!(body);
1090 extract_zip(&destination_path, body)
1091 .await
1092 .with_context(|| format!("unzipping {path:?} archive"))?;
1093 }
1094 }
1095
1096 Ok(())
1097 })
1098 .await
1099 .to_wasmtime_result()
1100 }
1101
1102 async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
1103 let path = self
1104 .host
1105 .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
1106
1107 make_file_executable(&path)
1108 .await
1109 .with_context(|| format!("setting permissions for path {path:?}"))
1110 .to_wasmtime_result()
1111 }
1112}
1113
1114impl llm_provider::Host for WasmState {
1115 async fn request_credential(
1116 &mut self,
1117 _provider_id: String,
1118 _credential_type: llm_provider::CredentialType,
1119 _label: String,
1120 _placeholder: String,
1121 ) -> wasmtime::Result<Result<bool, String>> {
1122 // For now, credential requests return false (not provided)
1123 // Extensions should use get_env_var to check for env vars first,
1124 // then store_credential/get_credential for manual storage
1125 // Full UI credential prompting will be added in a future phase
1126 Ok(Ok(false))
1127 }
1128
1129 async fn get_credential(&mut self, provider_id: String) -> wasmtime::Result<Option<String>> {
1130 let extension_id = self.manifest.id.clone();
1131
1132 // Check if this provider has an env var configured and if the user has allowed it
1133 let env_var_name = self
1134 .manifest
1135 .language_model_providers
1136 .get(&Arc::<str>::from(provider_id.as_str()))
1137 .and_then(|entry| entry.auth.as_ref())
1138 .and_then(|auth| auth.env_var.clone());
1139
1140 if let Some(env_var_name) = env_var_name {
1141 let full_provider_id: Arc<str> = format!("{}:{}", extension_id, provider_id).into();
1142 // Read settings dynamically to get current allowed_env_var_providers
1143 let is_allowed = self
1144 .on_main_thread({
1145 let full_provider_id = full_provider_id.clone();
1146 move |cx| {
1147 async move {
1148 cx.update(|cx| {
1149 crate::extension_settings::ExtensionSettings::get_global(cx)
1150 .allowed_env_var_providers
1151 .contains(&full_provider_id)
1152 })
1153 }
1154 .boxed_local()
1155 }
1156 })
1157 .await
1158 .unwrap_or(false);
1159
1160 if is_allowed {
1161 if let Ok(value) = env::var(&env_var_name) {
1162 if !value.is_empty() {
1163 return Ok(Some(value));
1164 }
1165 }
1166 }
1167 }
1168
1169 // Fall back to credential store
1170 let credential_key = format!("extension-llm-{}:{}", extension_id, provider_id);
1171
1172 self.on_main_thread(move |cx| {
1173 async move {
1174 let credentials_provider = cx.update(|cx| <dyn CredentialsProvider>::global(cx))?;
1175 let result = credentials_provider
1176 .read_credentials(&credential_key, cx)
1177 .await
1178 .ok()
1179 .flatten();
1180 Ok(result.map(|(_, password)| String::from_utf8_lossy(&password).to_string()))
1181 }
1182 .boxed_local()
1183 })
1184 .await
1185 }
1186
1187 async fn store_credential(
1188 &mut self,
1189 provider_id: String,
1190 value: String,
1191 ) -> wasmtime::Result<Result<(), String>> {
1192 let extension_id = self.manifest.id.clone();
1193 let credential_key = format!("extension-llm-{}:{}", extension_id, provider_id);
1194
1195 self.on_main_thread(move |cx| {
1196 async move {
1197 let credentials_provider = cx.update(|cx| <dyn CredentialsProvider>::global(cx))?;
1198 credentials_provider
1199 .write_credentials(&credential_key, "api_key", value.as_bytes(), cx)
1200 .await
1201 .map_err(|e| anyhow::anyhow!("{}", e))
1202 }
1203 .boxed_local()
1204 })
1205 .await
1206 .to_wasmtime_result()
1207 }
1208
1209 async fn delete_credential(
1210 &mut self,
1211 provider_id: String,
1212 ) -> wasmtime::Result<Result<(), String>> {
1213 let extension_id = self.manifest.id.clone();
1214 let credential_key = format!("extension-llm-{}:{}", extension_id, provider_id);
1215
1216 self.on_main_thread(move |cx| {
1217 async move {
1218 let credentials_provider = cx.update(|cx| <dyn CredentialsProvider>::global(cx))?;
1219 credentials_provider
1220 .delete_credentials(&credential_key, cx)
1221 .await
1222 .map_err(|e| anyhow::anyhow!("{}", e))
1223 }
1224 .boxed_local()
1225 })
1226 .await
1227 .to_wasmtime_result()
1228 }
1229
1230 async fn get_env_var(&mut self, name: String) -> wasmtime::Result<Option<String>> {
1231 let extension_id = self.manifest.id.clone();
1232
1233 // Find which provider (if any) declares this env var in its auth config
1234 let mut allowed_provider_id: Option<Arc<str>> = None;
1235 for (provider_id, provider_entry) in &self.manifest.language_model_providers {
1236 if let Some(auth_config) = &provider_entry.auth {
1237 if auth_config.env_var.as_deref() == Some(&name) {
1238 allowed_provider_id = Some(provider_id.clone());
1239 break;
1240 }
1241 }
1242 }
1243
1244 // If no provider declares this env var, deny access
1245 let Some(provider_id) = allowed_provider_id else {
1246 log::warn!(
1247 "Extension {} attempted to read env var {} which is not declared in any provider auth config",
1248 extension_id,
1249 name
1250 );
1251 return Ok(None);
1252 };
1253
1254 // Check if the user has allowed this provider to read env vars
1255 // Read settings dynamically to get current allowed_env_var_providers
1256 let full_provider_id: Arc<str> = format!("{}:{}", extension_id, provider_id).into();
1257 let is_allowed = self
1258 .on_main_thread({
1259 let full_provider_id = full_provider_id.clone();
1260 move |cx| {
1261 async move {
1262 cx.update(|cx| {
1263 crate::extension_settings::ExtensionSettings::get_global(cx)
1264 .allowed_env_var_providers
1265 .contains(&full_provider_id)
1266 })
1267 }
1268 .boxed_local()
1269 }
1270 })
1271 .await
1272 .unwrap_or(false);
1273
1274 if !is_allowed {
1275 log::debug!(
1276 "Extension {} provider {} is not allowed to read env var {}",
1277 extension_id,
1278 provider_id,
1279 name
1280 );
1281 return Ok(None);
1282 }
1283
1284 Ok(env::var(&name).ok())
1285 }
1286
1287 async fn oauth_start_web_auth(
1288 &mut self,
1289 config: llm_provider::OauthWebAuthConfig,
1290 ) -> wasmtime::Result<Result<llm_provider::OauthWebAuthResult, String>> {
1291 let auth_url = config.auth_url;
1292 let callback_path = config.callback_path;
1293 let timeout_secs = config.timeout_secs.unwrap_or(300);
1294
1295 self.on_main_thread(move |cx| {
1296 async move {
1297 let listener = TcpListener::bind("127.0.0.1:0")
1298 .await
1299 .map_err(|e| anyhow::anyhow!("Failed to bind localhost server: {}", e))?;
1300 let port = listener
1301 .local_addr()
1302 .map_err(|e| anyhow::anyhow!("Failed to get local address: {}", e))?
1303 .port();
1304
1305 let auth_url_with_port = auth_url.replace("{port}", &port.to_string());
1306 cx.update(|cx| {
1307 cx.open_url(&auth_url_with_port);
1308 })?;
1309
1310 let accept_future = async {
1311 let (mut stream, _) = listener
1312 .accept()
1313 .await
1314 .map_err(|e| anyhow::anyhow!("Failed to accept connection: {}", e))?;
1315
1316 let mut request_line = String::new();
1317 {
1318 let mut reader = smol::io::BufReader::new(&mut stream);
1319 smol::io::AsyncBufReadExt::read_line(&mut reader, &mut request_line)
1320 .await
1321 .map_err(|e| anyhow::anyhow!("Failed to read request: {}", e))?;
1322 }
1323
1324 let callback_url = if let Some(path_start) = request_line.find(' ') {
1325 if let Some(path_end) = request_line[path_start + 1..].find(' ') {
1326 let path = &request_line[path_start + 1..path_start + 1 + path_end];
1327 if path.starts_with(&callback_path) || path.starts_with(&format!("/{}", callback_path.trim_start_matches('/'))) {
1328 format!("http://localhost:{}{}", port, path)
1329 } else {
1330 return Err(anyhow::anyhow!(
1331 "Unexpected callback path: {}",
1332 path
1333 ));
1334 }
1335 } else {
1336 return Err(anyhow::anyhow!("Malformed HTTP request"));
1337 }
1338 } else {
1339 return Err(anyhow::anyhow!("Malformed HTTP request"));
1340 };
1341
1342 let response = "HTTP/1.1 200 OK\r\n\
1343 Content-Type: text/html\r\n\
1344 Connection: close\r\n\
1345 \r\n\
1346 <!DOCTYPE html>\
1347 <html><head><title>Authentication Complete</title></head>\
1348 <body style=\"font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;\">\
1349 <div style=\"text-align: center;\">\
1350 <h1>Authentication Complete</h1>\
1351 <p>You can close this window and return to Zed.</p>\
1352 </div></body></html>";
1353
1354 smol::io::AsyncWriteExt::write_all(&mut stream, response.as_bytes())
1355 .await
1356 .ok();
1357 smol::io::AsyncWriteExt::flush(&mut stream).await.ok();
1358
1359 Ok(callback_url)
1360 };
1361
1362 let timeout_duration = Duration::from_secs(timeout_secs as u64);
1363 let callback_url = smol::future::or(
1364 accept_future,
1365 async {
1366 smol::Timer::after(timeout_duration).await;
1367 Err(anyhow::anyhow!(
1368 "OAuth callback timed out after {} seconds",
1369 timeout_secs
1370 ))
1371 },
1372 )
1373 .await?;
1374
1375 Ok(llm_provider::OauthWebAuthResult {
1376 callback_url,
1377 port: port as u32,
1378 })
1379 }
1380 .boxed_local()
1381 })
1382 .await
1383 .to_wasmtime_result()
1384 }
1385
1386 async fn send_oauth_http_request(
1387 &mut self,
1388 request: llm_provider::OauthHttpRequest,
1389 ) -> wasmtime::Result<Result<llm_provider::OauthHttpResponse, String>> {
1390 let http_client = self.host.http_client.clone();
1391
1392 self.on_main_thread(move |_cx| {
1393 async move {
1394 let method = match request.method.to_uppercase().as_str() {
1395 "GET" => ::http_client::Method::GET,
1396 "POST" => ::http_client::Method::POST,
1397 "PUT" => ::http_client::Method::PUT,
1398 "DELETE" => ::http_client::Method::DELETE,
1399 "PATCH" => ::http_client::Method::PATCH,
1400 _ => {
1401 return Err(anyhow::anyhow!(
1402 "Unsupported HTTP method: {}",
1403 request.method
1404 ));
1405 }
1406 };
1407
1408 let mut builder = ::http_client::Request::builder()
1409 .method(method)
1410 .uri(&request.url);
1411
1412 for (key, value) in &request.headers {
1413 builder = builder.header(key.as_str(), value.as_str());
1414 }
1415
1416 let body = if request.body.is_empty() {
1417 AsyncBody::empty()
1418 } else {
1419 AsyncBody::from(request.body.into_bytes())
1420 };
1421
1422 let http_request = builder
1423 .body(body)
1424 .map_err(|e| anyhow::anyhow!("Failed to build request: {}", e))?;
1425
1426 let mut response = http_client
1427 .send(http_request)
1428 .await
1429 .map_err(|e| anyhow::anyhow!("HTTP request failed: {}", e))?;
1430
1431 let status = response.status().as_u16();
1432 let headers: Vec<(String, String)> = response
1433 .headers()
1434 .iter()
1435 .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
1436 .collect();
1437
1438 let mut body_bytes = Vec::new();
1439 futures::AsyncReadExt::read_to_end(response.body_mut(), &mut body_bytes)
1440 .await
1441 .map_err(|e| anyhow::anyhow!("Failed to read response body: {}", e))?;
1442
1443 let body = String::from_utf8_lossy(&body_bytes).to_string();
1444
1445 Ok(llm_provider::OauthHttpResponse {
1446 status,
1447 headers,
1448 body,
1449 })
1450 }
1451 .boxed_local()
1452 })
1453 .await
1454 .to_wasmtime_result()
1455 }
1456
1457 async fn oauth_open_browser(&mut self, url: String) -> wasmtime::Result<Result<(), String>> {
1458 self.on_main_thread(move |cx| {
1459 async move {
1460 cx.update(|cx| {
1461 cx.open_url(&url);
1462 })?;
1463 Ok(())
1464 }
1465 .boxed_local()
1466 })
1467 .await
1468 .to_wasmtime_result()
1469 }
1470}