Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T01:36:16.511Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

task.rs

483 lines · 20.1 KB · rust
1//! Baseline interface of Tasks in Zed: all tasks in Zed are intended to use those for implementing their own logic.
2
3mod adapter_schema;
4mod debug_format;
5mod serde_helpers;
6pub mod static_source;
7mod task_template;
8mod vscode_debug_format;
9mod vscode_format;
10
11use anyhow::Context as _;
12use collections::{HashMap, HashSet, hash_map};
13use gpui::SharedString;
14use serde::{Deserialize, Serialize};
15use std::borrow::Cow;
16use std::path::PathBuf;
17use std::str::FromStr;
18use std::sync::Arc;
19
20pub use adapter_schema::{AdapterSchema, AdapterSchemas};
21pub use debug_format::{
22    AttachRequest, BuildTaskDefinition, DebugRequest, DebugScenario, DebugTaskFile, LaunchRequest,
23    Request, TcpArgumentsTemplate, ZedDebugConfig,
24};
25pub use task_template::{
26    DebugArgsRequest, HideStrategy, RevealStrategy, SaveStrategy, TaskHook, TaskTemplate,
27    TaskTemplates, substitute_variables_in_map, substitute_variables_in_str,
28};
29pub use util::shell::{Shell, ShellKind};
30pub use util::shell_builder::ShellBuilder;
31pub use vscode_debug_format::VsCodeDebugTaskFile;
32pub use vscode_format::VsCodeTaskFile;
33pub use zed_actions::RevealTarget;
34
35/// Task identifier, unique within the application.
36/// Based on it, task reruns and terminal tabs are managed.
37#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize)]
38pub struct TaskId(pub String);
39
40/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
41#[derive(Default, Debug, Clone, PartialEq, Eq)]
42pub struct SpawnInTerminal {
43    /// Id of the task to use when determining task tab affinity.
44    pub id: TaskId,
45    /// Full unshortened form of `label` field.
46    pub full_label: String,
47    /// Human readable name of the terminal tab.
48    pub label: String,
49    /// Executable command to spawn.
50    pub command: Option<String>,
51    /// Arguments to the command, potentially unsubstituted,
52    /// to let the shell that spawns the command to do the substitution, if needed.
53    pub args: Vec<String>,
54    /// A human-readable label, containing command and all of its arguments, joined and substituted.
55    pub command_label: String,
56    /// Current working directory to spawn the command into.
57    pub cwd: Option<PathBuf>,
58    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
59    pub env: HashMap<String, String>,
60    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
61    pub use_new_terminal: bool,
62    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
63    pub allow_concurrent_runs: bool,
64    /// What to do with the terminal pane and tab, after the command was started.
65    pub reveal: RevealStrategy,
66    /// Where to show tasks' terminal output.
67    pub reveal_target: RevealTarget,
68    /// What to do with the terminal pane and tab, after the command had finished.
69    pub hide: HideStrategy,
70    /// Which shell to use when spawning the task.
71    pub shell: Shell,
72    /// Whether to show the task summary line in the task output (success/failure).
73    pub show_summary: bool,
74    /// Whether to show the command line in the task output.
75    pub show_command: bool,
76    /// Whether to show the rerun button in the terminal tab.
77    pub show_rerun: bool,
78    /// Which edited buffers to save before running the task.
79    pub save: SaveStrategy,
80}
81
82impl SpawnInTerminal {
83    pub fn to_proto(&self) -> proto::SpawnInTerminal {
84        proto::SpawnInTerminal {
85            label: self.label.clone(),
86            command: self.command.clone(),
87            args: self.args.clone(),
88            env: self
89                .env
90                .iter()
91                .map(|(k, v)| (k.clone(), v.clone()))
92                .collect(),
93            cwd: self
94                .cwd
95                .clone()
96                .map(|cwd| cwd.to_string_lossy().into_owned()),
97        }
98    }
99
100    pub fn from_proto(proto: proto::SpawnInTerminal) -> Self {
101        Self {
102            label: proto.label.clone(),
103            command: proto.command.clone(),
104            args: proto.args.clone(),
105            env: proto.env.into_iter().collect(),
106            cwd: proto.cwd.map(PathBuf::from),
107            ..Default::default()
108        }
109    }
110}
111
112/// A final form of the [`TaskTemplate`], that got resolved with a particular [`TaskContext`] and now is ready to spawn the actual task.
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct ResolvedTask {
115    /// A way to distinguish tasks produced by the same template, but different contexts.
116    /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
117    /// but still may have different ids if the context was different during the resolution.
118    /// Since the template has `env` field, for a generic task that may be a bash command,
119    /// so it's impossible to determine the id equality without more context in a generic case.
120    pub id: TaskId,
121    /// A template the task got resolved from.
122    original_task: TaskTemplate,
123    /// Full, unshortened label of the task after all resolutions are made.
124    pub resolved_label: String,
125    /// Variables that were substituted during the task template resolution.
126    substituted_variables: HashSet<VariableName>,
127    /// Further actions that need to take place after the resolved task is spawned,
128    /// with all task variables resolved.
129    pub resolved: SpawnInTerminal,
130}
131
132impl ResolvedTask {
133    /// A task template before the resolution.
134    pub fn original_task(&self) -> &TaskTemplate {
135        &self.original_task
136    }
137
138    /// Variables that were substituted during the task template resolution.
139    pub fn substituted_variables(&self) -> &HashSet<VariableName> {
140        &self.substituted_variables
141    }
142
143    /// A human-readable label to display in the UI.
144    pub fn display_label(&self) -> &str {
145        self.resolved.label.as_str()
146    }
147}
148
149/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
150/// Name of the variable must be a valid shell variable identifier, which generally means that it is
151/// a word  consisting only  of alphanumeric characters and underscores,
152/// and beginning with an alphabetic character or an  underscore.
153#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
154pub enum VariableName {
155    /// An absolute path of the currently opened file.
156    File,
157    /// A path of the currently opened file (relative to worktree root).
158    RelativeFile,
159    /// A path of the currently opened file's directory (relative to worktree root).
160    RelativeDir,
161    /// The currently opened filename.
162    Filename,
163    /// The path to a parent directory of a currently opened file.
164    Dirname,
165    /// Stem (filename without extension) of the currently opened file.
166    Stem,
167    /// An absolute path of the currently opened worktree, that contains the file.
168    WorktreeRoot,
169    /// A symbol text, that contains latest cursor/selection position.
170    Symbol,
171    /// A row with the latest cursor/selection position.
172    Row,
173    /// A column with the latest cursor/selection position.
174    Column,
175    /// Text from the latest selection.
176    SelectedText,
177    /// The language of the currently opened buffer (e.g., "Rust", "Python").
178    Language,
179    /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
180    RunnableSymbol,
181    /// Open a Picker to select a process ID to use in place
182    /// Can only be used to debug configurations
183    PickProcessId,
184    /// An absolute path of the main (original) git worktree for the current repository.
185    /// For normal checkouts, this equals the worktree root. For linked worktrees,
186    /// this is the original repo's working directory.
187    MainGitWorktree,
188    /// Full SHA for the Git commit associated with the task context.
189    GitSha,
190    /// Short SHA for the Git commit associated with the task context.
191    GitShaShort,
192    /// Name of the Git repository associated with the task context.
193    GitRepositoryName,
194    /// Absolute path of the Git repository associated with the task context.
195    GitRepositoryPath,
196    /// Name of the Git ref (branch, remote ref, or tag) associated with the task context.
197    GitRef,
198    /// Custom variable, provided by the plugin or other external source.
199    /// Will be printed with `CUSTOM_` prefix to avoid potential conflicts with other variables.
200    Custom(Cow<'static, str>),
201}
202
203impl VariableName {
204    /// Generates a `$VARIABLE`-like string value to be used in templates.
205    pub fn template_value(&self) -> String {
206        format!("${self}")
207    }
208    /// Generates a `"$VARIABLE"`-like string, to be used instead of `Self::template_value` when expanded value could contain spaces or special characters.
209    pub fn template_value_with_whitespace(&self) -> String {
210        format!("\"${self}\"")
211    }
212}
213
214impl FromStr for VariableName {
215    type Err = ();
216
217    fn from_str(s: &str) -> Result<Self, Self::Err> {
218        let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
219        let value = match without_prefix {
220            "FILE" => Self::File,
221            "FILENAME" => Self::Filename,
222            "RELATIVE_FILE" => Self::RelativeFile,
223            "RELATIVE_DIR" => Self::RelativeDir,
224            "DIRNAME" => Self::Dirname,
225            "STEM" => Self::Stem,
226            "WORKTREE_ROOT" => Self::WorktreeRoot,
227            "SYMBOL" => Self::Symbol,
228            "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
229            "SELECTED_TEXT" => Self::SelectedText,
230            "LANGUAGE" => Self::Language,
231            "ROW" => Self::Row,
232            "COLUMN" => Self::Column,
233            "MAIN_GIT_WORKTREE" => Self::MainGitWorktree,
234            "GIT_SHA" => Self::GitSha,
235            "GIT_SHA_SHORT" => Self::GitShaShort,
236            "GIT_REPOSITORY_NAME" => Self::GitRepositoryName,
237            "GIT_REPOSITORY_PATH" => Self::GitRepositoryPath,
238            "GIT_REF" => Self::GitRef,
239            _ => {
240                if let Some(custom_name) =
241                    without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
242                {
243                    Self::Custom(Cow::Owned(custom_name.to_owned()))
244                } else {
245                    return Err(());
246                }
247            }
248        };
249        Ok(value)
250    }
251}
252
253/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
254pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
255const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
256
257impl std::fmt::Display for VariableName {
258    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
259        match self {
260            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
261            Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
262            Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
263            Self::RelativeDir => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_DIR"),
264            Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
265            Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
266            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
267            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
268            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
269            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
270            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
271            Self::Language => write!(f, "{ZED_VARIABLE_NAME_PREFIX}LANGUAGE"),
272            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
273            Self::PickProcessId => write!(f, "{ZED_VARIABLE_NAME_PREFIX}PICK_PID"),
274            Self::MainGitWorktree => write!(f, "{ZED_VARIABLE_NAME_PREFIX}MAIN_GIT_WORKTREE"),
275            Self::GitSha => write!(f, "{ZED_VARIABLE_NAME_PREFIX}GIT_SHA"),
276            Self::GitShaShort => write!(f, "{ZED_VARIABLE_NAME_PREFIX}GIT_SHA_SHORT"),
277            Self::GitRepositoryName => write!(f, "{ZED_VARIABLE_NAME_PREFIX}GIT_REPOSITORY_NAME"),
278            Self::GitRepositoryPath => write!(f, "{ZED_VARIABLE_NAME_PREFIX}GIT_REPOSITORY_PATH"),
279            Self::GitRef => write!(f, "{ZED_VARIABLE_NAME_PREFIX}GIT_REF"),
280            Self::Custom(s) => write!(
281                f,
282                "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
283            ),
284        }
285    }
286}
287
288/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
289#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
290pub struct TaskVariables(HashMap<VariableName, String>);
291
292impl TaskVariables {
293    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
294    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
295        self.0.insert(variable, value)
296    }
297
298    /// Extends the container with another one, overwriting the existing variables on collision.
299    pub fn extend(&mut self, other: Self) {
300        self.0.extend(other.0);
301    }
302    /// Get the value associated with given variable name, if there is one.
303    pub fn get(&self, key: &VariableName) -> Option<&str> {
304        self.0.get(key).map(|s| s.as_str())
305    }
306    /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
307    pub fn sweep(&mut self) {
308        self.0.retain(|name, _| {
309            if let VariableName::Custom(name) = name {
310                !name.starts_with('_')
311            } else {
312                true
313            }
314        })
315    }
316
317    pub fn iter(&self) -> impl Iterator<Item = (&VariableName, &String)> {
318        self.0.iter()
319    }
320}
321
322impl FromIterator<(VariableName, String)> for TaskVariables {
323    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
324        Self(HashMap::from_iter(iter))
325    }
326}
327
328impl IntoIterator for TaskVariables {
329    type Item = (VariableName, String);
330
331    type IntoIter = hash_map::IntoIter<VariableName, String>;
332
333    fn into_iter(self) -> Self::IntoIter {
334        self.0.into_iter()
335    }
336}
337
338/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
339/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
340#[derive(Clone, Debug, Default, PartialEq, Eq)]
341pub struct TaskContext {
342    /// A path to a directory in which the task should be executed.
343    pub cwd: Option<PathBuf>,
344    /// Additional environment variables associated with a given task.
345    pub task_variables: TaskVariables,
346    /// Environment variables obtained when loading the project into Zed.
347    /// This is the environment one would get when `cd`ing in a terminal
348    /// into the project's root directory.
349    pub project_env: HashMap<String, String>,
350}
351
352/// A shared reference to a [`TaskContext`], used to avoid cloning the context multiple times.
353#[derive(Clone, Debug, Default)]
354pub struct SharedTaskContext(Arc<TaskContext>);
355
356impl std::ops::Deref for SharedTaskContext {
357    type Target = TaskContext;
358
359    fn deref(&self) -> &Self::Target {
360        &self.0
361    }
362}
363
364impl From<TaskContext> for SharedTaskContext {
365    fn from(context: TaskContext) -> Self {
366        Self(Arc::new(context))
367    }
368}
369
370/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
371#[derive(Clone, Debug)]
372pub struct RunnableTag(pub SharedString);
373
374pub fn shell_from_proto(proto: proto::Shell) -> anyhow::Result<Shell> {
375    let shell_type = proto.shell_type.context("invalid shell type")?;
376    let shell = match shell_type {
377        proto::shell::ShellType::System(_) => Shell::System,
378        proto::shell::ShellType::Program(program) => Shell::Program(program),
379        proto::shell::ShellType::WithArguments(program) => Shell::WithArguments {
380            program: program.program,
381            args: program.args,
382            title_override: None,
383        },
384    };
385    Ok(shell)
386}
387
388pub fn shell_to_proto(shell: Shell) -> proto::Shell {
389    let shell_type = match shell {
390        Shell::System => proto::shell::ShellType::System(proto::System {}),
391        Shell::Program(program) => proto::shell::ShellType::Program(program),
392        Shell::WithArguments {
393            program,
394            args,
395            title_override: _,
396        } => proto::shell::ShellType::WithArguments(proto::shell::WithArguments { program, args }),
397    };
398    proto::Shell {
399        shell_type: Some(shell_type),
400    }
401}
402
403type VsCodeEnvVariable = String;
404type VsCodeCommand = String;
405type ZedEnvVariable = String;
406
407struct EnvVariableReplacer {
408    variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>,
409    commands: HashMap<VsCodeCommand, ZedEnvVariable>,
410}
411
412impl EnvVariableReplacer {
413    fn new(variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>) -> Self {
414        Self {
415            variables,
416            commands: HashMap::default(),
417        }
418    }
419
420    fn with_commands(
421        mut self,
422        commands: impl IntoIterator<Item = (VsCodeCommand, ZedEnvVariable)>,
423    ) -> Self {
424        self.commands = commands.into_iter().collect();
425        self
426    }
427
428    fn replace_value(&self, input: serde_json::Value) -> serde_json::Value {
429        match input {
430            serde_json::Value::String(s) => serde_json::Value::String(self.replace(&s)),
431            serde_json::Value::Array(arr) => {
432                serde_json::Value::Array(arr.into_iter().map(|v| self.replace_value(v)).collect())
433            }
434            serde_json::Value::Object(obj) => serde_json::Value::Object(
435                obj.into_iter()
436                    .map(|(k, v)| (self.replace(&k), self.replace_value(v)))
437                    .collect(),
438            ),
439            _ => input,
440        }
441    }
442    // Replaces occurrences of VsCode-specific environment variables with Zed equivalents.
443    fn replace(&self, input: &str) -> String {
444        shellexpand::env_with_context_no_errors(&input, |var: &str| {
445            // Colons denote a default value in case the variable is not set. We want to preserve that default, as otherwise shellexpand will substitute it for us.
446            let colon_position = var.find(':').unwrap_or(var.len());
447            let (left, right) = var.split_at(colon_position);
448            if left == "env" && !right.is_empty() {
449                let variable_name = &right[1..];
450                return Some(format!("${{{variable_name}}}"));
451            } else if left == "command" && !right.is_empty() {
452                let command_name = &right[1..];
453                if let Some(replacement_command) = self.commands.get(command_name) {
454                    return Some(format!("${{{replacement_command}}}"));
455                }
456            }
457
458            let (variable_name, default) = (left, right);
459            let append_previous_default = |ret: &mut String| {
460                if !default.is_empty() {
461                    ret.push_str(default);
462                }
463            };
464            if let Some(substitution) = self.variables.get(variable_name) {
465                // Got a VSCode->Zed hit, perform a substitution
466                let mut name = format!("${{{substitution}");
467                append_previous_default(&mut name);
468                name.push('}');
469                return Some(name);
470            }
471            // This is an unknown variable.
472            // We should not error out, as they may come from user environment (e.g. $PATH). That means that the variable substitution might not be perfect.
473            // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
474            if !default.is_empty() {
475                return Some(format!("${{{var}}}"));
476            }
477            // Else we can just return None and that variable will be left as is.
478            None
479        })
480        .into_owned()
481    }
482}
483
Served at tenant.openagents/omega Member data and write actions are omitted.