diff --git a/backend/parsers/windmill-parser-r/src/lib.rs b/backend/parsers/windmill-parser-r/src/lib.rs index e73d358a60..756bd3ca1a 100644 --- a/backend/parsers/windmill-parser-r/src/lib.rs +++ b/backend/parsers/windmill-parser-r/src/lib.rs @@ -40,8 +40,12 @@ pub fn parse_r_signature(code: &str) -> anyhow::Result { Ok(parse_r_sig_meta(code)?) } -/// Extract package names from `library(...)` and `require(...)` calls in R code. -/// Returns a newline-separated list of package names. +/// Extract the packages R code depends on: `library()`, `require()`, `requireNamespace()`, +/// `loadNamespace()` and `pkg::fun` / `pkg:::fun`. Returns a newline-separated, sorted list. +/// +/// The worker keys its resolution cache on this list while renv resolves from its own scan of +/// the code, so a form renv detects and this misses lets two scripts share a lock that lacks +/// one of their packages. pub fn parse_r_requirements(code: &str) -> anyhow::Result { let mut parser = tree_sitter::Parser::new(); let language = tree_sitter_r::LANGUAGE; @@ -66,41 +70,89 @@ pub fn parse_r_requirements(code: &str) -> anyhow::Result { } fn find_library_calls(node: Node, code: &str, packages: &mut Vec) { + let text = |n: Node| n.utf8_text(code.as_bytes()).unwrap_or(""); let mut cursor = node.walk(); for child in node.children(&mut cursor) { - if child.kind() == "call" { - // call node: child 0 is the function name, child 1 is arguments - if let (Some(func_node), Some(args_node)) = (child.child(0), child.child(1)) { - let func_name = func_node.utf8_text(code.as_bytes()).unwrap_or(""); - if func_name == "library" || func_name == "require" { - // AST: arguments → ( + argument → identifier/string + ) - if args_node.kind() == "arguments" { - let mut args_cursor = args_node.walk(); - for arg in args_node.children(&mut args_cursor) { - if arg.kind() == "argument" { - // The argument node wraps the actual value - if let Some(value_node) = arg.child(0) { - let pkg = value_node - .utf8_text(code.as_bytes()) - .unwrap_or("") - .trim_matches('"') - .trim_matches('\''); - if !pkg.is_empty() { - packages.push(pkg.to_string()); - } - } - break; // only first arg - } + match child.kind() { + "call" => { + if let (Some(func_node), Some(args_node)) = ( + child.child_by_field_name("function"), + child.child_by_field_name("arguments"), + ) { + // `library` and `require` take a bare name unless `character.only = TRUE`; + // the namespace functions take a string. + let bare_name_allowed = match text(func_node) { + "library" | "require" => !has_character_only(args_node, code), + "requireNamespace" | "loadNamespace" => false, + _ => { + find_library_calls(child, code, packages); + continue; + } + }; + if let Some(value) = package_argument(args_node, code) { + let pkg = match value.kind() { + "identifier" if bare_name_allowed => Some(text(value)), + "string" => Some(text(value).trim_matches(['"', '\''])), + _ => None, + }; + if let Some(pkg) = pkg.filter(|p| !p.is_empty()) { + packages.push(pkg.to_string()); } } } } + "namespace_operator" => { + if let Some(lhs) = child.child_by_field_name("lhs") { + if matches!(lhs.kind(), "identifier" | "string") { + let pkg = text(lhs).trim_matches(['"', '\'']); + if !pkg.is_empty() { + packages.push(pkg.to_string()); + } + } + } + } + _ => {} } - // Recurse into children to find nested library() calls find_library_calls(child, code, packages); } } +/// The first positional argument, or the one named `package`. +fn package_argument<'a>(args_node: Node<'a>, code: &str) -> Option> { + let mut cursor = args_node.walk(); + let mut first_positional = None; + for arg in args_node.children(&mut cursor) { + if arg.kind() != "argument" { + continue; + } + match arg.child_by_field_name("name") { + Some(name) if name.utf8_text(code.as_bytes()).unwrap_or("") == "package" => { + return arg.child_by_field_name("value"); + } + Some(_) => {} + None if first_positional.is_none() => { + first_positional = arg.child_by_field_name("value"); + } + None => {} + } + } + first_positional +} + +fn has_character_only(args_node: Node, code: &str) -> bool { + let mut cursor = args_node.walk(); + let found = args_node.children(&mut cursor).any(|arg| { + arg.kind() == "argument" + && arg + .child_by_field_name("name") + .is_some_and(|n| n.utf8_text(code.as_bytes()).unwrap_or("") == "character.only") + && arg + .child_by_field_name("value") + .is_some_and(|v| matches!(v.utf8_text(code.as_bytes()).unwrap_or(""), "TRUE" | "T")) + }); + found +} + fn is_base_package(pkg: &str) -> bool { matches!( pkg, @@ -353,6 +405,30 @@ main <- function() { } assert!(pkgs.contains(&"jsonlite")); } + #[test] + fn test_parse_r_requirements_namespace_forms() { + use super::parse_r_requirements; + + let code = r#" +suppressPackageStartupMessages(library("dplyr", quietly = TRUE)) +library(package = tidyr) +x <- cli::rule() +y <- R6:::encapsulate +if (requireNamespace("crayon", quietly = TRUE)) {} +loadNamespace('digest') +z <- utils::head(1) +p <- "ggplot2" +library(p, character.only = TRUE) +requireNamespace(p) +"#; + let reqs = parse_r_requirements(code).unwrap(); + let pkgs: Vec<&str> = reqs.lines().collect(); + assert_eq!( + pkgs, + vec!["R6", "cli", "crayon", "digest", "dplyr", "tidyr"] + ); + } + #[test] fn test_parse_r_requirements_no_deps() { use super::parse_r_requirements; diff --git a/backend/windmill-api/src/ai_session_tools/gen/instructions.json b/backend/windmill-api/src/ai_session_tools/gen/instructions.json index 196a5ea212..c1779ee78a 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -304,7 +304,7 @@ "script.nu": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (nu)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n", "script.java": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (java)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# Java\n\nThe script must contain a Main public class with a `public static main()` method:\n\n```java\npublic class Main {\n public static Object main(String name, int count) {\n java.util.Map result = new java.util.HashMap<>();\n result.put(\"name\", name);\n result.put(\"count\", count);\n return result;\n }\n}\n```\n\n**Important:**\n- Class must be named `Main`\n- Method must be `public static Object main(...)`\n- Return type is `Object` or `void`\n\n## Maven Dependencies\n\nAdd dependencies using comments at the top:\n\n```java\n//requirements:\n//com.google.code.gson:gson:2.10.1\n//org.apache.httpcomponents:httpclient:4.5.14\n\nimport com.google.gson.Gson;\n\npublic class Main {\n public static Object main(String input) {\n Gson gson = new Gson();\n return gson.fromJson(input, Object.class);\n }\n}\n```\n", "script.ruby": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (ruby)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n", - "script.rlang": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (rlang)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# R\n\n## Structure\n\nDefine a `main` function using `<-` or `=` assignment. Parameters become the script inputs:\n\n```r\nlibrary(dplyr)\nlibrary(jsonlite)\n\nmain <- function(x, name = \"default\", flag = TRUE) {\n df <- tibble(x = x, name = name)\n result <- df %>% mutate(greeting = paste(\"Hello\", name))\n return(toJSON(result, auto_unbox = TRUE))\n}\n```\n\n**Important:**\n- The `main` function is required\n- Use `library()` to load packages — they are resolved and installed automatically\n- `jsonlite` is always available (used internally for argument parsing)\n- Return values must be JSON-serializable\n\n## Parameters\n\nR types map to Windmill types:\n- `numeric` → float/int\n- `character` → string\n- `logical` → bool (use `TRUE`/`FALSE`)\n- `list` → object/dict\n- `NULL` → null\n\nDefault values are inferred from the function signature:\n\n```r\nmain <- function(\n name, # required string\n count = 10, # optional int, default 10\n verbose = FALSE # optional bool, default FALSE\n) {\n # ...\n}\n```\n\n## Resources and Variables\n\nUse the built-in Windmill helpers (no import needed):\n\n```r\nmain <- function() {\n # Get a variable\n api_key <- get_variable(\"f/my_folder/api_key\")\n\n # Get a resource (returns a list)\n db <- get_resource(\"f/my_folder/postgres_config\")\n host <- db$host\n port <- db$port\n\n return(list(host = host, port = port))\n}\n```\n\n## Output\n\nReturn any JSON-serializable value from `main`. The return value becomes the step result:\n\n```r\nmain <- function(x) {\n # Return a scalar\n return(x + 1)\n\n # Or a list (becomes JSON object)\n return(list(result = x + 1, status = \"ok\"))\n}\n```\n\n## Annotations\n\nControl execution behavior with comment annotations:\n\n```r\n#renv_verbose = true # Show verbose renv output during resolution\n#renv_install_verbose = true # Show verbose output during package installation\n#sandbox = true # Run in nsjail sandbox (requires nsjail)\n```\n", + "script.rlang": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (rlang)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# R\n\n## Structure\n\nDefine a `main` function using `<-` or `=` assignment. Parameters become the script inputs:\n\n```r\nlibrary(dplyr)\nlibrary(jsonlite)\n\nmain <- function(x, name = \"default\", flag = TRUE) {\n df <- tibble(x = x, name = name)\n result <- df %>% mutate(greeting = paste(\"Hello\", name))\n return(toJSON(result, auto_unbox = TRUE))\n}\n```\n\n**Important:**\n- The `main` function is required\n- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()`\n- A deployed script runs with the package versions locked when it was deployed\n- `jsonlite` is always available (used internally for argument parsing)\n- Return values must be JSON-serializable\n\n## Parameters\n\nR types map to Windmill types:\n- `numeric` → float/int\n- `character` → string\n- `logical` → bool (use `TRUE`/`FALSE`)\n- `list` → object/dict\n- `NULL` → null\n\nDefault values are inferred from the function signature:\n\n```r\nmain <- function(\n name, # required string\n count = 10, # optional int, default 10\n verbose = FALSE # optional bool, default FALSE\n) {\n # ...\n}\n```\n\n## Resources and Variables\n\nUse the built-in Windmill helpers (no import needed):\n\n```r\nmain <- function() {\n # Get a variable\n api_key <- get_variable(\"f/my_folder/api_key\")\n\n # Get a resource (returns a list)\n db <- get_resource(\"f/my_folder/postgres_config\")\n host <- db$host\n port <- db$port\n\n return(list(host = host, port = port))\n}\n```\n\n## Output\n\nReturn any JSON-serializable value from `main`. The return value becomes the step result:\n\n```r\nmain <- function(x) {\n # Return a scalar\n return(x + 1)\n\n # Or a list (becomes JSON object)\n return(list(result = x + 1, status = \"ok\"))\n}\n```\n\n## Annotations\n\nControl execution behavior with comment annotations:\n\n```r\n#renv_verbose = true # Show verbose renv output during resolution\n#renv_install_verbose = true # Show verbose output during package installation\n#sandbox = true # Run in nsjail sandbox (requires nsjail)\n```\n", "script.duckdb": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (duckdb)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# DuckDB\n\nArguments are defined with comments and used with `$name` syntax:\n\n```sql\n-- $name (text) = default\n-- $age (integer)\nSELECT * FROM users WHERE name = $name AND age > $age;\n```\n\n## Ducklake Integration\n\nAttach Ducklake for data lake operations:\n\n```sql\n-- Main ducklake\nATTACH 'ducklake' AS dl;\n\n-- Named ducklake\nATTACH 'ducklake://my_lake' AS dl;\n\n-- Then query\nSELECT * FROM dl.schema.table;\n```\n\n## External Database Connections\n\nConnect to external databases using resources:\n\n```sql\nATTACH '$res:path/to/resource' AS db (TYPE postgres);\nSELECT * FROM db.schema.table;\n```\n\n## S3 File Operations\n\nRead files from S3 storage:\n\n```sql\n-- Default storage\nSELECT * FROM read_csv('s3:///path/to/file.csv');\n\n-- Named storage\nSELECT * FROM read_csv('s3://storage_name/path/to/file.csv');\n\n-- Parquet files\nSELECT * FROM read_parquet('s3:///path/to/file.parquet');\n\n-- JSON files\nSELECT * FROM read_json('s3:///path/to/file.json');\n```\n\n### Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for it\nand binds the arg as the bare `s3://storage/key` URI, which DuckDB's reader\nfunctions consume directly:\n\n```sql\n-- $file (s3object)\nSELECT * FROM read_parquet($file);\n```\n\nWorks with any DuckDB reader: `read_csv($file)`, `read_json($file)`, etc.\n\n### Writing query results to S3\n\nDuckDB writes to S3 natively via `COPY ... TO`:\n\n```sql\nCOPY (SELECT * FROM users) TO 's3:///exports/users.parquet' (FORMAT PARQUET);\n```\n\nUse this instead of the `-- s3` streaming directive supported by the other SQL\ndialects — that directive is not available in DuckDB.\n", "script.bunnative": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (bunnative)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# TypeScript (Bun Native)\n\nNative TypeScript execution. Native scripts are Bun scripts that run on the native worker — a lightweight V8 isolate that exposes `fetch` and the JavaScript standard library — and can be heavily parallelized. Every script MUST start with `//native` on its first line so Windmill routes it to the native worker; without it the exact same script runs on the regular Bun worker. You may import npm packages and other Windmill scripts (e.g. `./helper.ts`) — imports are resolved and bundled just like a regular Bun script — as long as everything (your code and its dependencies) relies only on `fetch` and the standard library. Libraries that need Node/Bun runtime APIs (filesystem, `node:*` modules, child processes, native addons) will not work on the native worker; use the regular `bun` language for those.\n\n## Structure\n\nExport a single **async** function called `main`:\n\n```typescript\n//native\nexport async function main(param1: string, param2: number) {\n // Your code here\n return { result: param1, count: param2 };\n}\n```\n\nDo not call the main function.\n\n## Resource Types\n\nOn Windmill, credentials and configuration are stored in resources and passed as parameters to main.\n\nUse the `RT` namespace for resource types:\n\n```typescript\n//native\nexport async function main(stripe: RT.Stripe) {\n // stripe contains API key and config from the resource\n}\n```\n\nOnly use resource types if you need them to satisfy the instructions. Always use the RT namespace.\n\n## Imports\n\n**The constraint is the runtime, not the import list.** You may import npm packages and relative Windmill scripts; they are resolved and bundled exactly like a regular Bun script. But the native worker only provides `fetch` and the JavaScript standard library, so any imported code must work using only those. Anything requiring Node/Bun built-ins (`node:fs`, `child_process`, the `Bun` API, native modules) belongs in a regular `bun` script instead. Use the globally available `fetch` for HTTP:\n\n```typescript\n//native\nexport async function main(url: string) {\n const response = await fetch(url);\n return await response.json();\n}\n```\n\n## Pure computation: `//no_network`\n\nA native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. Without `//native` it means something else: the script must run in an nsjail sandbox (`//sandbox`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments:\n\n```typescript\n//native\n//no_network\nexport async function main(items: { price: number; qty: number }[]) {\n return items.reduce((sum, i) => sum + i.price * i.qty, 0);\n}\n```\n\n## Windmill Client\n\n`windmill-client` works on the native worker (its calls go over `fetch`), so use it as the **preferred way to talk to Windmill** — reading resources/variables/states, running scripts and flows, and the S3 helpers below (`loadS3File`, `loadS3FileStream`, `writeS3File`, `S3Object`). It handles auth, the workspace, and the base URL for you. Reserve raw `fetch` for calling *external* HTTP APIs that aren't Windmill.\n\nThe full `windmill-client` API reference (every exported function and its signature) is included below — consult it for the exact method instead of hand-rolling a `fetch` against the Windmill API.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```typescript\n//native\ntype Event = {\n kind:\n | \"webhook\"\n | \"http\"\n | \"websocket\"\n | \"kafka\"\n | \"email\"\n | \"nats\"\n | \"postgres\"\n | \"sqs\"\n | \"mqtt\"\n | \"amqp\"\n | \"gcp\"\n | \"azure\";\n body: any;\n headers: Record;\n query: Record;\n};\n\nexport async function preprocessor(event: Event) {\n return {\n param1: event.body.field1,\n param2: event.query.id,\n };\n}\n```\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations. The `wmill.S3Object` type covers both the `s3://storage/key` URI form (`s3:///key` for the workspace default storage) and the `{ s3, storage? }` record form — always use it instead of redefining your own.\n\n### Receiving an S3Object as a script parameter\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\nexport async function main(file: wmill.S3Object) {\n const content = await wmill.loadS3File(file);\n // ...\n}\n```\n\n### S3 operations\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\n// Load file content from S3\nconst content: Uint8Array = await wmill.loadS3File(s3object);\n\n// Load file as stream\nconst blob: Blob = await wmill.loadS3FileStream(s3object);\n\n// Write file to S3\nconst result: wmill.S3Object = await wmill.writeS3File(\n s3object, // Target path (or undefined to auto-generate)\n fileContent, // string or Blob\n s3ResourcePath // Optional: specific S3 resource to use\n);\n```\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable): Promise\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise\n\n/**\n * Run the deployed flow at `path` with some of its steps overridden, wait for it and return\n * its result. Meant for test scripts.\n * \n * Each entry of `steps` maps a step id to either:\n * - a value: the step is skipped and returns that value, or\n * - a function exported from the calling script's own file: the step runs that function\n * instead of its own code, with the step's inputs as arguments (matched by name).\n * \n * A step inside a subflow is named by the path of step ids to it, `\"sub:inner\"` for step `inner`\n * of the subflow that step `sub` calls. It applies to every call of that subflow made by the\n * tested flow and by the subflows it overrides; a subflow left as is still calls the deployed\n * one. Those subflows, and each one on the way to an override, run as you rather than as their\n * on-behalf-of identity. Result caching is off for the whole test run.\n * \n * The flow's preprocessor does not run: `args` are what the flow receives after it. A subflow\n * never runs its own preprocessor, in a test or not. AI agent\n * tools cannot be overridden; override the agent step instead.\n * \n * @example\n * export function fakeFetch(url: string) { return { status: 200 } }\n * export async function main() {\n * const result = await wmill.testFlow(\"f/flows/sync\", { user: \"a\" }, {\n * fetch_users: fakeFetch, // replaced logic\n * send_email: \"sent\", // mocked result\n * });\n * }\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param steps - Step id to mocked result, or to the function replacing the step\n * @param verbose - Enable verbose logging\n * @returns Flow execution result\n */\nasync testFlow(path: string, args: Record | null = null, steps: Record = {}, verbose: boolean = false): Promise\n\n/**\n * Like {@link testFlow}, but returns the job id without waiting for the flow to complete.\n */\nasync testFlowAsync(path: string, args: Record | null = null, steps: Record = {}): Promise\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step(name: string, fn: () => T | Promise,): Promise>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow(fn: (...args: any[]) => Promise): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel(items: T[], fn: (item: T) => PromiseLike | R, options?: { concurrency?: number },): Promise\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit,): SqlStatement\n", "script.dbt": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (dbt)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n", diff --git a/backend/windmill-worker/nsjail/install.r.config.proto b/backend/windmill-worker/nsjail/install.r.config.proto index e844b2e720..9be63d1b75 100644 --- a/backend/windmill-worker/nsjail/install.r.config.proto +++ b/backend/windmill-worker/nsjail/install.r.config.proto @@ -95,6 +95,13 @@ mount { rw: true } +mount { + src: "{LIB_ROOT}" + dst: "{LIB_ROOT}" + is_bind: true + mandatory: false +} + mount { src: "{PKG_DIR}" dst: "/install" diff --git a/backend/windmill-worker/src/r_executor.rs b/backend/windmill-worker/src/r_executor.rs index bcf94ba603..158474d330 100644 --- a/backend/windmill-worker/src/r_executor.rs +++ b/backend/windmill-worker/src/r_executor.rs @@ -49,6 +49,21 @@ lazy_static::lazy_static! { } const DEFAULT_CRAN_REPO_URL: &str = "https://cloud.r-project.org"; +const R_LIBS_SEPARATOR: &str = if cfg!(windows) { ";" } else { ":" }; + +/// A short key for the repository a package is installed from, without credentials, so a +/// rotated mirror password does not invalidate the cache. +fn repo_key(url: &str) -> String { + let url = match url::Url::parse(url) { + Ok(mut parsed) => { + let _ = parsed.set_username(""); + let _ = parsed.set_password(None); + parsed.to_string() + } + Err(_) => url.to_string(), + }; + calculate_hash(url.trim_end_matches('/'))[..12].to_string() +} /// The CRAN mirror configured for this workspace (or instance), if any. /// @@ -80,6 +95,106 @@ async fn configured_cran_repo_url(job_id: &Uuid, w_id: &str, conn: &Connection) Some(repo) } +/// The R a job runs under. A package built by one R `major.minor` is not loadable by another, +/// and renv picks the versions the running R supports, so this keys both the resolution cache +/// and the installed-package directories. +pub struct RRuntime { + pub rscript: String, + version: String, +} + +lazy_static::lazy_static! { + static ref R_VERSIONS: std::sync::Mutex> = Default::default(); +} + +impl RRuntime { + pub async fn detect() -> Result { + let rscript = if cfg!(windows) { + "Rscript.exe".to_string() + } else { + RSCRIPT_PATH.clone() + }; + Self::for_rscript(rscript).await + } + + async fn for_rscript(rscript: String) -> Result { + if let Some(version) = R_VERSIONS.lock().unwrap().get(&rscript) { + return Ok(RRuntime { rscript, version: version.clone() }); + } + let out = Command::new(&rscript) + .args([ + "--vanilla", + "-e", + r#"cat("\n", R.version$major, ".", R.version$minor, "\n", sep = "")"#, + ]) + .env_clear() + .env("PATH", PATH_ENV.as_str()) + .envs(WIN_ENVS.to_vec()) + .stdin(Stdio::null()) + .output() + .await + .map_err(|e| Error::ExecutionErr(format!("could not run {rscript}: {e}")))?; + let stdout = String::from_utf8_lossy(&out.stdout); + let version = stdout.trim().lines().last().unwrap_or_default().to_string(); + let well_formed = version.split('.').count() >= 2 + && version + .split('.') + .all(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())); + if !out.status.success() || !well_formed { + return Err(Error::ExecutionErr(format!( + "could not read the R version of {rscript}: {}", + String::from_utf8_lossy(&out.stderr) + ))); + } + R_VERSIONS + .lock() + .unwrap() + .insert(rscript.clone(), version.clone()); + Ok(RRuntime { rscript, version }) + } + + /// `major.minor`, the granularity at which R requires packages to be reinstalled. + pub fn minor(&self) -> String { + self.version.split('.').take(2).join(".") + } +} + +/// The packages a script needs, as the resolution cache knows them: what the parser finds plus +/// jsonlite, which the wrapper uses to read arguments and write the result. renv is left out: +/// it ships with the image and locks never install it. +fn required_packages(inner_content: &str) -> Result, Error> { + let mut packages = parse_r_requirements(inner_content)? + .lines() + .filter(|p| *p != "renv") + .map(str::to_string) + .collect_vec(); + if !packages.iter().any(|p| p == "jsonlite") { + packages.push("jsonlite".to_string()); + packages.sort(); + } + Ok(packages) +} + +/// The `major.minor` of the R a lock was resolved under. +fn lock_r_minor(lockfile: &str) -> Option { + let lock: serde_json::Value = serde_json::from_str(lockfile).ok()?; + let version = lock.get("R")?.get("Version")?.as_str()?; + Some(version.split('.').take(2).join(".")) +} + +/// The packages of `required` that `lockfile` does not list. +fn missing_from_lock(lockfile: &str, required: &[String]) -> Result, Error> { + let locked = parse_renv_lock(lockfile)? + .into_iter() + .map(|p| p.name) + .collect::>(); + Ok(required + .iter() + .filter(|p| !locked.contains(*p)) + .cloned() + .collect()) +} + const NSJAIL_CONFIG_RUN_R_CONTENT: &str = include_str!("../nsjail/run.r.config.proto"); const NSJAIL_CONFIG_INSTALL_R_CONTENT: &str = include_str!("../nsjail/install.r.config.proto"); @@ -123,33 +238,96 @@ pub async fn handle_r_job<'a>( let jailed = !cfg!(windows) && (is_sandboxing_enabled() || annotation.sandbox); check_no_network_jailed(annotation.no_network, jailed)?; + let runtime = RRuntime::detect().await?; + // --- Prepare --- { prepare(&args).await?; } - // --- Resolve lockfile --- - let lockfile = resolve( - &args.job.id, - args.inner_content, - args.mem_peak, - args.canceled_by, - args.job_dir, - args.conn, - args.worker_name, - &args.job.workspace_id, - annotation.renv_verbose, - ) - .await?; + // --- Lockfile: the deployed one, else resolve --- + // A lock that misses a package the code needs is resolved again rather than trusted: a lock + // stored by a dependency job that scanned no code holds only renv, and a preview can carry + // the lock of code since edited. + let deployed_lock = match args + .requirements_o + .map(|l| l.trim()) + .filter(|l| !l.is_empty()) + { + Some(lock) => { + let required = required_packages(args.inner_content)?; + match missing_from_lock(lock, &required) { + Ok(missing) if missing.is_empty() => { + if let Some(locked_r) = lock_r_minor(lock).filter(|v| *v != runtime.minor()) { + append_logs( + &args.job.id, + &args.job.workspace_id, + format!( + "\nthe script's lock was resolved under R {locked_r} and runs under R {}: its versions are installed as locked\n", + runtime.minor() + ), + args.conn, + ) + .await; + } + Some(lock.to_string()) + } + Ok(missing) => { + append_logs( + &args.job.id, + &args.job.workspace_id, + format!( + "\nthe script's lock does not cover {}: resolving again. Redeploy the script to store a complete lock.\n", + missing.join(", ") + ), + args.conn, + ) + .await; + None + } + Err(e) => { + append_logs( + &args.job.id, + &args.job.workspace_id, + format!("\nthe script's lock is not a valid renv.lock ({e}): resolving again.\n"), + args.conn, + ) + .await; + None + } + } + } + None => None, + }; + let lockfile = match deployed_lock { + Some(lock) => lock, + None => { + resolve( + &args.job.id, + args.inner_content, + args.mem_peak, + args.canceled_by, + args.job_dir, + args.conn, + args.worker_name, + &args.job.workspace_id, + annotation.renv_verbose, + &runtime, + ) + .await? + } + }; // --- Install --- - let lib_path = if !lockfile.is_empty() { + let r_libs_user = if !lockfile.is_empty() { Some( install( &mut args, &lockfile, annotation.renv_verbose, annotation.renv_install_verbose, + &runtime, ) - .await?, + .await? + .join(R_LIBS_SEPARATOR), ) } else { None @@ -158,9 +336,10 @@ pub async fn handle_r_job<'a>( { run( &mut args, - lib_path.as_deref(), + r_libs_user.as_deref(), jailed, annotation.no_network, + &runtime, ) .await?; } @@ -228,26 +407,20 @@ pub async fn resolve<'a>( worker_name: &str, w_id: &str, verbose: bool, + runtime: &RRuntime, ) -> Result { - let mut packages = parse_r_requirements(inner_content)?; - - // jsonlite is always needed by the wrapper for JSON arg parsing and result serialization - let has_jsonlite = packages.lines().any(|l| l.trim() == "jsonlite"); - if !has_jsonlite { - if packages.is_empty() { - packages = "jsonlite".to_string(); - } else { - packages.push_str("\njsonlite"); - } - } + let required = required_packages(inner_content)?; + let packages = required.join("\n"); let custom_repo = configured_cran_repo_url(job_id, w_id, conn).await; - // A mirror resolves its own versions, so it must not share a cache entry with CRAN. - let req_hash = match &custom_repo { - Some(repo) => format!("r-{}", calculate_hash(&format!("{packages}\n#repo:{repo}"))), - None => format!("r-{}", calculate_hash(&packages)), - }; + // A mirror resolves its own versions, and renv picks versions the running R supports, so + // neither may share a cache entry with another. + let mut key = format!("{packages}\n#r:{}", runtime.minor()); + if let Some(repo) = &custom_repo { + key.push_str(&format!("\n#repo:{repo}")); + } + let req_hash = format!("r-{}", calculate_hash(&key)); let repo_url = custom_repo.as_deref().unwrap_or(DEFAULT_CRAN_REPO_URL); if let Some(db) = conn.as_sql() { if let Some(cached) = sqlx::query_scalar!( @@ -269,9 +442,16 @@ pub async fn resolve<'a>( ) .await; - // main.r is already written by prepare() and contains the library() calls. - // renv will scan it to detect dependencies. + // renv resolves what it finds scanning this directory, so it holds the script and the + // wrapper's own dependency, and nothing else that would depend on the caller. // Disable renv's own package cache — Windmill manages its own install cache. + let resolve_dir = format!("{job_dir}/r_resolve"); + fs::create_dir_all(&resolve_dir).await?; + write_file( + &resolve_dir, + "main.r", + &format!("{inner_content}\n\nlibrary(jsonlite)\n"), + )?; let resolve_script = format!( r#"options( repos = c(CRAN = "{repo_url}"), @@ -289,18 +469,13 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) repo_url = escape_r_double_quoted(repo_url), ); - let mut file = File::create(format!("{}/resolve.r", job_dir)).await?; - file.write_all(resolve_script.as_bytes()).await?; + write_file(&resolve_dir, "resolve.r", &resolve_script)?; let child = { let renv_root = format!("{}/renv", *R_CACHE_DIR); - let rscript_executable = if cfg!(windows) { - "Rscript.exe" - } else { - RSCRIPT_PATH.as_str() - }; + let rscript_executable = runtime.rscript.as_str(); let mut cmd = Command::new(rscript_executable); - cmd.current_dir(job_dir) + cmd.current_dir(&resolve_dir) .env("PATH", PATH_ENV.as_str()) .env("RENV_PATHS_ROOT", &renv_root) .arg("resolve.r") @@ -326,7 +501,7 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) ) .await?; - let lock_path = format!("{}/renv.lock", job_dir); + let lock_path = format!("{}/renv.lock", resolve_dir); let mut lock_file = File::open(&lock_path).await?; let mut lock = String::new(); lock_file.read_to_string(&mut lock).await?; @@ -334,8 +509,21 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) lock = strip_repo_credentials(lock); } - // Cache the lockfile - if let Some(db) = conn.as_sql() { + // A lock without a package the script needs must not be cached: every script with the same + // package list would be served it until the entry expires. + let missing = missing_from_lock(&lock, &required)?; + if !missing.is_empty() { + append_logs( + job_id, + w_id, + format!( + "renv did not resolve {}: the lock is not cached\n", + missing.join(", ") + ), + conn, + ) + .await; + } else if let Some(db) = conn.as_sql() { sqlx::query!( "INSERT INTO pip_resolution_cache (hash, lockfile, expiration) VALUES ($1, $2, now() + ('3 days')::interval) ON CONFLICT (hash) DO UPDATE SET lockfile = EXCLUDED.lockfile", req_hash, @@ -504,42 +692,71 @@ fn parse_renv_lock(lockfile: &str) -> Result, Error> { Ok(result) } +/// Installs the lock's packages and returns the directories to put on `R_LIBS_USER`: one per +/// package, keyed by its version and the R `major.minor`, so that versions and R installs +/// sharing a worker cache never see each other's builds. async fn install<'a>( args: &mut JobHandlerInput<'a>, lockfile: &str, verbose: bool, install_verbose: bool, -) -> Result { - let lib_path = format!("{}/r_site_library", *R_CACHE_DIR); - fs::create_dir_all(&lib_path).await?; + runtime: &RRuntime, +) -> Result, Error> { + let lib_root = format!("{}/r_site_library/{}", *R_CACHE_DIR, runtime.minor()); + fs::create_dir_all(&lib_root).await?; let packages = parse_renv_lock(lockfile)?; - if packages.is_empty() { - return Ok(lib_path); - } // The configured mirror wins over the URL recorded in the lockfile, so a lockfile // resolved against CRAN still installs on an instance that can only reach the mirror. let custom_repo = configured_cran_repo_url(&args.job.id, &args.job.workspace_id, args.conn).await; + let repo_of = |p: &RenvPackage| custom_repo.clone().unwrap_or_else(|| p.repo_url.clone()); + // Every workspace shares these directories, and a lock or a workspace setting names the + // repository, so a build is only ever reused for the repository it came from. + let outer_dir = |p: &RenvPackage| { + format!( + "{lib_root}/{}/{}_{}_outer", + repo_key(&repo_of(p)), + p.name, + p.version + ) + }; + let lib_dirs = packages.iter().map(|p| outer_dir(p)).collect_vec(); + if packages.is_empty() { + return Ok(lib_dirs); + } #[derive(Clone, Debug)] struct RPackagePayload { pkg: String, version: String, repo_url: String, + /// The lock's other packages, which a source build loads while installing. + other_libs: Vec, } // Build dependency graph for topological layering let mut graph = DependencyGraph::new(); for renv_pkg in &packages { - let handle = format!("{}-{}", renv_pkg.name, renv_pkg.version); + let handle = format!( + "{}-{}-r{}-{}", + renv_pkg.name, + renv_pkg.version, + runtime.minor(), + repo_key(&repo_of(renv_pkg)) + ); // renv uses staged installation: it builds to a temp dir then rename()s onto // the target. If the target is a bind mount point, rename fails with // "target file already exists". We work around this by mounting the parent // (wrapper) dir at /install so renv can freely create /install/{pkg}/ via rename. - let pkg_outer = format!("{}/{}_outer", lib_path, renv_pkg.name); + let pkg_outer = outer_dir(renv_pkg); let path = format!("{}/{}", pkg_outer, renv_pkg.name); + let other_libs = lib_dirs + .iter() + .filter(|d| **d != pkg_outer) + .cloned() + .collect_vec(); graph.insert( renv_pkg.name.clone(), RequiredDependency { @@ -549,9 +766,8 @@ async fn install<'a>( custom_payload: RPackagePayload { pkg: renv_pkg.name.clone(), version: renv_pkg.version.clone(), - repo_url: custom_repo - .clone() - .unwrap_or_else(|| renv_pkg.repo_url.clone()), + repo_url: repo_of(renv_pkg), + other_libs, }, }, renv_pkg.dependencies.clone(), @@ -560,6 +776,8 @@ async fn install<'a>( let jailed = !cfg!(windows) && is_sandboxing_enabled(); let job_dir = args.job_dir.to_owned(); + let rscript = runtime.rscript.clone(); + let lib_root_c = lib_root.clone(); par_install_language_dependencies_seq( InstallDeps::Layered(graph), @@ -568,12 +786,14 @@ async fn install<'a>( false, *R_CONCURRENT_DOWNLOADS, move |dependency| { - let lib_path_c = lib_path.clone(); let job_dir = job_dir.clone(); - let pkg_name = &dependency.custom_payload.pkg; // pkg_outer is the wrapper dir mounted rw at /install inside nsjail. // renv creates /install/{pkg}/ inside it via staged rename. - let pkg_outer = format!("{}/{}_outer", lib_path_c, pkg_name); + let pkg_outer = dependency + .path + .rsplit_once('/') + .map(|(outer, _)| outer.to_string()) + .unwrap_or_default(); std::fs::create_dir_all(&pkg_outer)?; let mut cmd = if jailed { @@ -581,6 +801,7 @@ async fn install<'a>( let config_content = NSJAIL_CONFIG_INSTALL_R_CONTENT .replace("{JOB_DIR}", &job_dir) .replace("{PKG_DIR}", &pkg_outer) + .replace("{LIB_ROOT}", &lib_root_c) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) .replace("{TRACING_PROXY_CA_CERT_PATH}", &*TRACING_PROXY_CA_CERT_PATH) .replace("#{DEV}", DEV_CONF_NSJAIL); @@ -590,19 +811,10 @@ async fn install<'a>( &config_content, )?; let mut cmd = Command::new(NSJAIL_PATH.as_str()); - cmd.args(vec![ - "--config", - &nsjail_proto, - "--", - RSCRIPT_PATH.as_str(), - ]); + cmd.args(vec!["--config", &nsjail_proto, "--", rscript.as_str()]); cmd } else { - Command::new(if cfg!(windows) { - "Rscript.exe" - } else { - RSCRIPT_PATH.as_str() - }) + Command::new(rscript.as_str()) }; let verbose_r = if verbose { "TRUE" } else { "FALSE" }; @@ -619,12 +831,20 @@ async fn install<'a>( .args(&[ "-e", &format!( - r#"options(repos = c(CRAN = "{repo}"), renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = "{lib}", dependencies = FALSE)"#, + r#"options(repos = c(CRAN = "{repo}"), renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = c("{lib}"{other_libs}), dependencies = FALSE)"#, verbose_r = verbose_r, install_verbose_r = install_verbose_r, pkg = escape_r_double_quoted(&dependency.custom_payload.pkg), version = escape_r_double_quoted(&dependency.custom_payload.version), lib = escape_r_double_quoted(&install_lib), + // Installs into the first library; a source build loads the package's + // dependencies from the others, which earlier layers installed. + other_libs = dependency + .custom_payload + .other_libs + .iter() + .map(|d| format!(", \"{}\"", escape_r_double_quoted(d))) + .join(""), repo = escape_r_double_quoted(&dependency.custom_payload.repo_url), ), // install.packages fallback (no version pinning): @@ -651,23 +871,7 @@ async fn install<'a>( ) .await?; - Ok(format!("{}/r_site_library", *R_CACHE_DIR)) -} - -/// Build R_LIBS_USER from lib_path by listing *_outer subdirs. -/// Each package wrapper dir ({pkg}_outer) is added so R finds {pkg}_outer/{pkg}/DESCRIPTION. -fn r_libs_user(lib_path: &str) -> String { - std::fs::read_dir(lib_path) - .into_iter() - .flatten() - .filter_map(|e| e.ok()) - .filter(|e| { - e.file_type().map(|t| t.is_dir()).unwrap_or(false) - && e.file_name().to_string_lossy().ends_with("_outer") - }) - .map(|e| e.path().to_string_lossy().to_string()) - .collect::>() - .join(":") + Ok(lib_dirs) } async fn run<'a>( @@ -686,9 +890,10 @@ async fn run<'a>( parent_runnable_path, .. }: &mut JobHandlerInput<'a>, - lib_path: Option<&str>, + r_libs_user: Option<&str>, nsjail: bool, no_network: bool, + runtime: &RRuntime, ) -> Result<(), Error> { let mut reserved_variables = get_reserved_variables(job, &client.token, conn, parent_runnable_path.clone()).await?; @@ -728,14 +933,14 @@ async fn run<'a>( ) .await?, ); - if let Some(lp) = lib_path { - cmd.env("R_LIBS_USER", r_libs_user(lp)); + if let Some(lp) = r_libs_user { + cmd.env("R_LIBS_USER", lp); } cmd.args(vec![ "--config", "run.config.proto", "--", - RSCRIPT_PATH.as_str(), + runtime.rscript.as_str(), "main.r", ]); cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); @@ -774,11 +979,7 @@ async fn run<'a>( ) .await; - let rscript_executable = if cfg!(windows) { - "Rscript.exe" - } else { - RSCRIPT_PATH.as_str() - }; + let rscript_executable = runtime.rscript.as_str(); let args = vec!["main.r"]; let mut cmd = build_command_with_isolation(rscript_executable, &args); @@ -804,8 +1005,8 @@ async fn run<'a>( .await?, ) .envs(envs); - if let Some(lp) = lib_path { - cmd.env("R_LIBS_USER", r_libs_user(lp)); + if let Some(lp) = r_libs_user { + cmd.env("R_LIBS_USER", lp); } cmd.stdin(Stdio::null()) @@ -877,9 +1078,22 @@ tryCatch({{ #[cfg(test)] mod tests { use super::{ - escape_r_double_quoted, parse_renv_lock, strip_repo_credentials, validate_renv_package, + escape_r_double_quoted, missing_from_lock, parse_renv_lock, required_packages, + strip_repo_credentials, validate_renv_package, }; + #[test] + fn test_a_lock_holding_only_renv_covers_nothing() { + let required = + required_packages("library(R6)\nx <- renv::status\nmain <- function() 1").unwrap(); + assert_eq!(required, vec!["R6", "jsonlite"]); + let renv_only = r#"{"Packages": {"renv": {"Package": "renv", "Version": "1.2.0"}}}"#; + assert_eq!( + missing_from_lock(renv_only, &required).unwrap(), + vec!["R6", "jsonlite"] + ); + } + #[test] fn test_validate_renv_package_accepts_real() { for (n, v) in [ diff --git a/backend/windmill-worker/src/worker_lockfiles.rs b/backend/windmill-worker/src/worker_lockfiles.rs index 1dead293ea..2b7a82558a 100644 --- a/backend/windmill-worker/src/worker_lockfiles.rs +++ b/backend/windmill-worker/src/worker_lockfiles.rs @@ -3807,6 +3807,7 @@ async fn capture_dependency_job( worker_name, w_id, false, + &r_executor::RRuntime::detect().await?, ) .await? } diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 0e65b3a283..1adc007271 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -5530,7 +5530,8 @@ main <- function(x, name = "default", flag = TRUE) { **Important:** - The \`main\` function is required -- Use \`library()\` to load packages — they are resolved and installed automatically +- Use \`library()\` to load packages — they are resolved and installed automatically, as are packages used through \`pkg::fun()\`, \`require()\` and \`requireNamespace()\` +- A deployed script runs with the package versions locked when it was deployed - \`jsonlite\` is always available (used internally for argument parsing) - Return values must be JSON-serializable diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 8ad01da379..ca8c32952b 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -6260,7 +6260,8 @@ main <- function(x, name = "default", flag = TRUE) { **Important:** - The \`main\` function is required -- Use \`library()\` to load packages — they are resolved and installed automatically +- Use \`library()\` to load packages — they are resolved and installed automatically, as are packages used through \`pkg::fun()\`, \`require()\` and \`requireNamespace()\` +- A deployed script runs with the package versions locked when it was deployed - \`jsonlite\` is always available (used internally for argument parsing) - Return values must be JSON-serializable diff --git a/system_prompts/auto-generated/script.md b/system_prompts/auto-generated/script.md index b768d2645a..7f0d63146c 100644 --- a/system_prompts/auto-generated/script.md +++ b/system_prompts/auto-generated/script.md @@ -1254,7 +1254,8 @@ main <- function(x, name = "default", flag = TRUE) { **Important:** - The `main` function is required -- Use `library()` to load packages — they are resolved and installed automatically +- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()` +- A deployed script runs with the package versions locked when it was deployed - `jsonlite` is always available (used internally for argument parsing) - Return values must be JSON-serializable diff --git a/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md b/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md index 636bc100e3..7fd8e9a0cf 100644 --- a/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md @@ -94,7 +94,8 @@ main <- function(x, name = "default", flag = TRUE) { **Important:** - The `main` function is required -- Use `library()` to load packages — they are resolved and installed automatically +- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()` +- A deployed script runs with the package versions locked when it was deployed - `jsonlite` is always available (used internally for argument parsing) - Return values must be JSON-serializable diff --git a/system_prompts/languages/rlang.md b/system_prompts/languages/rlang.md index 7ae3b34525..aa09acf0ad 100644 --- a/system_prompts/languages/rlang.md +++ b/system_prompts/languages/rlang.md @@ -17,7 +17,8 @@ main <- function(x, name = "default", flag = TRUE) { **Important:** - The `main` function is required -- Use `library()` to load packages — they are resolved and installed automatically +- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()` +- A deployed script runs with the package versions locked when it was deployed - `jsonlite` is always available (used internally for argument parsing) - Return values must be JSON-serializable