From 3125e6dac0010b57750e26eb5e699238689bf11f Mon Sep 17 00:00:00 2001 From: hugocasa Date: Tue, 3 Nov 2026 11:49:17 +0100 Subject: [PATCH 01/14] feat: let the ai session test-run hub scripts (#12170) * feat: let the ai session run and test-run hub scripts Co-Authored-By: Claude Opus 5.5 * fix: keep hub scripts to test runs in the ai session Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../src/ai_session_tools/gen/tools.json | 2 +- .../windmill-api/src/ai_session_tools/runs.rs | 6 ++-- .../src/ai_session_tools/workspace.rs | 28 +++++++++++++++++-- .../components/copilot/chat/global/core.ts | 6 +++- 4 files changed, 34 insertions(+), 8 deletions(-) diff --git a/backend/windmill-api/src/ai_session_tools/gen/tools.json b/backend/windmill-api/src/ai_session_tools/gen/tools.json index 6227f0c11d..81b779088f 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/tools.json +++ b/backend/windmill-api/src/ai_session_tools/gen/tools.json @@ -1019,7 +1019,7 @@ "type": "object", "properties": { "path": { - "description": "Workspace path of the script to test.", + "description": "Workspace path of the script to test, or a hub/// path from search_hub_scripts to try a hub script.", "type": "string" }, "args": { diff --git a/backend/windmill-api/src/ai_session_tools/runs.rs b/backend/windmill-api/src/ai_session_tools/runs.rs index 99b6a653ec..c3df5f6008 100644 --- a/backend/windmill-api/src/ai_session_tools/runs.rs +++ b/backend/windmill-api/src/ai_session_tools/runs.rs @@ -8,7 +8,7 @@ use serde_json::{json, Map, Value}; use super::chat::{Effect, RunPhase}; use super::workspace::{ - api_message, get_draft, infer_script_schema, load_flow, load_script, path_enc, + api_message, get_draft, infer_script_schema, load_flow, load_script_to_run, path_enc, }; use super::{enc, js_head, js_len, js_tail, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult}; @@ -943,7 +943,7 @@ fn form_keys(schema: Option<&Value>) -> Vec { } async fn resolve_test_script(ctx: &Ctx<'_>, path: &str) -> Result { - let script = load_script(ctx, path).await?; + let script = load_script_to_run(ctx, path).await?; Ok(Resolved { schema: script.schema, code: Some(script.content.clone()), @@ -1643,7 +1643,7 @@ async fn resolve_step(ctx: &Ctx<'_>, path: &str, step_id: &str) -> Result { - let loaded = load_script(ctx, &target).await?; + let loaded = load_script_to_run(ctx, &target).await?; (loaded.content, loaded.language, loaded.schema) } }; diff --git a/backend/windmill-api/src/ai_session_tools/workspace.rs b/backend/windmill-api/src/ai_session_tools/workspace.rs index 80e5da2041..f75146b92c 100644 --- a/backend/windmill-api/src/ai_session_tools/workspace.rs +++ b/backend/windmill-api/src/ai_session_tools/workspace.rs @@ -982,6 +982,30 @@ pub(super) struct LoadedScript { pub schema: Option, } +/// A hub script, by its `hub///` path. Hub scripts live outside the +/// workspace: they have no draft and no workspace row. +pub(super) async fn get_hub_script(ctx: &Ctx<'_>, path: &str) -> Result { + ctx.get(&format!("/scripts/hub/get_full/{}", path_enc(path))) + .await +} + +/// The script a test run executes: `load_script`, or a hub script as published. Only test +/// runs take a hub path: an edit would save a draft no run reads, and `run_script` stays +/// limited to deployed workspace scripts, which is all a read-and-run session may run. +pub(super) async fn load_script_to_run(ctx: &Ctx<'_>, path: &str) -> Result { + if !path.starts_with("hub/") { + return load_script(ctx, path).await; + } + let script = get_hub_script(ctx, path).await?; + let text = |key: &str| script.get(key).and_then(Value::as_str).map(String::from); + Ok(LoadedScript { + content: text("content").unwrap_or_default(), + language: text("language").unwrap_or_default(), + summary: text("summary"), + schema: non_null(script.get("schema")).cloned(), + }) +} + pub(super) async fn load_script(ctx: &Ctx<'_>, path: &str) -> Result { let text = |value: &Value, key: &str| value.get(key).and_then(Value::as_str).map(String::from); if let Some((item, _)) = get_draft_item(ctx, "script", path, None).await? { @@ -1664,9 +1688,7 @@ async fn read_workspace_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { let item = match item_type { "script" if hub => { - let script = ctx - .get(&format!("/scripts/hub/get_full/{}", path_enc(path))) - .await?; + let script = get_hub_script(ctx, path).await?; let mut row = script.clone(); row["path"] = json!(path); let mut item = with_value( diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 9943367090..3a8882f8c5 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -853,7 +853,11 @@ function waitSecondsToDetachMs(waitSeconds: number | undefined): number | undefi } const testRunScriptSchema = z.object({ - path: z.string().describe('Workspace path of the script to test.'), + path: z + .string() + .describe( + 'Workspace path of the script to test, or a hub/// path from search_hub_scripts to try a hub script.' + ), args: testRunArgsSchema, background: backgroundArgSchema, wait_seconds: waitSecondsArgSchema From c05febcefafbe70fe2759fba9c920dbc0b413686 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 3 Nov 2026 12:37:24 +0100 Subject: [PATCH 02/14] fix: fall back to getAll for set-cookie in the pages preview proxy The Pages function runs without a compatibility date, where Headers has no getSetCookie, so every proxied API call failed with a 500. Co-Authored-By: Claude Opus 5.5 --- functions/api/[[path]].ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/functions/api/[[path]].ts b/functions/api/[[path]].ts index c9c378ee03..97f47a1276 100644 --- a/functions/api/[[path]].ts +++ b/functions/api/[[path]].ts @@ -34,10 +34,19 @@ export async function onRequest(context) { // `windmill.dev`) does not match this host, and a browser drops a cookie whose Domain // does not match. Reading them joined (`headers.get`) would merge the session cookie with // the `wm_session` hint set beside it, Domain included. - const setCookies = res.headers.getSetCookie(); - newResponse.headers.delete("set-cookie"); - for (const c of setCookies) { - newResponse.headers.append("set-cookie", c.replace(/;\s*Domain=[^;]*/gi, "")); + // Pages runs without a compatibility date, where `getSetCookie` does not exist; its + // `getAll` returns the same list there, and only for `set-cookie`. + const setCookies: string[] | undefined = + typeof res.headers.getSetCookie === "function" + ? res.headers.getSetCookie() + : typeof res.headers.getAll === "function" + ? res.headers.getAll("set-cookie") + : undefined; + if (setCookies) { + newResponse.headers.delete("set-cookie"); + for (const c of setCookies) { + newResponse.headers.append("set-cookie", c.replace(/;\s*Domain=[^;]*/gi, "")); + } } newResponse.headers.set("Cross-Origin-Resource-Policy", "cross-origin"); From df2a631e77c901bf338646ec1f25051fa57cdf2b Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 3 Nov 2026 13:12:21 +0100 Subject: [PATCH 03/14] fix: refetch persisted resources when the cache identity becomes known (#12176) A response is tagged with the cache keys of its request. When the user or the session they hold is confirmed after a persisted resource's first request (the first load of a workspace), the keys shown change and the untagged response is hidden, with nothing refetching: Home's recent runs, folder names, usernames, pipeline folders and owner counts stayed empty until their arguments changed. The identity is now part of the resource's source, and a session confirmation bumps it the way a user change does. Co-authored-by: Claude Opus 5.5 --- frontend/src/lib/lastSession.ts | 18 +++++++++++++++--- frontend/src/lib/persistedCache.svelte.ts | 14 +++++++++++--- frontend/src/lib/persistedResource.svelte.ts | 6 +++++- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/frontend/src/lib/lastSession.ts b/frontend/src/lib/lastSession.ts index fc5f5cf279..7e9779ddd3 100644 --- a/frontend/src/lib/lastSession.ts +++ b/frontend/src/lib/lastSession.ts @@ -27,6 +27,18 @@ export function readSessionHint(cookies?: string): string | undefined { // it renders as. Another tab logging in swaps the session under this one, whose user stays // the old one until its next `whoami`: until then, nothing may be read or written as them. let confirmedHint: string | undefined +const confirmationListeners = new Set<() => void>() + +function setConfirmedHint(hint: string | undefined) { + if (hint === confirmedHint) return + confirmedHint = hint + for (const cb of confirmationListeners) cb() +} + +/** Called whenever the session this tab's user is confirmed under changes. */ +export function onSessionConfirmationChange(cb: () => void): void { + confirmationListeners.add(cb) +} /** Whether the session the browser holds is still the one this tab's user was confirmed under. */ export function sessionStillConfirmed(): boolean { @@ -50,7 +62,7 @@ function currentLastUser(): UserExt | undefined { export function optimisticUser(workspace: string): UserExt | undefined { const user = currentLastUser() if (user?.workspace_id !== workspace) return undefined - confirmedHint = readSessionHint() + setConfirmedHint(readSessionHint()) return user } @@ -68,7 +80,7 @@ export function rememberUser(user: UserExt, sentWith: string | undefined): void try { const hint = readSessionHint() // Who answered is only known for the session the request went out with. - confirmedHint = hint === sentWith ? hint : undefined + setConfirmedHint(hint === sentWith ? hint : undefined) if (hint && hint === sentWith) localStorage.setItem(KEY, JSON.stringify({ hint, user } satisfies LastSession)) else localStorage.removeItem(KEY) @@ -76,7 +88,7 @@ export function rememberUser(user: UserExt, sentWith: string | undefined): void } export function forgetLastSession(): void { - confirmedHint = undefined + setConfirmedHint(undefined) try { localStorage.removeItem(KEY) } catch {} diff --git a/frontend/src/lib/persistedCache.svelte.ts b/frontend/src/lib/persistedCache.svelte.ts index ce4480be56..2414a8d74c 100644 --- a/frontend/src/lib/persistedCache.svelte.ts +++ b/frontend/src/lib/persistedCache.svelte.ts @@ -6,7 +6,11 @@ import { OpenAPI } from '$lib/gen' import { userStore } from '$lib/stores' import { userScopedDb } from '$lib/userScopedDb' import { getCurrentUserEmail, onUserChange } from '$lib/userScopedStorage' -import { rememberedEmail, sessionStillConfirmed } from '$lib/lastSession' +import { + onSessionConfirmationChange, + rememberedEmail, + sessionStillConfirmed +} from '$lib/lastSession' // Last-known API responses, kept so a page can paint them before its requests return. Every // row in them was filtered by row-level security for one user, so an entry is only ever served @@ -284,7 +288,9 @@ if (BROWSER) { readSnapshot() // Loads the whole (bounded) store into memory once the user is known, and keeps only what // belongs to them: the snapshot's entries for the same identity survive. - onUserChange(() => { + // The identity is known once both the user and the session they hold are: either can come + // second, and a key derived before must follow. + const onIdentityChange = () => { userTick++ // No user yet (the call at registration, as the app boots): nothing can be read without // an identity, and the snapshot just loaded is waiting for its user. Logout clears memory @@ -294,5 +300,7 @@ if (BROWSER) { const mine = `[${JSON.stringify(identity)},` for (const key of [...memory.keys()]) if (!key.startsWith(mine)) memory.delete(key) void hydrate() - }) + } + onUserChange(onIdentityChange) + onSessionConfirmationChange(onIdentityChange) } diff --git a/frontend/src/lib/persistedResource.svelte.ts b/frontend/src/lib/persistedResource.svelte.ts index ffef3b349e..582687a043 100644 --- a/frontend/src/lib/persistedResource.svelte.ts +++ b/frontend/src/lib/persistedResource.svelte.ts @@ -67,7 +67,11 @@ export function persistedResource( let latest = 0 let inFlight = $state(false) let error = $state(undefined) - const res = resource>(source, async (args) => { + // The identity is a source too: a response is tagged with the keys of its request, and once + // the identity changes no response tagged before matches the keys shown, so without a new + // request nothing would be shown until the arguments next change. + const sourceWithIdentity = () => ({ args: source(), identity: cacheIdentity() }) + const res = resource(sourceWithIdentity, async ({ args }): Promise> => { const id = ++latest inFlight = true try { From 795ded9d19ff768f0113d82ae3853db61812f7bf Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 3 Nov 2026 13:29:08 +0100 Subject: [PATCH 04/14] fix: make home's failed-runs ask ai clickable, add failed filter and runs link (#12174) * fix: make the home failed-runs count's ask ai reachable, add a failed filter and runs link Co-Authored-By: Claude Opus 5.5 * fix: clear the failed filter with its last failure, keep the window tooltip Co-Authored-By: Claude Opus 5.5 * refactor: use design-system buttons in the failed-runs menu Co-Authored-By: Claude Opus 5.5 * fix: fall back to getAll for set-cookie in the pages preview proxy The Pages function runs without a compatibility date, where Headers has no getSetCookie, so every proxied API call failed with a 500. Co-Authored-By: Claude Opus 5.5 * refactor: use a design-system button for the header's failed runs link Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../home/RecentRunsHeaderStatus.svelte | 13 ++- .../components/home/RecentRunsPanel.svelte | 101 ++++++++++++++---- .../lib/components/home/recentRuns.svelte.ts | 15 +++ 3 files changed, 108 insertions(+), 21 deletions(-) diff --git a/frontend/src/lib/components/home/RecentRunsHeaderStatus.svelte b/frontend/src/lib/components/home/RecentRunsHeaderStatus.svelte index c2f24df00b..4bcb31ed93 100644 --- a/frontend/src/lib/components/home/RecentRunsHeaderStatus.svelte +++ b/frontend/src/lib/components/home/RecentRunsHeaderStatus.svelte @@ -6,6 +6,7 @@ import { allRunsHref, askAI, + failedRunsHref, canAskAI, collisionPrefixes, itemKey, @@ -154,7 +155,7 @@ {/if}
@@ -165,6 +166,16 @@ All runs + {#if data && data.failed_runs > 0} + + {/if} {#if onShowPanel}
- {/if} - + + + {#snippet trigger()} + {data.failed_runs} failed + {/snippet} + {#snippet content()} +
+ + {#if failedItems.length > 0} + + {/if} + {#if canAskAI() && failing.length > 0} + + {/if} + +
+ {/snippet} +
{:else} - {totalLabel(data)} + {totalLabel(data)} {/if} - · {windowText} + +  · {windowText} {/if} @@ -102,7 +163,7 @@ {:else if data}
- {#each data.items as item (itemKey(item))} + {#each shownItems as item (itemKey(item))} { + const { minTs, maxTs } = t.computeMinMax() + const span = minTs && maxTs ? Date.parse(maxTs) - Date.parse(minTs) : NaN + return Math.abs(span - windowHours * 3600_000) < 1000 + }) + if (timeframe) params.set('timeframe', timeframe.label) + return `/runs?${params}` +} + export function windowLabel(hours: number) { return hours > 24 && hours % 24 === 0 ? `last ${hours / 24}d` : `last ${hours}h` } From 67dcf145f4ba67ff88d8a7a8eba673e27b333e56 Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:09:22 +0100 Subject: [PATCH 05/14] fix: parse a schedule's target once, at save and when it fires (#12183) --- ...7_normalize_schedule_target_paths.down.sql | 1 + ...907_normalize_schedule_target_paths.up.sql | 12 ++++++ backend/tests/schedule_target_path.rs | 43 +++++++++++++++++++ backend/windmill-api-schedule/src/lib.rs | 10 ++++- backend/windmill-queue/src/schedule.rs | 42 +++++++++--------- backend/windmill-queue/tests/schedule_push.rs | 20 +++++++++ cli/src/commands/schedule/schedule.ts | 12 +++++- ...schedule_push_permissioned_as_unit.test.ts | 24 +++++++++-- 8 files changed, 139 insertions(+), 25 deletions(-) create mode 100644 backend/migrations/20261102180907_normalize_schedule_target_paths.down.sql create mode 100644 backend/migrations/20261102180907_normalize_schedule_target_paths.up.sql create mode 100644 backend/tests/schedule_target_path.rs diff --git a/backend/migrations/20261102180907_normalize_schedule_target_paths.down.sql b/backend/migrations/20261102180907_normalize_schedule_target_paths.down.sql new file mode 100644 index 0000000000..8bc39341e4 --- /dev/null +++ b/backend/migrations/20261102180907_normalize_schedule_target_paths.down.sql @@ -0,0 +1 @@ +-- Nothing to do here: the stripped `/` named nothing. diff --git a/backend/migrations/20261102180907_normalize_schedule_target_paths.up.sql b/backend/migrations/20261102180907_normalize_schedule_target_paths.up.sql new file mode 100644 index 0000000000..11fe735698 --- /dev/null +++ b/backend/migrations/20261102180907_normalize_schedule_target_paths.up.sql @@ -0,0 +1,12 @@ +-- A schedule's target is compared with the path of the jobs it queues, and with a renamed +-- runnable's old path, neither of which starts with `/`. A target with more than one leading `/` +-- names nothing and is left as is: firing the schedule refuses it. +UPDATE schedule SET script_path = substr(script_path, 2) +WHERE script_path LIKE '/%' AND script_path NOT LIKE '//%'; +-- A restore puts the trashed row back as saved, so the copies awaiting one get the same fix. +UPDATE trashbin +SET item_data = jsonb_set(item_data, '{row,script_path}', + to_jsonb(substr(item_data #>> '{row,script_path}', 2))) +WHERE item_kind = 'schedule' + AND item_data #>> '{row,script_path}' LIKE '/%' + AND item_data #>> '{row,script_path}' NOT LIKE '//%'; diff --git a/backend/tests/schedule_target_path.rs b/backend/tests/schedule_target_path.rs new file mode 100644 index 0000000000..33762ac3af --- /dev/null +++ b/backend/tests/schedule_target_path.rs @@ -0,0 +1,43 @@ +use serde_json::json; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn create_stores_the_parsed_target(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace/schedules", + server.addr.port() + ); + let client = reqwest::Client::new(); + let create = |path: &str, script_path: &str| { + client + .post(format!("{base}/create")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ + "path": path, + "schedule": "0 0 0 * * *", + "timezone": "UTC", + "script_path": script_path, + "is_flow": false, + "args": {}, + "enabled": false, + })) + .send() + }; + + let resp = create("u/test-user/one_slash", "/u/test-user/x").await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let stored: String = sqlx::query_scalar( + "SELECT script_path FROM schedule WHERE workspace_id = 'test-workspace' AND path = 'u/test-user/one_slash'", + ) + .fetch_one(&db) + .await?; + assert_eq!(stored, "u/test-user/x"); + + let resp = create("u/test-user/two_slashes", "//u/test-user/x").await?; + assert_eq!(resp.status(), 400, "{}", resp.text().await?); + Ok(()) +} diff --git a/backend/windmill-api-schedule/src/lib.rs b/backend/windmill-api-schedule/src/lib.rs index e2fa7da8fe..70b0984605 100644 --- a/backend/windmill-api-schedule/src/lib.rs +++ b/backend/windmill-api-schedule/src/lib.rs @@ -21,6 +21,7 @@ use windmill_api_auth::{ }; use windmill_audit::audit_oss::audit_log; use windmill_audit::ActionKind; +use windmill_common::runnable_ref::RunnableRef; use windmill_common::DB; use windmill_common::{ can_preserve_on_behalf_of, @@ -268,10 +269,17 @@ async fn create_schedule( Extension(db): Extension, Extension(user_db): Extension, Path(w_id): Path, - Json(ns): Json, + Json(mut ns): Json, ) -> Result { check_scopes(&authed, || format!("schedules:write:{}", ns.path))?; reject_reserved_schedule_path(&ns.path)?; + // Stored as parsed: the next-run check, the monitor's re-arm, the run history and renames + // all match the stored target exactly against job paths, which never start with `/`. + if !ns.script_path.is_empty() { + ns.script_path = RunnableRef::from_path(&ns.script_path, ns.is_flow)? + .path() + .to_string(); + } let authed = maybe_refresh_folders(&ns.path, &w_id, authed, &db).await; diff --git a/backend/windmill-queue/src/schedule.rs b/backend/windmill-queue/src/schedule.rs index e404e07f05..246a05bb0c 100644 --- a/backend/windmill-queue/src/schedule.rs +++ b/backend/windmill-queue/src/schedule.rs @@ -23,6 +23,7 @@ use windmill_common::get_latest_flow_version_id_for_path; use windmill_common::jobs::JobPayload; use windmill_common::jobs::JobTriggerKind; use windmill_common::jobs::OnBehalfOf; +use windmill_common::runnable_ref::RunnableRef; use windmill_common::runnable_settings::ConcurrencySettings; use windmill_common::runnable_settings::DebouncingSettings; use windmill_common::schedule::schedule_to_user; @@ -43,6 +44,7 @@ use windmill_common::{ async fn get_schedule_metadata<'c>( tx: &mut sqlx::Transaction<'c, sqlx::Postgres>, schedule: &Schedule, + target: &RunnableRef, ) -> Result<( Option, // tag Option, // timeout @@ -61,7 +63,7 @@ async fn get_schedule_metadata<'c>( None, &mut **tx, &schedule.workspace_id, - &schedule.script_path, + target.path(), false, ) .await?; @@ -70,7 +72,7 @@ async fn get_schedule_metadata<'c>( &mut **tx, version, &schedule.workspace_id, - &schedule.script_path, + target.path(), ) .await?; @@ -87,7 +89,7 @@ async fn get_schedule_metadata<'c>( Some(version), parsed_retry, )) - } else if schedule.script_path.starts_with("hub/") { + } else if target.path().starts_with("hub/") { Ok((None, None, None, None, None, parsed_retry)) } else { let ( @@ -111,7 +113,7 @@ async fn get_schedule_metadata<'c>( ) = windmill_common::get_latest_hash_for_path( &mut **tx, &schedule.workspace_id, - &schedule.script_path, + target.path(), false, ) .await?; @@ -138,6 +140,7 @@ pub async fn push_scheduled_job<'c>( )); } + let target = RunnableRef::from_path(&schedule.script_path, schedule.is_flow)?; let sched = ScheduleType::from_str(&schedule.schedule, schedule.cron_version.as_deref(), false)?; @@ -200,7 +203,7 @@ pub async fn push_scheduled_job<'c>( &schedule.workspace_id, &schedule.path, next, - &schedule.script_path + target.path() ) .fetch_one(&mut *tx) .warn_after_seconds_with_sql(1, "already_exists_job".to_string()) @@ -326,11 +329,11 @@ pub async fn push_scheduled_job<'c>( // Get metadata from the scheduled script/flow for tag, timeout, etc. let (tag, timeout, on_behalf_of, hash, flow_version, retry) = - get_schedule_metadata(&mut tx, schedule).await?; + get_schedule_metadata(&mut tx, schedule, &target).await?; ( JobPayload::SingleStepFlow { - path: schedule.script_path.clone(), + path: target.path().to_string(), hash, flow_version, language: None, @@ -366,7 +369,7 @@ pub async fn push_scheduled_job<'c>( None, &mut *tx, &schedule.workspace_id, - &schedule.script_path, + target.path(), false, ) .warn_after_seconds_with_sql(1, "get_latest_flow_version_id_for_path".to_string()) @@ -376,7 +379,7 @@ pub async fn push_scheduled_job<'c>( &mut *tx, version, &schedule.workspace_id, - &schedule.script_path, + target.path(), ) .warn_after_seconds_with_sql(1, "get_flow_version_info_from_version".to_string()) .await?; @@ -391,7 +394,7 @@ pub async fn push_scheduled_job<'c>( ( JobPayload::Flow { - path: schedule.script_path.clone(), + path: target.path().to_string(), dedicated_worker, apply_preprocessor: false, version, @@ -402,18 +405,18 @@ pub async fn push_scheduled_job<'c>( None, on_behalf_of, ) - } else if schedule.script_path.starts_with("hub/") { + } else if target.path().starts_with("hub/") { let tag = schedule.tag.clone().filter(|t| !t.is_empty()); let payload = match &schedule.retry { // The language is what lets `push` materialize this as a native retry // instead of a flow wrapper, which would queue the next tick at start. Some(retry) => JobPayload::SingleStepFlow { - path: schedule.script_path.clone(), + path: target.path().to_string(), hash: None, flow_version: None, language: Some( get_full_hub_script_by_path( - StripPath(schedule.script_path.clone()), + StripPath(target.path().to_string()), &HTTP_CLIENT, Some(db), ) @@ -438,10 +441,9 @@ pub async fn push_scheduled_job<'c>( concurrency_settings: ConcurrencySettings::default(), debouncing_settings: DebouncingSettings::default(), }, - None => JobPayload::ScriptHub { - path: schedule.script_path.clone(), - apply_preprocessor: false, - }, + None => { + JobPayload::ScriptHub { path: target.path().to_string(), apply_preprocessor: false } + } }; (payload, tag, None, None) } else { @@ -466,7 +468,7 @@ pub async fn push_scheduled_job<'c>( ) = windmill_common::get_latest_hash_for_path( &mut *tx, &schedule.workspace_id, - &schedule.script_path, + target.path(), false, ) .warn_after_seconds_with_sql(1, "get_latest_hash_for_path".to_string()) @@ -500,7 +502,7 @@ pub async fn push_scheduled_job<'c>( // cannot be evaluated and fails closed (no retry). ( JobPayload::SingleStepFlow { - path: schedule.script_path.clone(), + path: target.path().to_string(), hash: Some(hash), flow_version: None, language: Some(language), @@ -534,7 +536,7 @@ pub async fn push_scheduled_job<'c>( ( JobPayload::ScriptHash { hash, - path: schedule.script_path.clone(), + path: target.path().to_string(), cache_ttl, cache_ignore_s3_path, dedicated_worker, diff --git a/backend/windmill-queue/tests/schedule_push.rs b/backend/windmill-queue/tests/schedule_push.rs index 9e86386107..19fd7b88f6 100644 --- a/backend/windmill-queue/tests/schedule_push.rs +++ b/backend/windmill-queue/tests/schedule_push.rs @@ -145,6 +145,26 @@ mod schedule_push { Ok(()) } + #[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))] + async fn test_push_parses_target(db: Pool) -> anyhow::Result<()> { + let authed = make_authed(); + let schedule = make_schedule(|s| s.script_path = "/f/system/test_script".to_string()); + let tx = db.begin().await?; + push_scheduled_job(&db, tx, &schedule, Some(&authed), None) + .await? + .commit() + .await?; + let (_, path, _, _) = get_queued_job(&db).await.unwrap(); + assert_eq!(path.as_deref(), Some("f/system/test_script")); + + let schedule = make_schedule(|s| s.script_path = "//f/system/test_script".to_string()); + let tx = db.begin().await?; + assert!(push_scheduled_job(&db, tx, &schedule, Some(&authed), None) + .await + .is_err()); + Ok(()) + } + // ----------------------------------------------------------------------- // push_scheduled_job: flow schedule // ----------------------------------------------------------------------- diff --git a/cli/src/commands/schedule/schedule.ts b/cli/src/commands/schedule/schedule.ts index 096615c757..d2eb7ffc80 100644 --- a/cli/src/commands/schedule/schedule.ts +++ b/cli/src/commands/schedule/schedule.ts @@ -107,6 +107,13 @@ async function get(opts: GlobalOptions & { json?: boolean }, path: string) { } } +// A server stores a target without its one tolerated leading `/`, while one predating +// that stores it as typed. Compared as written, the two spellings never match and every +// push re-saves the schedule, which resets its run-as to a non-admin pusher. +function canonicalTarget(path: string): string { + return path?.startsWith("/") && !path.startsWith("//") ? path.slice(1) : path; +} + export async function pushSchedule( workspace: string, path: string, @@ -130,6 +137,8 @@ export async function pushSchedule( // Strip CLI-only boolean marker before sending to API delete (localSchedule as any).has_permissioned_as; + localSchedule.script_path = canonicalTarget(localSchedule.script_path); + // In a fork, the file's `enabled` is the parent's for a path the parent // also has (see sync push's `parentOwnedScheduleEnabled`): the fork's own // flag stays as it is. @@ -158,7 +167,8 @@ export async function pushSchedule( } if (schedule) { - if (isSuperset(localSchedule, schedule)) { + const remote = { ...schedule, script_path: canonicalTarget(schedule.script_path) }; + if (isSuperset(localSchedule, remote)) { log.debug(`Schedule ${path} is up to date`); return; } diff --git a/cli/test/schedule_push_permissioned_as_unit.test.ts b/cli/test/schedule_push_permissioned_as_unit.test.ts index 953f8a415e..43984503bd 100644 --- a/cli/test/schedule_push_permissioned_as_unit.test.ts +++ b/cli/test/schedule_push_permissioned_as_unit.test.ts @@ -13,12 +13,13 @@ import { mockServices } from "./mock_services.ts"; let updateScheduleCalls: any[] = []; let remotePermissionedAs: string | undefined = "u/svc"; +let remoteScriptPath = "u/admin/script"; const REMOTE_SCHEDULE = () => ({ path: "u/admin/sched", schedule: "0 0 */6 * * *", timezone: "Etc/UTC", - script_path: "u/admin/script", + script_path: remoteScriptPath, is_flow: false, args: {}, enabled: false, @@ -74,8 +75,8 @@ await mockModule("../src/core/auth.ts", (real) => ({ requireLogin: async () => ({}), })); -const scheduleCommand = (await import("../src/commands/schedule/schedule.ts")) - .default; +const scheduleModule = await import("../src/commands/schedule/schedule.ts"); +const scheduleCommand = scheduleModule.default; async function pushIn(wmillYamlTail: string): Promise { const dir = await mkdtemp(join(tmpdir(), "windmill_sched_push_")); @@ -107,6 +108,7 @@ describe("wmill schedule push ownership", () => { beforeEach(() => { updateScheduleCalls = []; remotePermissionedAs = "u/svc"; + remoteScriptPath = "u/admin/script"; }); test("keeps the remote's permissioned_as under syncBehavior v1", async () => { @@ -141,4 +143,20 @@ describe("wmill schedule push ownership", () => { expect(body.permissioned_as).toBeUndefined(); expect(body.preserve_permissioned_as).toBeUndefined(); }); + + for (const [server, stored] of [ + ["a current server", "u/admin/script"], + ["an older server", "/u/admin/script"], + ]) { + test(`a target written with one leading slash matches what ${server} stores (${stored})`, async () => { + remoteScriptPath = stored; + const { permissioned_as: _, path: __, ...remote } = REMOTE_SCHEDULE(); + await scheduleModule.pushSchedule("w", "u/admin/sched.schedule.yaml", undefined, { + ...remote, + script_path: "/u/admin/script", + } as any); + + expect(updateScheduleCalls).toHaveLength(0); + }); + } }); From b532c819713ec260fd5fd9dacd2a02af11895dd3 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Tue, 3 Nov 2026 17:10:04 +0100 Subject: [PATCH 06/14] feat: download session artifacts as pdf (#12182) * feat: download session artifacts as pdf Co-Authored-By: Claude Opus 5.5 * fix: wrap code and wait only on pending diagrams in artifact pdf Co-Authored-By: Claude Opus 5.5 * fix: wait for markdown images before printing an artifact Co-Authored-By: Claude Opus 5.5 * fix: iterate stylesheet nodes through Array.from for ci's dom lib Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../lib/components/MarkdownCodeBlock.svelte | 7 +- .../artifacts/ArtifactExportButton.svelte | 19 ++- .../chat/artifacts/ArtifactPrintBody.svelte | 14 +++ .../artifacts/ArtifactPrintCodeBlock.svelte | 7 ++ .../copilot/chat/artifacts/printArtifact.ts | 115 ++++++++++++++++++ .../copilot/chat/script/MermaidDisplay.svelte | 17 ++- 6 files changed, 169 insertions(+), 10 deletions(-) create mode 100644 frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte create mode 100644 frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte create mode 100644 frontend/src/lib/components/copilot/chat/artifacts/printArtifact.ts diff --git a/frontend/src/lib/components/MarkdownCodeBlock.svelte b/frontend/src/lib/components/MarkdownCodeBlock.svelte index 26022e21cf..46ba73c281 100644 --- a/frontend/src/lib/components/MarkdownCodeBlock.svelte +++ b/frontend/src/lib/components/MarkdownCodeBlock.svelte @@ -28,12 +28,15 @@ applyButtonIcon = undefined, // Render ```mermaid blocks as diagrams. Off by default so untrusted // markdown surfaces don't execute mermaid — the chat opts in. - renderMermaid = false + renderMermaid = false, + // Draw diagrams in the light theme whatever the app's theme (printing). + lightMermaid = false }: { showApplyButton?: boolean onApplyCode?: () => void applyButtonIcon?: typeof ClipboardCopy renderMermaid?: boolean + lightMermaid?: boolean } = $props() const astNode = getAstNode() @@ -131,7 +134,7 @@
{#if renderMermaid && language === 'mermaid'} - + {:else} - import { Check, Copy, Download } from 'lucide-svelte' + import { Check, Copy, Download, FileDown } from 'lucide-svelte' import { Button } from '$lib/components/common' import { copyToClipboard, download } from '$lib/utils' import { artifactFilename, artifactMimeType, type ArtifactKind } from './artifactsDB' + import { printArtifact } from './printArtifact' interface Props { name: string @@ -31,11 +32,23 @@ title="Copy raw markdown" dropdownItems={[ { - label: 'Download as .md', + label: `Download as .${kind}`, icon: Download, onClick: () => download(artifactFilename({ name, kind }), content, artifactMimeType(kind)), disabled - } + }, + // Markdown only: an html artifact is agent-written markup, and printing it would run its + // scripts in this origin. + ...(kind === 'md' + ? [ + { + label: 'Download as PDF', + icon: FileDown, + onClick: () => printArtifact(name, content), + disabled + } + ] + : []) ]} > {copied ? 'Copied' : 'Copy'} diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte new file mode 100644 index 0000000000..f07c6f643f --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte @@ -0,0 +1,14 @@ + + +
+ +
diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte new file mode 100644 index 0000000000..261b39febf --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte @@ -0,0 +1,7 @@ + + + + diff --git a/frontend/src/lib/components/copilot/chat/artifacts/printArtifact.ts b/frontend/src/lib/components/copilot/chat/artifacts/printArtifact.ts new file mode 100644 index 0000000000..0d2099a3ea --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/artifacts/printArtifact.ts @@ -0,0 +1,115 @@ +import { mount, unmount, tick } from 'svelte' +import ArtifactPrintBody from './ArtifactPrintBody.svelte' + +/** + * Opens the browser's print dialog on a markdown artifact, where "Save as PDF" writes the file. + * The browser's print engine keeps the text selectable and the links live, which a + * canvas-rendered PDF would not. + * + * The document is rendered into a hidden iframe with the viewer's renderer rather than printing + * this page: the app's own print would include the whole session layout. The iframe copies + * this page's stylesheets, and its carries no `dark` class, so the PDF always uses the + * light theme. + */ +// Set while the iframe is being prepared, so a second click before the dialog opens does not +// stack a second print behind the first. +let preparing = false + +export async function printArtifact(name: string, content: string): Promise { + if (preparing) return + preparing = true + try { + await preparePrint(name, content) + } finally { + preparing = false + } +} + +async function preparePrint(name: string, content: string): Promise { + const iframe = document.createElement('iframe') + iframe.setAttribute('aria-hidden', 'true') + iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0' + document.body.appendChild(iframe) + + const doc = iframe.contentDocument + const win = iframe.contentWindow + if (!doc || !win) { + iframe.remove() + return + } + // The print dialog proposes the title as the PDF's file name. + doc.title = name + for (const node of Array.from(document.querySelectorAll('link[rel="stylesheet"], style'))) { + doc.head.appendChild(node.cloneNode(true)) + } + const page = doc.createElement('style') + // Without exact color adjust, browsers drop code-block and callout backgrounds. The break + // rules keep a code block, diagram, callout or table row whole and a heading with what follows. + // Code blocks scroll on screen; paper cannot, so they wrap and lose their height cap. + page.textContent = ` + @page { margin: 16mm } + html, body { background: white } + body { margin: 0; print-color-adjust: exact; -webkit-print-color-adjust: exact } + pre, svg, blockquote, tr, .markdown-alert { break-inside: avoid } + h1, h2, h3, h4, h5, h6 { break-after: avoid } + .not-prose, .not-prose * { overflow: visible !important; max-height: none !important } + .not-prose pre, .not-prose code { white-space: pre-wrap !important; overflow-wrap: anywhere } + ` + doc.head.appendChild(page) + + // Printing before the stylesheets load gives an unstyled PDF; the cap keeps a link that + // never settles from swallowing the click. + const stylesheets = Array.from( + doc.head.querySelectorAll('link[rel="stylesheet"]'), + (link) => + new Promise((resolve) => { + link.addEventListener('load', () => resolve(), { once: true }) + link.addEventListener('error', () => resolve(), { once: true }) + }) + ) + await Promise.race([ + Promise.all(stylesheets), + new Promise((resolve) => setTimeout(resolve, 3000)) + ]) + + const component = mount(ArtifactPrintBody, { target: doc.body, props: { content } }) + await tick() + await diagramsSettled(doc) + await imagesSettled(doc) + await doc.fonts?.ready + + const cleanup = () => { + unmount(component) + iframe.remove() + } + // print() blocks until the dialog closes in Chromium and Firefox, but returns at once in + // Safari, so the iframe is removed on afterprint rather than after the call. + win.addEventListener('afterprint', cleanup, { once: true }) + win.focus() + win.print() +} + +/** The print dialog snapshots the document as it is, so an image still loading is missing from + * the PDF. A broken image settles through `error`; the cap covers one that never answers. */ +async function imagesSettled(doc: Document): Promise { + const pending = Array.from(doc.images) + .filter((img) => !img.complete) + .map( + (img) => + new Promise((resolve) => { + img.addEventListener('load', () => resolve(), { once: true }) + img.addEventListener('error', () => resolve(), { once: true }) + }) + ) + await Promise.race([Promise.all(pending), new Promise((resolve) => setTimeout(resolve, 10_000))]) +} + +/** Mermaid draws asynchronously; printing before it lands puts the diagram source in the PDF. + * A diagram that fails to parse settles too (as its source), so this waits only on renders + * still in flight; the cap covers one that never returns. */ +async function diagramsSettled(doc: Document): Promise { + const deadline = Date.now() + 10_000 + while (doc.querySelector('[data-mermaid-pending="true"]') && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 100)) + } +} diff --git a/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte b/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte index e17cdbcb36..d39ab52bf7 100644 --- a/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte @@ -7,7 +7,7 @@ import { ClipboardCopy, Download, Maximize2, Minus, Plus, RotateCcw } from 'lucide-svelte' import type { PanZoom } from 'panzoom' - let { code }: { code: string } = $props() + let { code, forceLight = false }: { code: string; forceLight?: boolean } = $props() const isDarkMode = useIsDarkMode() @@ -19,6 +19,9 @@ // Monotonic token so an earlier-started render that resolves late can't // overwrite the result of a newer one (out-of-order async on rapid code/theme changes). let renderSeq = 0 + // False while a render is in flight, true once it drew or failed. Exposed as + // data-mermaid-pending so a print can wait for diagrams without counting fences. + let settled = $state(false) let expanded = $state(false) @@ -27,8 +30,10 @@ if (!source?.trim()) { svg = undefined renderedCode = undefined + settled = true return } + settled = false try { const mermaid = (await import('mermaid')).default mermaid.initialize({ @@ -65,11 +70,13 @@ // Parse failure (often a partial block still streaming in): fall back to the // raw source. `showSvg` already hides any previous diagram since `renderedCode` // no longer matches the current `code`. + } finally { + if (seq === renderSeq) settled = true } } $effect(() => { - void render(code, isDarkMode.val) + void render(code, !forceLight && isDarkMode.val) }) // Only show the diagram while it corresponds to the current source. @@ -130,8 +137,8 @@ {#if showSvg} -
-
+
+
- +
{:else if shared.current?.state === 'gone'} Date: Tue, 3 Nov 2026 17:10:46 +0100 Subject: [PATCH 08/14] feat: expose the page's query parameters to full-code apps as ctx.query (#12179) --- .../ai_session_tools/gen/instructions.json | 4 +-- cli/src/commands/app/dev.ts | 2 +- cli/src/guidance/skills.gen.ts | 2 ++ .../apps/editor/InWorkspaceAppViewer.svelte | 8 +++--- .../components/apps/editor/PublicApp.svelte | 8 +++--- .../components/raw_apps/RawAppEditor.svelte | 13 +++++++-- .../components/raw_apps/RawAppPreview.svelte | 27 ++++++++++--------- .../src/lib/components/raw_apps/utils.test.ts | 11 ++++++++ frontend/src/lib/components/raw_apps/utils.ts | 17 ++++++++++++ .../components/sessions/ItemViewerView.svelte | 2 +- .../RawAppRecordSession.svelte | 1 + system_prompts/auto-generated/prompts.ts | 2 ++ .../auto-generated/skills/raw-app/SKILL.md | 2 ++ system_prompts/base/raw-app.md | 2 ++ 14 files changed, 75 insertions(+), 26 deletions(-) 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 0118abaa24..c6b6dfce38 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -254,8 +254,8 @@ "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", "flow": "# Global draft flow instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\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. Never invent a folder.\n- `write_flow` mirrors flow mode's `set_flow_json`: pass `path`, optional `summary`, optional `description`, required `modules`, and optional `schema`, `preprocessor_module`, `failure_module`, `groups`, and `notes`. `summary` and `description` are top-level flow metadata (not part of the compact value `patch_flow_json` edits); the flow-structure arguments are JSON strings, matching the tool schema descriptions. When overwriting an existing flow, top-level flow settings (see below) are preserved from the current flow — use `patch_flow_json` to change them.\n- `read_workspace_item` returns a compact flow `value` object with `modules`, `schema`, `preprocessor_module`, `failure_module`, `groups`, `notes`, and any top-level flow settings that are set.\n- Top-level flow settings appear as top-level keys of the compact flow value and can be added, edited, or removed with `patch_flow_json`: same_worker, preserve_step_tags, concurrent_limit, concurrency_key, concurrency_time_window_s, debounce_delay_s, debounce_key, debounce_args_to_accumulate, max_total_debouncing_time, max_total_debounces_amount, skip_expr, cache_ttl, cache_ignore_s3_path, delete_after_secs, flow_env, priority, early_return, chat_input_enabled. For example, `chat_input_enabled: true` marks a flow as chat-style (flow-as-chat); keep it intact when restructuring such a flow.\n- `modules` contains normal sequential modules. Use top-level `preprocessor_module` and `failure_module` for special modules; do not put `preprocessor` or `failure` in `modules`.\n- Every module needs a stable unique `id` and a useful `summary` when the schema supports it.\n- Prefer path/script/flow modules when composing existing workspace logic. Use rawscript modules only when new inline code is needed.\n- When writing rawscript module code, call `get_instructions` with `subject: \"script\"` and the rawscript language first.\n\n## Groups and notes\n\n- Add `groups` to any non-trivial flow without being asked; \"Organizing Flows: Groups and Notes\" in the reference below gives the fields and the rules the editor enforces. Pass `null` to `write_flow` to clear them, and the same for `notes`.\n- With `patch_flow_json`, edit `groups` and `notes` the same way as any other field — they appear as top-level keys in the compact flow value.\n\n## Compact view: how rawscript bodies surface in tool I/O\n\n- `read_workspace_item` and `patch_flow_json` operate on a **compact view** of the flow: every rawscript module's `value.content` is replaced with the placeholder `\"inline_script.\"` so inline script bodies don't bloat tool I/O. Schema, groups, notes, preprocessor_module and failure_module are all shown in this view.\n- Inline rawscript content is **not** part of the JSON `patch_flow_json` sees. Edits to inline bodies happen via dedicated tools:\n - `read_flow_module_code(path, module_id)` — returns the raw inline script content for one module.\n - `set_flow_module_code(path, module_id, code)` — overwrites that module's inline script content; saves to the draft.\n- Use `patch_flow_json` for *structural* edits: module ids, paths, input_transforms, branch arrangement, summaries, preprocessor/failure swaps, schema/groups/notes. Use `set_flow_module_code` for changes inside a specific rawscript body.\n- When **adding a new rawscript module** with `patch_flow_json`, set its `content` to the placeholder `\"inline_script.\"` (matching the compact view) — never real code — then **immediately fill the body** with `set_flow_module_code(path, module_id, code)`. The module is saved with an empty body until you do; the tool result lists the module ids still awaiting code. A placeholder that names anything other than the module's own id or an existing rawscript module is rejected.\n- `write_flow` is for full overwrites / create-from-scratch. Its `modules`, `preprocessor_module`, and `failure_module` arguments are **non-compact** flow modules: inline each rawscript body directly in `content` by default. But if a body is long or quote/backslash-heavy enough that escaping it into the JSON string is error-prone — or if a `write_flow` call comes back with a JSON parse error — create that module with **empty content** (`\"content\": \"\"`) and fill it with `set_flow_module_code(path, module_id, code)`, whose `code` is a plain argument with no nested escaping. `write_flow` reports which modules still have empty bodies so you know what to fill.\n - When overwriting an **existing** flow, set `\"content\": \"inline_script.\"` on any rawscript module whose code you are not changing — the placeholder resolves to that module's current body, so you never re-send (or re-read) unchanged code. Placeholders that match no existing rawscript module and are not the module's own id are rejected.\n\n\n# Windmill flow authoring reference\n\n# Windmill Flow Building Guide\n\n## OpenFlow Schema\n\nThe OpenFlow schema (openflow.openapi.yaml) is the source of truth for flow structure. Refer to OPENFLOW_SCHEMA for the complete type definitions.\n\n## Reserved Module IDs\n\n- `failure` - Reserved for failure handler module\n- `preprocessor` - Reserved for preprocessor module\n- `Input` - Reserved for flow input reference\n\n## Hard Structural Rules\n\nThese are strict Windmill schema rules. Follow them exactly.\n\n- `value.modules` is only for normal sequential steps\n- `value.preprocessor_module` and `value.failure_module` are special top-level fields inside `value`, not entries in `value.modules`\n- If a flow needs a preprocessor, create `value.preprocessor_module` with `id: preprocessor`\n- If a flow needs a failure handler, create `value.failure_module` with `id: failure`\n- Do NOT create regular modules inside `value.modules` named `preprocessor` or `failure`\n- `preprocessor_module` and `failure_module` only support `script` or `rawscript`\n- `preprocessor_module` runs before normal modules and cannot reference `results.*`\n- `failure_module` can use the `error` object with `error.message`, `error.step_id`, `error.name`, and `error.stack`\n- A flow whose `failure_module` runs still ends as failed, unless the handler returns an object with `recover: true`: the flow then ends as a success. This also holds when the failing step is inside a loop, a branch or a subflow. `recover` never changes which steps run; whether a loop or branch carries on past a failure is still decided by its own settings (`skip_failures`, `continue_on_error`)\n\nCorrect shape:\n\n```yaml\nvalue:\n preprocessor_module:\n id: preprocessor\n value:\n type: rawscript\n ...\n failure_module:\n id: failure\n value:\n type: rawscript\n ...\n modules:\n - id: process_event\n value:\n type: rawscript\n ...\n```\n\nIncorrect shape:\n\n```yaml\nvalue:\n modules:\n - id: preprocessor\n ...\n - id: process_event\n ...\n - id: failure\n ...\n```\n\n## Module ID Rules\n\n- Must be unique across the entire flow\n- Use underscores, not spaces (e.g., `fetch_data` not `fetch data`)\n- Use descriptive names that reflect the step's purpose\n\n## AI Agent Modules\n\nAn `aiagent` module runs an LLM that can call tools. Each entry of `value.tools` is a module-shaped\nobject with an extra `value.tool_type`: `flowmodule` for a script or inline script tool (or a nested\nagent or AI decision), `mcp` for an MCP server tool, `websearch` for web search, `question` for a\nbuilt-in `ask_question` tool (the agent stops, without holding a worker, until someone answers from\nthe run page or the chat; optional `value.timeout` in seconds, default 1800). Set\n`requires_approval: true` on a `flowmodule` or `mcp` tool to have a person approve or reject each of\nits calls before it runs.\n\n```json\n{\n \"id\": \"support_agent\",\n \"summary\": \"AI agent for customer support\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"openai\", \"resource\": \"$res:f/ai_providers/openai\", \"model\": \"gpt-4o\" }\n },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.query\" },\n \"system_prompt\": { \"type\": \"static\", \"value\": \"You are a helpful assistant.\" }\n },\n \"tools\": [\n {\n \"id\": \"search_docs\",\n \"summary\": \"search_documentation\",\n \"description\": \"Search the product documentation. Use it whenever the user asks how a feature works.\",\n \"value\": {\n \"tool_type\": \"flowmodule\",\n \"type\": \"rawscript\",\n \"language\": \"bun\",\n \"content\": \"export async function main(query: string) { return ['doc1', 'doc2']; }\",\n \"input_transforms\": { \"query\": { \"type\": \"ai\" } }\n }\n }\n ]\n }\n}\n```\n\n- A flow cannot be a tool: a run offered one fails with `Unsupported tool`. Wrap it in a script\n that runs the flow\n- Each argument of a tool is either the model's or fixed. `{ \"type\": \"ai\" }` (or no value) lets the\n model fill it; a static value, an empty string included, fixes it and hides it from the model. Fix\n what the model must not choose, such as a resource, a table name or a limit\n- `provider` is an object, not a bare resource string: `{ \"kind\": ,\n \"resource\": \"$res:\", \"model\": }`. Required unless the module links to a saved\n agent through `value.agent`. Static is right for a flow run from a form; a chat flow wires its\n fields to flow inputs instead — see below\n\n### Chat-Mode Flows\n\nA flow with `value.chat_input_enabled: true` is run from a chat instead of a form: the composer\nsends one message per turn and renders the conversation. It needs a required `user_message` string\ninput, read by the agent. Any other flow input the composer does not edit itself is asked for\nunder Configure inputs.\n\n**A static `provider` gives a chat that cannot change its model.** Feed it from flow inputs\ninstead, either way round: one input carrying the whole object (`\"expr\": \"flow_input.model_config\"`)\nmakes every field editable, or wire it field by field to fix some and expose others. A field the\nchat can write becomes a control in the composer — a provider picker, a model list, a thinking\ncontrol — and a field left static is fixed, with no control drawn for it. `kind` is the one\nexception: the composer writes it only together with `resource`, since a provider is picked as a\npair, so a `kind` input wired on its own stays askable under Configure inputs and nothing the run\nneeds becomes unreachable.\n\n```json\n{\n \"id\": \"chat_agent\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"javascript\",\n \"expr\": \"({ kind: 'anthropic', resource: '$res:f/ai/claude', model: flow_input.model, reasoning_effort: flow_input.thinking })\"\n },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.user_message\" },\n \"user_attachments\": { \"type\": \"javascript\", \"expr\": \"flow_input.files\" },\n \"memory\": { \"type\": \"static\", \"value\": { \"kind\": \"compaction\" } },\n \"streaming\": { \"type\": \"static\", \"value\": true },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" }\n },\n \"tools\": []\n }\n}\n```\n\n- Wiring field by field means one object literal whose values are literals or bare `flow_input.x`\n references. A spread, a call or a computed key leaves the composer unable to tell which input\n feeds which field, so it offers no control at all — a bare `flow_input.x` for the whole object\n is read instead as that one input carrying every field\n- A step linked to a saved agent (`agent` set) has no `provider` of its own. It exposes the same\n two controls through its `model` and `reasoning_effort` inputs, which replace what the agent\n saved: `\"model\": { \"type\": \"javascript\", \"expr\": \"flow_input.model\" }`. An empty model keeps the\n saved one, an empty effort sends none, and the provider resource always stays the agent's\n- `memory` is what lets the agent see earlier turns; without it every message starts from nothing\n- `streaming` on makes the answer and its thinking appear token by token instead of all at once\n- `user_attachments` points at a flow input typed as an array of s3 objects\n (`{ \"type\": \"array\", \"items\": { \"type\": \"object\", \"resourceType\": \"s3object\" } }`), so files\n sent with a message reach the agent\n- Running one needs a `memory_id` **query parameter** — not a flow argument — naming the\n conversation the turn belongs to: a fresh UUID starts one, reusing a UUID continues it. The chat\n supplies it itself; a run driven any other way has to pass it or the server refuses the job\n\n### Tool Naming Rules\n\nThese rules cover `flowmodule` tools, the ones the agent calls by name. A `websearch` or `question`\ntool's `summary` is a plain label (`Web Search`), and an `mcp` tool exposes the MCP\nserver's own tool names, so none is name-checked at all — leave those summaries as they are.\n\n- A flowmodule tool's `summary` is the **name the agent calls it by**, not a human label. Put the\n human-readable explanation in `description`\n- `summary` must match `^[a-zA-Z0-9_]+$`: letters, numbers and underscores only. No spaces, dashes,\n dots or accents — `search_documentation`, never `Search documentation`\n- Always set `summary`. It must be unique among that agent's tools, and must not be one of the\n reserved ids (`do`, `bg`, `ctx`, `state`, `if`, `else`, `for`, `delete`, `while`, `new`, `in`,\n `failure`, `preprocessor`, `as`, `Input`, `Result`, `Trigger`)\n- A tool name outside that character set fails any run that offers the tool to the agent, with `Invalid tool name`.\n The flow write tools refuse such a name.\n- Tool `id` follows the same rules as any module ID — unique across the flow, underscores not spaces\n- `description` is optional free text telling the agent when and how to call the tool. Set it\n whenever the name alone does not make that obvious; it overrides the description derived from the\n underlying script\n\n## AI Decision Modules\n\nAn `aidecision` module asks a decision model (TypeSafe's Jev, Cloudflare's Clef or OpenAI's Decisions API) typed questions about a `state` and\nanswers each with calibrated probabilities instead of text. Prefer it over an `aiagent` when the step\nis a judgment (classify, route, score or a yes/no check) that needs no tools and no free text: it\nis faster, cheaper, and its answers have a fixed shape.\n\n```json\n{\n \"id\": \"triage\",\n \"summary\": \"Classify the ticket\",\n \"value\": {\n \"type\": \"aidecision\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"typesafe\", \"resource\": \"$res:f/ai/typesafe\", \"model\": \"jev-latest\" }\n },\n \"state\": { \"type\": \"javascript\", \"expr\": \"flow_input.message\" },\n \"questions\": {\n \"type\": \"static\",\n \"value\": {\n \"intent\": {\n \"type\": \"choice\",\n \"instructions\": \"What does the customer want?\",\n \"criteria\": { \"refund\": \"Money back\", \"bug\": \"Something is broken\", \"other\": \"Anything else\" }\n },\n \"urgency\": {\n \"type\": \"score\",\n \"instructions\": \"How urgent is the ticket?\",\n \"criteria\": [\"Can wait\", \"This week\", \"Today\", \"Right now\"]\n },\n \"angry\": { \"type\": \"noul\", \"instructions\": \"Is the customer angry?\" }\n }\n }\n }\n }\n}\n```\n\n- `provider.kind` is `typesafe` (`model` `jev-latest` unless a version is pinned), `cloudflare`\n (`model` `clef`, or `clef-flash` for faster answers) or `openai` (`model` `gpt-6-luna`, never a\n chat model); the resource is of that same type\n- `state` is the content to evaluate: usually a text, such as the message to classify. To combine\n several values, pass an object with descriptive keys holding only what the questions need\n (`({ message: flow_input.message, plan: results.get_account.plan })`); an array of strings also works\n- `questions` maps each question name to `{ type, instructions, criteria }`:\n - `choice`: `criteria` maps each option to its description (up to 255 options). The answer has\n `choice`, `probabilities` and `confidence`\n - `score`: `criteria` is an ordered array of 2 to 10 level descriptions. The answer has `score`,\n `legend`, `probabilities` and `confidence`\n - `noul`: yes/no, `criteria` optionally `{ \"true\": ..., \"false\": ... }` descriptions. The answer has\n `noul`, the probability of yes from 0 to 1\n- The result is `{ output, model, usage }` with `output` keyed by question name, so a later step\n reads `results.triage.output.intent.choice`, `results.triage.output.urgency.score` or\n `results.triage.output.angry.noul > 0.7`\n- On `openai` the same `questions` are translated for its Decisions API and the answers read the\n same way (`choice`, `score`, `noul`), except that `probabilities` is a list of\n `{ value, probability }` (plus `label` on a score) and a score has no `legend`. A question OpenAI\n refuses to answer fails the step. A `state` that is\n an array of user messages (`[{ role: \"user\", content: [{ type: \"input_text\", text }, { type: \"input_image\", image_url: \"data:image/png;base64,...\" }] }]`)\n is sent as is, which is how an image is evaluated; any other object or array is sent as JSON text\n\n### Branching on the Answers\n\nTo route on the answers, put a `branchone` right after the decision, one branch per option, with\neach `expr` reading the decision by id:\n\n```json\n{\n \"id\": \"route\",\n \"value\": {\n \"type\": \"branchone\",\n \"branches\": [\n { \"summary\": \"refund\", \"expr\": \"results.triage.output.intent.choice === 'refund'\", \"modules\": [...] },\n { \"summary\": \"bug\", \"expr\": \"results.triage.output.intent.choice === 'bug'\", \"modules\": [...] }\n ],\n \"default\": [...]\n }\n}\n```\n\nFor a yes/no question, one branch with `\"expr\": \"results.triage.output.angry.noul >= 0.5\"` (tune the\nthreshold as needed) and the `default` as the \"no\" path.\n\n### As an Agent Tool\n\nAn `aidecision` can be a `flowmodule` tool of an `aiagent` (`\"tool_type\": \"flowmodule\", \"type\":\n\"aidecision\"`): set `state` to `{ \"type\": \"ai\" }` so the calling model supplies it, and only `output`\ngoes back to the model. The Tool Naming Rules apply to its `summary`. Only a flow's own agent step\ncan call one, not an agent used as a tool.\n\n## Common Mistakes to Avoid\n\n- Missing `input_transforms` - Rawscript parameters won't receive values without them\n- Referencing future steps - `results.step_id` only works for steps that execute before the current one\n- Duplicate module IDs - Each module ID must be unique in the flow\n- AI agent flowmodule tool names with spaces - `summary` is the tool name and only accepts letters, numbers and underscores\n\n## Data Flow Between Steps\n\n- `flow_input.property` - Access flow input parameters\n- `results.step_id` - Access output from a previous step only when that step result is in scope\n- `results.step_id.property` - Access specific property from a previous step output only when that step result is in scope\n- `flow_input.iter.value` - Current iteration value inside a `forloopflow`; in a `whileloopflow` it is just the iteration index (a plain number, same as `flow_input.iter.index`)\n- `flow_input.iter.index` - Current loop index when inside a loop (`forloopflow` or `whileloopflow`)\n- After a suspend step (approval), the next step's javascript expressions also get:\n - `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: \"SuspendedDisapproved\" | \"SuspendedTimedOut\", message } }` instead\n - `resumes` - every resume payload, in arrival order\n - `approvers` - a plain array of strings, one per resume: for a resume through the `resume`/`cancel` URL from `getResumeUrls(approver)`, the `approver` passed there if any; otherwise (including the `approvalPage` link) the resuming user's username, else `\"anonymous\"`, e.g. `approvers[0]`. It is NOT the `{ resume_id, approver }` objects stored in the flow status, so `approvers[0].approver` is always undefined\n\n## Loop Structure Rules\n\n- A `forloopflow` runs its `modules` once per element of `iterator`, a javascript expression returning an array (e.g. `results.get_items`); `parallel: true` runs the iterations concurrently, and `skip_failures: true` carries on past a failed iteration\n- For `whileloopflow`, break the loop with a module-level `stop_after_if`: on the loop module itself, or on an inner step (required when that step carries state via its own `results` — see below)\n- `stop_after_if` is always a sibling of `id` and `value` on a flow module — never a direct key of the loop's `value` object\n- `stop_after_all_iters_if` is for checks after the whole loop finishes, not the normal per-iteration break condition\n- `stop_after_if` is evaluated after each iteration: on the loop module, `result` is that iteration's result (what its last step returned); on an inner step, it is that step's result\n- `flow_input.iter.value` in a `whileloopflow` is just the iteration index (same number as `flow_input.iter.index`) — it never carries state, so `flow_input.iter.value.` is always undefined and a loop whose stop condition depends on it never terminates\n- To carry state across iterations, a step reads its own previous-iteration result via `results.` with a first-iteration fallback (e.g. `results.b ?? flow_input.start`) — but then the loop's `stop_after_if` MUST sit on that inner step, not on the loop module: a body that is exactly one plain step with the stop condition on the loop module runs on a fast path where `results.` is null on every iteration and the loop never terminates (bodies with 2+ steps, or whose single step has its own `stop_after_if`, retry or similar, resolve `results` across iterations regardless of stop placement)\n- For state that is just a counter, derive it from the index instead (e.g. `flow_input.iter.index + 1`) — that works in every configuration, including with `stop_after_if` on the loop module\n- If the user asks for a final scalar/object after a loop, add a normal step after the loop that extracts the final value from the loop result instead of returning the whole loop result array\n\nCorrect `whileloopflow` shape:\n\n```yaml\n- id: loop_until_done\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n value:\n type: rawscript\n input_transforms:\n count:\n type: javascript\n expr: flow_input.iter.index + 1\n- id: return_final_state\n value:\n type: rawscript\n input_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done[results.loop_until_done.length - 1]\n```\n\nCorrect `whileloopflow` shape carrying state via `results` (stop condition on the inner step):\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: rawscript\n input_transforms:\n state:\n type: javascript\n expr: results.advance_state ?? flow_input.initial_state\n```\n\nIncorrect `whileloopflow` patterns:\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n stop_after_if:\n expr: result.done === true\n```\n\n```yaml\ninput_transforms:\n state:\n type: javascript\n # iter.value is a number (the iteration index); there is no previous-iteration state\n expr: flow_input.iter.value.count\n```\n\n```yaml\ninput_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done\n```\n\n## Approval / Suspend Structure\n\nAn approval step is a normal **script** step (`type: rawscript` or `type: script`) that is turned into an approval by adding a module-level `suspend`. Its script calls `wmill.getResumeUrls(approver)` to generate the secret resume/cancel URLs and returns them so they can be sent to the approver(s) (Slack, email, etc.) or approved from the run page.\n\n- `suspend` belongs on the flow module object itself, as a sibling of `id` and `value`\n- Never put `suspend` inside `value`\n- Do NOT use `type: identity` for an approval step. An identity step suspends but never produces the resume URLs, so approvers have no link to act on — it is not a functional approval.\n\nCorrect shape:\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n resume_form:\n schema:\n type: object\n properties:\n comment:\n type: string\n required: [comment]\n value:\n type: rawscript\n language: bun\n input_transforms:\n approver:\n type: static\n value: ''\n content: |\n import * as wmill from \"windmill-client\"\n\n export async function main(approver?: string) {\n const urls = await wmill.getResumeUrls(approver)\n // send urls.resume / urls.cancel to the approver(s), e.g. via Slack or email\n return urls\n }\n```\n\nIncorrect shape (suspend misplaced inside `value`):\n\n```yaml\n- id: request_approval\n value:\n type: rawscript\n suspend:\n required_events: 1\n```\n\nIncorrect shape (identity has no resume URLs — not a real approval):\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n value:\n type: identity\n```\n\n## Branch Result Scope Rules\n\n- A `branchone` runs the first of its `branches` whose `expr` is true, in order, and its `default` modules when none is; a `branchall` runs every branch (concurrently with `parallel: true`)\n- Inside a branch, you may reference earlier outer steps and earlier steps in the same branch\n- Outside a `branchone`, do NOT reference ids of steps that only exist inside its branches or default branch. Use `results.` instead\n- Outside a `branchall`, do NOT reference ids of steps inside its branches. Use `results.` instead\n- If downstream steps need a stable shape after a branch, make each branch return the same fields\n- When needed, add a normalization step immediately after the branch and consume `results.` there\n\nCorrect after `branchone`:\n\n```yaml\n- id: route_order\n value:\n type: branchone\n ...\n- id: send_confirmation\n value:\n input_transforms:\n routed:\n type: javascript\n expr: results.route_order\n```\n\nIncorrect after `branchone`:\n\n```yaml\nexpr: results.create_shipment\nexpr: results.create_backorder\n```\n\nCorrect after `branchall`:\n\n```yaml\n- id: enrich_parallel\n value:\n type: branchall\n parallel: true\n ...\n- id: combine_data\n value:\n input_transforms:\n enrichments:\n type: javascript\n expr: results.enrich_parallel\n```\n\n## Input Transforms\n\nEvery rawscript module needs `input_transforms` to map function parameters to values:\n\nStatic transform (fixed value):\n{\"param_name\": {\"type\": \"static\", \"value\": \"fixed_string\"}}\n\nJavaScript transform (dynamic expression):\n{\"param_name\": {\"type\": \"javascript\", \"expr\": \"results.previous_step.data\"}}\n\n## Resource References\n\n- For flow inputs: Use type `\"object\"` with format `\"resource-{type}\"` (e.g., `\"resource-postgresql\"`)\n- For step inputs: Use static value `\"$res:path/to/resource\"`\n\n## Reusing Existing Scripts and Flows\n\nUnless the user asked for new code, look for a workspace script or flow that already does a step's job before writing it, and reuse it by path instead of copying its logic into a rawscript:\n\n- a workspace script: `type: script` with `path` (e.g. `f/folder/send_email`)\n- a workspace flow, run as a subflow: `type: flow` with `path`\n- a Hub script: `type: script` with a `hub///` path\n\nThe step's `input_transforms` must cover the reused item's inputs, so read its input schema first.\n\n## Additional Prompt for AI\n\nA flow's input schema may carry a top-level `prompt_for_ai` string, as a script's can: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that flow, and keep it when you rewrite the schema.\n\n## Organizing Flows: Groups and Notes\n\nGroups and notes shape how a flow reads in the editor; neither changes what it does.\n\n**Segment every non-trivial flow into groups without waiting to be asked.** Whenever a flow has more than a couple of steps, or consecutive steps form a stage (\"fetch\", \"transform\", \"notify\"), put them in a group, and aim for every meaningful step to belong to one. Use notes sparingly, for flow-wide information that belongs to no span of steps: the flow's purpose, key assumptions, warnings, TODOs. One note is usually enough; never label a run of steps with a note, which is what a group is for.\n\n`value.groups` lists the groups, each spanning the steps from `start_id` to `end_id`:\n\n- `start_id`, `end_id` (required): ids of the group's first and last step; the same id for both makes a one-step group\n- `summary`: the group's title\n- `note`: markdown shown under the title\n- `color`: one of `yellow`, `blue`, `green`, `purple`, `pink`, `orange`, `red`, `cyan`, `lime`, `gray`, never a hex code or CSS color; leave it out and the editor picks one\n- `autocollapse`: `true` shows the group collapsed by default\n\nThe editor refuses to draw a flow whose groups break any of these rules:\n\n- `start_id` and `end_id` are steps of the same list: both top-level, or both in the same loop body or branch. A group can hold a loop or branch step whole, but cannot start outside one and end inside it\n- `start_id` does not come after `end_id` in that list\n- groups nest (one entirely inside another) but never partly overlap, and no two groups share both `start_id` and `end_id`\n- groups hold ordinary steps only: never `preprocessor`, `failure`, `Input`, `Result`, `Trigger`, or an AI agent's tools\n\n`value.notes` lists sticky notes, each with a unique `id`, markdown `text`, a `color` from the same list, and `type: free`. The `group` note type is deprecated; use `value.groups` instead.\nLeave a note's `position` and `size` out and they are filled in for you.\n\n## Final Structural Self-Check\n\nBefore finalizing a flow, verify:\n\n- any preprocessor is in `value.preprocessor_module`\n- any failure handler is in `value.failure_module`\n- any approval step has module-level `suspend`\n- no downstream step references inner branch step ids from outside the branch\n- every AI agent flowmodule tool has a unique `summary` made only of letters, numbers and underscores\n- every group starts and ends on steps of the same list, start before end, nesting without partial overlap\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations.\n\nTo accept an S3 object as flow input:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\n \"type\": \"object\",\n \"format\": \"resource-s3_object\",\n \"description\": \"File to process\"\n }\n }\n}\n```\n\n## Using Resources in Flows\n\nOn Windmill, credentials and configuration are stored in resources. Resource types define the format of the resource.\n\n### As Flow Input\n\nIn the flow schema, set the property type to `\"object\"` with format `\"resource-{type}\"`:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"database\": {\n \"type\": \"object\",\n \"format\": \"resource-postgresql\",\n \"description\": \"Database connection\"\n }\n }\n}\n```\n\n### When No Resource Type Fits\n\nA connection still comes in as one resource input, not as separate string inputs (a URL, a token) or a variable read inside a step: type the input `resource-c_` with a custom resource type holding the service's connection fields, its secret in a variable the resource references. The `c_` prefix of custom types keeps one apart from a hub type synced later under the same name.\n\n- 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.\n- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it.\n- A plain variable is fine when the user asks for it.\n\n### As Step Input (Static Reference)\n\nReference a specific resource using `$res:` prefix:\n\n```json\n{\n \"database\": {\n \"type\": \"static\",\n \"value\": \"$res:f/folder/my_database\"\n }\n}\n```\n\n\n## OpenFlow Schema\n\n{\"OpenFlow\":{\"type\":\"object\",\"description\":\"Top-level flow definition containing metadata, configuration, and the flow structure\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of what this flow does\"},\"description\":{\"type\":\"string\",\"description\":\"Detailed documentation for this flow\"},\"value\":{\"$ref\":\"#/components/schemas/FlowValue\"},\"schema\":{\"type\":\"object\",\"description\":\"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-' (e.g., 'resource-stripe')\"},\"on_behalf_of_email\":{\"type\":\"string\",\"description\":\"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names.\"},\"on_behalf_of\":{\"type\":\"string\",\"description\":\"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead.\"}},\"required\":[\"summary\",\"value\"]},\"FlowValue\":{\"type\":\"object\",\"description\":\"The flow structure containing modules and optional preprocessor/failure handlers\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"failure_module\":{\"description\":\"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types\",\"$ref\":\"#/components/schemas/FlowModule\"},\"preprocessor_module\":{\"description\":\"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results\",\"$ref\":\"#/components/schemas/FlowModule\"},\"same_worker\":{\"type\":\"boolean\",\"description\":\"If true, all steps run on the same worker for better performance\"},\"preserve_step_tags\":{\"type\":\"boolean\",\"description\":\"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag.\"},\"concurrent_limit\":{\"type\":\"number\",\"description\":\"Maximum number of concurrent executions of this flow\"},\"concurrency_key\":{\"type\":\"string\",\"description\":\"Expression to group concurrent executions (e.g., by user ID)\"},\"concurrency_time_window_s\":{\"type\":\"number\",\"description\":\"Time window in seconds for concurrent_limit\"},\"debounce_delay_s\":{\"type\":\"integer\",\"description\":\"Delay in seconds to debounce flow executions\"},\"debounce_key\":{\"type\":\"string\",\"description\":\"Expression to group debounced executions\"},\"debounce_args_to_accumulate\":{\"type\":\"array\",\"description\":\"Arguments to accumulate across debounced executions\",\"items\":{\"type\":\"string\"}},\"max_total_debouncing_time\":{\"type\":\"integer\",\"description\":\"Maximum total time in seconds that a job can be debounced\"},\"max_total_debounces_amount\":{\"type\":\"integer\",\"description\":\"Maximum number of times a job can be debounced\"},\"skip_expr\":{\"type\":\"string\",\"description\":\"JavaScript expression to conditionally skip the entire flow\"},\"cache_ttl\":{\"type\":\"number\",\"description\":\"Cache duration in seconds for flow results\"},\"cache_ignore_s3_path\":{\"type\":\"boolean\"},\"delete_after_secs\":{\"type\":\"integer\",\"description\":\"If set, delete the flow job's args, result and logs after this many seconds following job completion\"},\"flow_env\":{\"type\":\"object\",\"description\":\"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).\",\"additionalProperties\":{}},\"priority\":{\"type\":\"number\",\"description\":\"Execution priority (higher numbers run first)\"},\"early_return\":{\"type\":\"string\",\"description\":\"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead.\"},\"chat_input_enabled\":{\"type\":\"boolean\",\"description\":\"Whether this flow accepts chat-style input\"},\"notes\":{\"type\":\"array\",\"description\":\"Sticky notes attached to the flow\",\"items\":{\"$ref\":\"#/components/schemas/FlowNote\"}},\"groups\":{\"type\":\"array\",\"description\":\"Semantic groups of modules for organizational purposes\",\"items\":{\"$ref\":\"#/components/schemas/FlowGroup\"}}},\"required\":[\"modules\"]},\"Retry\":{\"type\":\"object\",\"description\":\"Retry configuration for failed module executions\",\"properties\":{\"constant\":{\"type\":\"object\",\"description\":\"Retry with constant delay between attempts\",\"properties\":{\"attempts\":{\"type\":\"integer\",\"description\":\"Number of retry attempts\"},\"seconds\":{\"type\":\"integer\",\"description\":\"Seconds to wait between retries\"}}},\"exponential\":{\"type\":\"object\",\"description\":\"Retry with exponential backoff: the n-th retry waits multiplier \\u00d7 seconds^n\",\"properties\":{\"attempts\":{\"type\":\"integer\",\"description\":\"Number of retry attempts\"},\"multiplier\":{\"type\":\"integer\",\"description\":\"Multiplier for exponential backoff\"},\"seconds\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Base of the exponential (seconds); the n-th retry waits multiplier \\u00d7 seconds^n, where n counts constant retries too\"},\"random_factor\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"description\":\"Random jitter percentage (0-100) to avoid thundering herd\"}}},\"retry_if\":{\"$ref\":\"#/components/schemas/RetryIf\"}}},\"FlowNote\":{\"type\":\"object\",\"description\":\"A sticky note attached to a flow for documentation and annotation\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for the note\"},\"text\":{\"type\":\"string\",\"description\":\"Content of the note\"},\"position\":{\"type\":\"object\",\"description\":\"Position of the note in the flow editor\",\"properties\":{\"x\":{\"type\":\"number\",\"description\":\"X coordinate\"},\"y\":{\"type\":\"number\",\"description\":\"Y coordinate\"}},\"required\":[\"x\",\"y\"]},\"size\":{\"type\":\"object\",\"description\":\"Size of the note in the flow editor\",\"properties\":{\"width\":{\"type\":\"number\",\"description\":\"Width in pixels\"},\"height\":{\"type\":\"number\",\"description\":\"Height in pixels\"}},\"required\":[\"width\",\"height\"]},\"color\":{\"type\":\"string\",\"description\":\"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled.\"},\"type\":{\"type\":\"string\",\"enum\":[\"free\",\"group\"],\"description\":\"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead.\"},\"locked\":{\"type\":\"boolean\",\"default\":false,\"description\":\"Whether the note is locked and cannot be edited or moved\"},\"contained_node_ids\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"For group notes, the IDs of nodes contained within this group\"}},\"required\":[\"id\",\"text\",\"color\",\"type\"]},\"FlowGroup\":{\"type\":\"object\",\"description\":\"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Display name for this group\"},\"note\":{\"type\":\"string\",\"description\":\"Markdown note shown below the group header\"},\"autocollapse\":{\"type\":\"boolean\",\"default\":false,\"description\":\"If true, this group is collapsed by default in the flow editor. UI hint only.\"},\"start_id\":{\"type\":\"string\",\"description\":\"ID of the first flow module in this group (topological entry point)\"},\"end_id\":{\"type\":\"string\",\"description\":\"ID of the last flow module in this group (topological exit point)\"},\"color\":{\"type\":\"string\",\"description\":\"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one.\"}},\"required\":[\"start_id\",\"end_id\"]},\"RetryIf\":{\"type\":\"object\",\"description\":\"Conditional retry based on error or result\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\"}},\"required\":[\"expr\"]},\"StopAfterIf\":{\"type\":\"object\",\"description\":\"Early termination condition for a module\",\"properties\":{\"skip_if_stopped\":{\"type\":\"boolean\",\"description\":\"If true, following steps are skipped when this condition triggers\"},\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop\"},\"error_message\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.\"},\"error_include_result\":{\"type\":\"boolean\",\"description\":\"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.\"}},\"required\":[\"expr\"]},\"FlowModule\":{\"type\":\"object\",\"description\":\"A single step in a flow. Can be a script, subflow, loop, or branch\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)\"},\"value\":{\"$ref\":\"#/components/schemas/FlowModuleValue\"},\"stop_after_if\":{\"description\":\"Early termination condition evaluated after this step completes\",\"$ref\":\"#/components/schemas/StopAfterIf\"},\"stop_after_all_iters_if\":{\"description\":\"For loops only - early termination condition evaluated after all iterations complete\",\"$ref\":\"#/components/schemas/StopAfterIf\"},\"skip_if\":{\"type\":\"object\",\"description\":\"Conditionally skip this step based on previous results or flow inputs\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.'\"}},\"required\":[\"expr\"]},\"sleep\":{\"description\":\"Delay after this step completes, before the next step starts (in seconds or as expression)\",\"$ref\":\"#/components/schemas/InputTransform\"},\"cache_ttl\":{\"type\":\"number\",\"description\":\"Cache duration in seconds for this step's results\"},\"cache_ignore_s3_path\":{\"type\":\"boolean\"},\"timeout\":{\"description\":\"Maximum execution time in seconds (static value or expression)\",\"$ref\":\"#/components/schemas/InputTransform\"},\"delete_after_secs\":{\"type\":\"integer\",\"description\":\"If set, delete the step's args, result and logs after this many seconds following job completion\"},\"summary\":{\"type\":\"string\",\"description\":\"Short description of what this step does\"},\"mock\":{\"type\":\"object\",\"description\":\"Mock configuration for testing without executing the actual step\",\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"If true, return mock value instead of executing\"},\"return_value\":{\"description\":\"Value to return when mocked\"}}},\"suspend\":{\"type\":\"object\",\"description\":\"Configuration for approval/resume steps that wait for user input\",\"properties\":{\"required_events\":{\"type\":\"integer\",\"description\":\"Number of approvals required before continuing\"},\"timeout\":{\"type\":\"integer\",\"description\":\"Timeout in seconds before auto-continuing or canceling\"},\"resume_form\":{\"type\":\"object\",\"description\":\"Form schema for collecting input when resuming\",\"properties\":{\"schema\":{\"type\":\"object\",\"description\":\"JSON Schema for the resume form\"}}},\"user_auth_required\":{\"type\":\"boolean\",\"description\":\"If true, only authenticated users can approve\"},\"user_groups_required\":{\"description\":\"Expression or list of groups that can approve\",\"$ref\":\"#/components/schemas/InputTransform\"},\"self_approval_disabled\":{\"type\":\"boolean\",\"description\":\"If true, the user who started the flow cannot approve\"},\"hide_cancel\":{\"type\":\"boolean\",\"description\":\"If true, hide the cancel button on the approval form\"},\"continue_on_disapprove_timeout\":{\"type\":\"boolean\",\"description\":\"If true, continue flow on timeout instead of canceling\"},\"skin\":{\"type\":\"string\",\"enum\":[\"detailed\",\"minimal\"],\"description\":\"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions\"}}},\"priority\":{\"type\":\"number\",\"description\":\"Execution priority for this step (higher numbers run first)\"},\"continue_on_error\":{\"type\":\"boolean\",\"description\":\"If true, flow continues even if this step fails\"},\"job_token_scopes\":{\"type\":\"array\",\"nullable\":true,\"items\":{\"type\":\"string\"},\"description\":\"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).\"},\"retry\":{\"description\":\"Retry configuration if this step fails\",\"$ref\":\"#/components/schemas/Retry\"},\"debouncing\":{\"description\":\"Debounce configuration for this step (EE only)\",\"type\":\"object\",\"properties\":{\"debounce_delay_s\":{\"type\":\"integer\",\"description\":\"Delay in seconds to debounce this step's executions across flow runs\"},\"debounce_key\":{\"type\":\"string\",\"description\":\"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/-\"},\"debounce_args_to_accumulate\":{\"type\":\"array\",\"description\":\"Array-type arguments to accumulate across debounced executions\",\"items\":{\"type\":\"string\"}},\"max_total_debouncing_time\":{\"type\":\"integer\",\"description\":\"Maximum total time in seconds before forced execution\"},\"max_total_debounces_amount\":{\"type\":\"integer\",\"description\":\"Maximum number of debounces before forced execution\"}}}},\"required\":[\"value\",\"id\"]},\"InputTransform\":{\"description\":\"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"StaticTransform\":{\"type\":\"object\",\"description\":\"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'\",\"properties\":{\"value\":{\"description\":\"The static value. For resources, use format '$res:path/to/resource'\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\"]},\"JavascriptTransform\":{\"type\":\"object\",\"description\":\"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)\"},\"type\":{\"type\":\"string\",\"enum\":[\"javascript\"]}},\"required\":[\"expr\",\"type\"]},\"AiTransform\":{\"type\":\"object\",\"description\":\"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"ai\"]}},\"required\":[\"type\"]},\"AIProviderKind\":{\"type\":\"string\",\"description\":\"Supported AI provider types\",\"enum\":[\"openai\",\"azure_openai\",\"azure_foundry\",\"anthropic\",\"mistral\",\"deepseek\",\"googleai\",\"groq\",\"openrouter\",\"togetherai\",\"customai\",\"aws_bedrock\",\"typesafe\",\"cloudflare\"]},\"ProviderConfig\":{\"type\":\"object\",\"description\":\"Complete AI provider configuration with resource reference and model selection\",\"properties\":{\"kind\":{\"$ref\":\"#/components/schemas/AIProviderKind\"},\"resource\":{\"type\":\"string\",\"description\":\"Resource reference in format '$res:{resource_path}' pointing to provider credentials\"},\"model\":{\"type\":\"string\",\"description\":\"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')\"},\"reasoning_effort\":{\"type\":\"string\",\"description\":\"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.\"}},\"required\":[\"kind\",\"resource\",\"model\"]},\"StaticProviderTransform\":{\"type\":\"object\",\"description\":\"Static provider configuration passed directly to the AI agent\",\"properties\":{\"value\":{\"$ref\":\"#/components/schemas/ProviderConfig\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\",\"value\"]},\"ProviderTransform\":{\"description\":\"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticProviderTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticProviderTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"MemoryOff\":{\"type\":\"object\",\"description\":\"No conversation memory/context\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"off\"]}},\"required\":[\"kind\"]},\"MemoryWindow\":{\"type\":\"object\",\"description\":\"Keeps the most recent messages of the memory named by the run's memory id (or the step's\\n`memory_id`). Without a memory id the agent runs without memory.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"window\"]},\"context_length\":{\"type\":\"integer\",\"description\":\"Number of most recent messages to load and store. 0 turns memory off.\"}},\"required\":[\"kind\",\"context_length\"]},\"MemoryAuto\":{\"type\":\"object\",\"deprecated\":true,\"description\":\"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"auto\"]},\"context_length\":{\"type\":\"integer\",\"description\":\"Maximum number of messages to retain in context\"},\"memory_id\":{\"type\":\"string\",\"description\":\"Identifier for persistent memory across agent invocations\"}},\"required\":[\"kind\"]},\"MemoryCompaction\":{\"type\":\"object\",\"description\":\"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\\nits older part with a summary as the conversation approaches the model's context window.\\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"compaction\"]},\"context_window\":{\"type\":\"integer\",\"description\":\"Overrides the context window looked up from the model, in tokens. Only a model\\nWindmill does not know needs one; those fall back to 128000.\\n\"}},\"required\":[\"kind\"]},\"MemoryMessage\":{\"type\":\"object\",\"description\":\"A single message in conversation history\",\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"user\",\"assistant\",\"system\"]},\"content\":{\"type\":\"string\"}},\"required\":[\"role\",\"content\"]},\"MemoryManual\":{\"type\":\"object\",\"deprecated\":true,\"description\":\"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"manual\"]},\"messages\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/MemoryMessage\"}}},\"required\":[\"kind\",\"messages\"]},\"MemoryConfig\":{\"description\":\"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.\",\"oneOf\":[{\"$ref\":\"#/components/schemas/MemoryOff\"},{\"$ref\":\"#/components/schemas/MemoryWindow\"},{\"$ref\":\"#/components/schemas/MemoryCompaction\"},{\"$ref\":\"#/components/schemas/MemoryAuto\"},{\"$ref\":\"#/components/schemas/MemoryManual\"}],\"discriminator\":{\"propertyName\":\"kind\",\"mapping\":{\"off\":\"#/components/schemas/MemoryOff\",\"window\":\"#/components/schemas/MemoryWindow\",\"compaction\":\"#/components/schemas/MemoryCompaction\",\"auto\":\"#/components/schemas/MemoryAuto\",\"manual\":\"#/components/schemas/MemoryManual\"}}},\"StaticMemoryTransform\":{\"type\":\"object\",\"description\":\"Static memory configuration passed directly to the AI agent\",\"properties\":{\"value\":{\"$ref\":\"#/components/schemas/MemoryConfig\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\",\"value\"]},\"MemoryTransform\":{\"description\":\"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticMemoryTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticMemoryTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"FlowModuleValue\":{\"description\":\"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type\",\"oneOf\":[{\"$ref\":\"#/components/schemas/RawScript\"},{\"$ref\":\"#/components/schemas/PathScript\"},{\"$ref\":\"#/components/schemas/PathFlow\"},{\"$ref\":\"#/components/schemas/ForloopFlow\"},{\"$ref\":\"#/components/schemas/WhileloopFlow\"},{\"$ref\":\"#/components/schemas/BranchOne\"},{\"$ref\":\"#/components/schemas/BranchAll\"},{\"$ref\":\"#/components/schemas/Identity\"},{\"$ref\":\"#/components/schemas/AiAgent\"},{\"$ref\":\"#/components/schemas/AiDecision\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"rawscript\":\"#/components/schemas/RawScript\",\"script\":\"#/components/schemas/PathScript\",\"flow\":\"#/components/schemas/PathFlow\",\"forloopflow\":\"#/components/schemas/ForloopFlow\",\"whileloopflow\":\"#/components/schemas/WhileloopFlow\",\"branchone\":\"#/components/schemas/BranchOne\",\"branchall\":\"#/components/schemas/BranchAll\",\"identity\":\"#/components/schemas/Identity\",\"aiagent\":\"#/components/schemas/AiAgent\",\"aidecision\":\"#/components/schemas/AiDecision\"}}},\"RawScript\":{\"type\":\"object\",\"description\":\"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"content\":{\"type\":\"string\",\"description\":\"The script source code. Should export a 'main' function\"},\"language\":{\"type\":\"string\",\"description\":\"Programming language for this script\",\"enum\":[\"deno\",\"bun\",\"bunnative\",\"python3\",\"go\",\"bash\",\"powershell\",\"postgresql\",\"mysql\",\"bigquery\",\"snowflake\",\"mssql\",\"oracledb\",\"graphql\",\"nativets\",\"php\",\"rust\",\"ansible\",\"csharp\",\"nu\",\"java\",\"ruby\",\"rlang\",\"duckdb\"]},\"path\":{\"type\":\"string\",\"description\":\"Optional path for saving this script\"},\"lock\":{\"type\":\"string\",\"description\":\"Lock file content for dependencies\"},\"type\":{\"type\":\"string\",\"enum\":[\"rawscript\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing\"},\"concurrent_limit\":{\"type\":\"number\",\"description\":\"Maximum concurrent executions of this script\"},\"concurrency_time_window_s\":{\"type\":\"number\",\"description\":\"Time window for concurrent_limit\"},\"custom_concurrency_key\":{\"type\":\"string\",\"description\":\"Custom key for grouping concurrent executions\"},\"is_trigger\":{\"type\":\"boolean\",\"description\":\"If true, this script is a trigger that can start the flow\"},\"assets\":{\"type\":\"array\",\"description\":\"External resources this script accesses (S3 objects, resources, etc.)\",\"items\":{\"type\":\"object\",\"required\":[\"path\",\"kind\"],\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Path to the asset\"},\"kind\":{\"type\":\"string\",\"description\":\"Type of asset\",\"enum\":[\"s3object\",\"resource\",\"ducklake\",\"datatable\",\"volume\",\"dbt\"]},\"access_type\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Access level for this asset\",\"enum\":[\"r\",\"w\",\"rw\"]},\"alt_access_type\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Alternative access level\",\"enum\":[\"r\",\"w\",\"rw\"]}}}}},\"required\":[\"type\",\"content\",\"language\",\"input_transforms\"]},\"PathScript\":{\"type\":\"object\",\"description\":\"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"path\":{\"type\":\"string\",\"description\":\"Path to the script in the workspace (e.g., 'f/scripts/send_email')\"},\"hash\":{\"type\":\"string\",\"description\":\"Optional specific version hash of the script to use\"},\"type\":{\"type\":\"string\",\"enum\":[\"script\"]},\"tag_override\":{\"type\":\"string\",\"description\":\"Override the script's default worker group tag\"},\"is_trigger\":{\"type\":\"boolean\",\"description\":\"If true, this script is a trigger that can start the flow\"}},\"required\":[\"type\",\"path\",\"input_transforms\"]},\"PathFlow\":{\"type\":\"object\",\"description\":\"Reference to an existing flow by path. Use this to call another flow as a subflow\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"path\":{\"type\":\"string\",\"description\":\"Path to the flow in the workspace (e.g., 'f/flows/process_user')\"},\"type\":{\"type\":\"string\",\"enum\":[\"flow\"]}},\"required\":[\"type\",\"path\",\"input_transforms\"]},\"ForloopFlow\":{\"type\":\"object\",\"description\":\"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"iterator\":{\"description\":\"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'\",\"$ref\":\"#/components/schemas/InputTransform\"},\"skip_failures\":{\"type\":\"boolean\",\"description\":\"If true, iteration failures don't stop the loop. Failed iterations return null\"},\"type\":{\"type\":\"string\",\"enum\":[\"forloopflow\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency\"},\"parallelism\":{\"description\":\"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression\",\"$ref\":\"#/components/schemas/InputTransform\"},\"squash\":{\"type\":\"boolean\"}},\"required\":[\"modules\",\"iterator\",\"skip_failures\",\"type\"]},\"WhileloopFlow\":{\"type\":\"object\",\"description\":\"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute in each iteration\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"skip_failures\":{\"type\":\"boolean\",\"description\":\"If true, iteration failures don't stop the loop. Failed iterations return null\"},\"type\":{\"type\":\"string\",\"enum\":[\"whileloopflow\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, iterations run concurrently (use with caution in while loops)\"},\"parallelism\":{\"description\":\"Maximum number of concurrent iterations when parallel=true\",\"$ref\":\"#/components/schemas/InputTransform\"},\"squash\":{\"type\":\"boolean\"}},\"required\":[\"modules\",\"skip_failures\",\"type\"]},\"BranchOne\":{\"type\":\"object\",\"description\":\"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes\",\"properties\":{\"branches\":{\"type\":\"array\",\"description\":\"Array of branches to evaluate in order. The first branch with expr evaluating to true executes\",\"items\":{\"type\":\"object\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of this branch condition\"},\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins\"},\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute if this branch's expr is true\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}}},\"required\":[\"modules\",\"expr\"]}},\"default\":{\"type\":\"array\",\"description\":\"Steps to execute if no branch expressions match\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"type\":{\"type\":\"string\",\"enum\":[\"branchone\"]}},\"required\":[\"branches\",\"default\",\"type\"]},\"BranchAll\":{\"type\":\"object\",\"description\":\"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently\",\"properties\":{\"branches\":{\"type\":\"array\",\"description\":\"Array of branches that all execute (either in parallel or sequentially)\",\"items\":{\"type\":\"object\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of this branch's purpose\"},\"skip_failure\":{\"type\":\"boolean\",\"description\":\"If true, failure in this branch doesn't fail the entire flow\"},\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute in this branch\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}}},\"required\":[\"modules\"]}},\"type\":{\"type\":\"string\",\"enum\":[\"branchall\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, all branches execute concurrently. If false, they execute sequentially\"}},\"required\":[\"branches\",\"type\"]},\"AgentTool\":{\"type\":\"object\",\"description\":\"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')\"},\"summary\":{\"type\":\"string\",\"description\":\"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp, websearch or question tool it is a plain label. Put the human-readable explanation in 'description'.\"},\"description\":{\"type\":\"string\",\"description\":\"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script.\"},\"job_token_scopes\":{\"type\":\"array\",\"nullable\":true,\"items\":{\"type\":\"string\"},\"description\":\"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it.\"},\"requires_approval\":{\"type\":\"boolean\",\"description\":\"Flowmodule and mcp tools only. Each call waits for a person to approve or reject it from the flow's run page or chat, without the agent holding a worker. Calls in the same turn that do not require approval run right away. A rejected call, or one nobody answers within 30 minutes, is reported to the AI as not run.\"},\"value\":{\"$ref\":\"#/components/schemas/ToolValue\"}},\"required\":[\"id\",\"value\"]},\"ToolValue\":{\"description\":\"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference\",\"oneOf\":[{\"$ref\":\"#/components/schemas/FlowModuleTool\"},{\"$ref\":\"#/components/schemas/McpToolValue\"},{\"$ref\":\"#/components/schemas/WebsearchToolValue\"},{\"$ref\":\"#/components/schemas/QuestionToolValue\"}],\"discriminator\":{\"propertyName\":\"tool_type\",\"mapping\":{\"flowmodule\":\"#/components/schemas/FlowModuleTool\",\"mcp\":\"#/components/schemas/McpToolValue\",\"websearch\":\"#/components/schemas/WebsearchToolValue\",\"question\":\"#/components/schemas/QuestionToolValue\"}}},\"FlowModuleTool\":{\"description\":\"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module\",\"allOf\":[{\"type\":\"object\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"flowmodule\"]}},\"required\":[\"tool_type\"]},{\"$ref\":\"#/components/schemas/FlowModuleValue\"}]},\"WebsearchToolValue\":{\"type\":\"object\",\"description\":\"A tool implemented as a websearch tool. The AI can call this like any other websearch tool\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"websearch\"]}},\"required\":[\"tool_type\"]},\"QuestionToolValue\":{\"type\":\"object\",\"description\":\"Built-in tool the AI calls as ask_question: the agent stops, releasing its worker, until someone answers from the flow's run page or chat or the question times out, then resumes with the answer as the tool result.\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"question\"]},\"timeout\":{\"type\":\"integer\",\"description\":\"Seconds to wait for an answer before the question is reported to the AI as timed out. Defaults to 1800.\"}},\"required\":[\"tool_type\"]},\"McpToolValue\":{\"type\":\"object\",\"description\":\"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"mcp\"]},\"resource_path\":{\"type\":\"string\",\"description\":\"Path to the MCP resource/server configuration\"},\"include_tools\":{\"type\":\"array\",\"description\":\"Whitelist of specific tools to include from this MCP server\",\"items\":{\"type\":\"string\"}},\"exclude_tools\":{\"type\":\"array\",\"description\":\"Blacklist of tools to exclude from this MCP server\",\"items\":{\"type\":\"string\"}}},\"required\":[\"tool_type\",\"resource_path\"]},\"AiAgent\":{\"type\":\"object\",\"description\":\"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Input parameters for the AI agent mapped to their values\",\"properties\":{\"provider\":{\"$ref\":\"#/components/schemas/ProviderTransform\"},\"output_type\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n\"},\"user_message\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"The user's prompt/message to the AI agent. Supports variable interpolation with\\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\\nthe prompt; image output always needs it.\\n\"},\"system_prompt\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"System instructions that guide the AI's behavior, persona, and response style. Optional.\"},\"streaming\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n\"},\"memory\":{\"$ref\":\"#/components/schemas/MemoryTransform\"},\"memory_id\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Names the memory this step reads and writes, overriding the memory id the run\\nwas started with (the chat conversation, an app chat session or the `memory_id` run\\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\\nkey. When it evaluates to an empty value the agent runs without memory. Read only\\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\\nolder `auto` or `manual` memory reads neither history input.\\n\"},\"previous_messages\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\\nand the user message. Read only while `memory` is off or absent: managed memory\\nignores it, and an older `auto` or `manual` memory reads neither history input.\\n\"},\"output_schema\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n\"},\"user_attachments\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n\"},\"enabled_tools\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of strings naming which of the tools configured in `tools` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n\"},\"max_completion_tokens\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n\"},\"temperature\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n\"},\"max_iterations\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n\"},\"model\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Only on a step linked to a saved agent (see `agent`): replaces the model\\nsaved on the agent for this step's runs, on the agent's own provider resource. An\\nempty value keeps the saved model. Set it to an expression such as\\n`flow_input.model` to choose the model per run.\\n\"},\"reasoning_effort\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning\\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\\ndefault. Leave the input out to keep the saved effort, which holds only while the\\nstep runs the saved model. A step that is not linked sets both inside `provider`.\\n\"}}},\"tools\":{\"type\":\"array\",\"description\":\"Array of tools the agent can use. The agent decides which tools to call based on the task\",\"items\":{\"$ref\":\"#/components/schemas/AgentTool\"}},\"type\":{\"type\":\"string\",\"enum\":[\"aiagent\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)\"},\"omit_output_from_conversation\":{\"type\":\"boolean\",\"default\":false,\"description\":\"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.\"},\"agent\":{\"type\":\"string\",\"description\":\"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\\nand, optionally, the `model` and `reasoning_effort` overrides of what the agent saved.\\n\"},\"tool_inputs\":{\"type\":\"object\",\"description\":\"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n\",\"additionalProperties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}}},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, the agent can execute multiple tool calls in parallel\"}},\"required\":[\"type\",\"input_transforms\"]},\"AiDecision\":{\"type\":\"object\",\"description\":\"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\\nstate with calibrated probabilities, instead of generating text.\\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\\ncheap and its answers are structured. Its result is { output: { : answer },\\nmodel, usage }, so a later step reads e.g. results..output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults..output..choice. Usable as an AI agent tool, where the calling agent\\nsupplies the state.\\n\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Input parameters for the decision mapped to their values\",\"properties\":{\"provider\":{\"$ref\":\"#/components/schemas/ProviderTransform\"},\"state\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"What the questions are asked about: a string, an object or an array of strings.\\nAn object with descriptive keys holding only what the questions need works best.\\nExample: { message: flow_input.message, plan: results.a.plan }\\n\"},\"questions\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Object mapping each question name to { type, instructions, criteria }, where type is:\\n- 'choice': criteria maps each option to its description (up to 255); the answer\\n has choice, probabilities and confidence\\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\\n has score, legend, probabilities and confidence\\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\\n noul, the probability of yes (0 to 1)\\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\\n\"}},\"required\":[\"provider\",\"state\",\"questions\"]},\"type\":{\"type\":\"string\",\"enum\":[\"aidecision\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)\"}},\"required\":[\"type\",\"input_transforms\"]},\"Identity\":{\"type\":\"object\",\"description\":\"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"identity\"]},\"flow\":{\"type\":\"boolean\",\"description\":\"If true, marks this as a flow identity (special handling)\"}},\"required\":[\"type\"]},\"FlowStatus\":{\"type\":\"object\",\"properties\":{\"step\":{\"type\":\"integer\"},\"modules\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/FlowStatusModule\"}},\"user_states\":{\"additionalProperties\":true},\"preprocessor_module\":{\"allOf\":[{\"$ref\":\"#/components/schemas/FlowStatusModule\"}]},\"failure_module\":{\"allOf\":[{\"$ref\":\"#/components/schemas/FlowStatusModule\"},{\"type\":\"object\",\"properties\":{\"parent_module\":{\"type\":\"string\"}}}]},\"retry\":{\"type\":\"object\",\"properties\":{\"fail_count\":{\"type\":\"integer\"},\"failed_jobs\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}}}}},\"required\":[\"step\",\"modules\",\"failure_module\"]},\"FlowStatusModule\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"WaitingForPriorSteps\",\"WaitingForEvents\",\"WaitingForExecutor\",\"InProgress\",\"Success\",\"Failure\"]},\"id\":{\"type\":\"string\"},\"job\":{\"type\":\"string\",\"format\":\"uuid\"},\"count\":{\"type\":\"integer\"},\"progress\":{\"type\":\"integer\"},\"iterator\":{\"type\":\"object\",\"properties\":{\"index\":{\"type\":\"integer\"},\"itered\":{\"type\":\"array\",\"items\":{}},\"itered_len\":{\"type\":\"integer\"},\"args\":{}}},\"flow_jobs\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"flow_jobs_success\":{\"type\":\"array\",\"items\":{\"type\":\"boolean\"}},\"flow_jobs_duration\":{\"type\":\"object\",\"properties\":{\"started_at\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"duration_ms\":{\"type\":\"array\",\"items\":{\"type\":\"integer\"}}}},\"branch_chosen\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"branch\",\"default\"]},\"branch\":{\"type\":\"integer\"}},\"required\":[\"type\"]},\"branchall\":{\"type\":\"object\",\"properties\":{\"branch\":{\"type\":\"integer\"},\"len\":{\"type\":\"integer\"}},\"required\":[\"branch\",\"len\"]},\"approvers\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"resume_id\":{\"type\":\"integer\"},\"approver\":{\"type\":\"string\"}},\"required\":[\"resume_id\",\"approver\"]}},\"failed_retries\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}},\"skipped\":{\"type\":\"boolean\"},\"agent_actions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"oneOf\":[{\"type\":\"object\",\"properties\":{\"job_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"function_name\":{\"type\":\"string\"},\"type\":{\"type\":\"string\",\"enum\":[\"tool_call\"]},\"module_id\":{\"type\":\"string\"}},\"required\":[\"job_id\",\"function_name\",\"type\",\"module_id\"]},{\"type\":\"object\",\"properties\":{\"call_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"function_name\":{\"type\":\"string\"},\"resource_path\":{\"type\":\"string\"},\"type\":{\"type\":\"string\",\"enum\":[\"mcp_tool_call\"]},\"arguments\":{\"type\":\"object\"}},\"required\":[\"call_id\",\"function_name\",\"resource_path\",\"type\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"web_search\"]}},\"required\":[\"type\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"approval\"]},\"call_id\":{\"type\":\"string\"},\"calls\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"function_name\":{\"type\":\"string\"},\"arguments\":{}},\"required\":[\"function_name\",\"arguments\"]}},\"expires_at\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"call_id\",\"calls\",\"expires_at\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"question\"]},\"call_id\":{\"type\":\"string\"},\"question\":{\"type\":\"string\"},\"choices\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"answers the model proposes; a free-text answer is always possible\"},\"multi_select\":{\"type\":\"boolean\",\"description\":\"whether several choices can be picked together\"},\"expires_at\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"call_id\",\"question\",\"expires_at\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"message\"]}},\"required\":[\"content\",\"type\"]}]}},\"agent_actions_success\":{\"type\":\"array\",\"items\":{\"type\":\"boolean\"}}},\"required\":[\"type\"]}}", "resource": "# Global draft resource & variable instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- A resource draft is a workspace item: `{ type: 'resource', path, summary?, value, isDraft }`. `value` is a CreateResource body: `{ path, value, description?, resource_type, labels? }` where the inner `value` is the resource type's data shape.\n- Reading a variable returns `{ type: 'variable', path, summary?, isSecret, isDraft }` — never its value, secret or not. `isSecret` tells you whether the value is encrypted.\n- `write_variable` takes `{ path, value?, is_secret?, description?, is_oauth?, expires_at?, value_valid_until?, labels? }`. Creating a variable needs `value` and `is_secret`; editing one needs only the fields you are changing. Omitting `value` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any `value` you did not get from the user destroys it.\n- For secret fields in a resource value, create the variable with `write_variable` and `is_secret: true`, and deploy it before the resource (see \"Secrets\" in the reference below).\n- Reference formats inside resource values: `$var:g/all/name` (global), `$var:u/user/name` (user), `$var:f/folder/name` (folder). Reference another resource with `$res:path/to/resource`. The same strings are also how a resource or variable is passed as a run argument (see the run-argument rule in the resource reference below); what they are never valid as is a variable's own value.\n- Use `search_resource_types` to discover valid `resource_type` names and their JSON Schemas. Match the resource value to that schema.\n- For an agent (an `ai_agent` resource), call `get_instructions` with `subject: \"agent\"` instead.\n- For OAuth resources, the `is_oauth: true` flag is managed by Windmill's OAuth flow; global mode generally creates manual resources, not OAuth ones.\n\n# Windmill resource & variable reference\n\n# Windmill Resources\n\nResources store credentials and configuration for external services.\n\n## Resource Structure\n\n```json\n{\n \"value\": {\n \"host\": \"db.example.com\",\n \"port\": 5432,\n \"user\": \"admin\",\n \"password\": \"$var:g/all/db_password\",\n \"dbname\": \"production\"\n },\n \"description\": \"Production PostgreSQL database\",\n \"resource_type\": \"postgresql\"\n}\n```\n\n## Required Fields\n\n- `value` - Object containing the resource configuration\n- `resource_type` - Name of the resource type (e.g., \"postgresql\", \"slack\")\n\n## Agents\n\nAn agent, as the Agents page lists it, is a resource of type `ai_agent`. Its value holds the\nagent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by\nlinking its path.\n\n## Variable References\n\nReference variables in resource values:\n\n```json\n{\n \"value\": {\n \"api_key\": \"$var:g/all/api_key\",\n \"secret\": \"$var:u/admin/secret\"\n }\n}\n```\n\n**Reference formats:**\n- `$var:g/all/name` - Global variable\n- `$var:u/username/name` - User variable\n- `$var:f/folder/name` - Folder variable\n\n## Secrets\n\nNever put a secret (password, API key, token) inline in a resource value. Store it in a secret variable and reference that variable as `$var:`.\n\n- `$var:` is a reference, not a value: it resolves to the variable's value at run time. Never invent a value for a variable.\n- A resource that references a variable needs the variable to exist first, so create or deploy the variable before the resource.\n\n## Resource References\n\nReference other resources:\n\n```json\n{\n \"value\": {\n \"database\": \"$res:f/databases/postgres\"\n }\n}\n```\n\n## Passing a Resource or Variable as a Run Argument\n\nA script or flow argument typed as a resource (schema `format: resource-`) is passed as\nthe **bare string** `$res:` — the whole argument value. Same for a variable, with\n`$var:`. This applies everywhere job arguments are supplied: `wmill script run/preview`,\n`wmill flow run/preview`, the `runScriptByPath` / `runFlowByPath` API, a schedule's `args`, a\ntrigger's configured static args.\n\n```json\n{\n \"db\": \"$res:f/databases/postgres_prod\",\n \"api_token\": \"$var:g/all/api_token\"\n}\n```\n\nThe reference is resolved when the job runs, under the job's run-as identity — the caller for an\nordinary run, but the configured principal for a schedule, a trigger, or a runnable set to run on\nbehalf of someone else. The run fails if that identity cannot read the referenced resource or\nvariable.\n\n**Never wrap it in an object.** The resolver only rewrites a JSON value that *is* a string\nstarting with `$res:` / `$var:`; keys are never inspected. These are all wrong and are passed\nthrough to the script unchanged:\n\n```json\n{ \"db\": { \"$res\": \"f/databases/postgres_prod\" } }\n{ \"db\": { \"resource\": \"f/databases/postgres_prod\" } }\n{ \"db\": \"f/databases/postgres_prod\" }\n```\n\nThe string may sit anywhere a string can — a top-level argument, a nested object field\n(`{ \"gh_auth\": { \"token\": \"$var:g/all/gh_token\" } }`), or an array element (array elements are\nwalked only while nested at most two levels deep, and only for arrays of at most 1000 items).\nThe prefix must be on the string itself.\n\n## Common Resource Types\n\n### PostgreSQL\n```json\n{\n \"resource_type\": \"postgresql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"user\": \"postgres\",\n \"password\": \"$var:g/all/pg_password\",\n \"dbname\": \"windmill\",\n \"sslmode\": \"prefer\"\n }\n}\n```\n\n### MySQL\n```json\n{\n \"resource_type\": \"mysql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"$var:g/all/mysql_password\",\n \"database\": \"myapp\"\n }\n}\n```\n\n### Slack\n```json\n{\n \"resource_type\": \"slack\",\n \"value\": {\n \"token\": \"$var:g/all/slack_token\"\n }\n}\n```\n\n### AWS S3\n```json\n{\n \"resource_type\": \"s3\",\n \"value\": {\n \"bucket\": \"my-bucket\",\n \"region\": \"us-east-1\",\n \"accessKeyId\": \"$var:g/all/aws_access_key\",\n \"secretAccessKey\": \"$var:g/all/aws_secret_key\"\n }\n}\n```\n\n### HTTP/API\n```json\n{\n \"resource_type\": \"http\",\n \"value\": {\n \"baseUrl\": \"https://api.example.com\",\n \"headers\": {\n \"Authorization\": \"Bearer $var:g/all/api_token\"\n }\n }\n}\n```\n\n### Kafka\n```json\n{\n \"resource_type\": \"kafka\",\n \"value\": {\n \"brokers\": \"broker1:9092,broker2:9092\",\n \"sasl_mechanism\": \"PLAIN\",\n \"security_protocol\": \"SASL_SSL\",\n \"username\": \"$var:g/all/kafka_user\",\n \"password\": \"$var:g/all/kafka_password\"\n }\n}\n```\n\n### NATS\n```json\n{\n \"resource_type\": \"nats\",\n \"value\": {\n \"servers\": [\"nats://localhost:4222\"],\n \"user\": \"$var:g/all/nats_user\",\n \"password\": \"$var:g/all/nats_password\"\n }\n}\n```\n\n### MQTT\n```json\n{\n \"resource_type\": \"mqtt\",\n \"value\": {\n \"host\": \"mqtt.example.com\",\n \"port\": 8883,\n \"username\": \"$var:g/all/mqtt_user\",\n \"password\": \"$var:g/all/mqtt_password\",\n \"tls\": true\n }\n}\n```\n\n## When No Resource Type Fits\n\nThe Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service:\n\n- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both.\n- Otherwise, or when the user prefers it to syncing, propose a custom resource type named `c_` holding the service's connection fields (base URL, account or region identifiers, credentials), as in \"Custom Resource Types\" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields.\n- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references.\n\n## Custom Resource Types\n\nA custom type's name starts with `c_`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: `format: resource-c_custom_api`, `RT.CCustomApi` in TypeScript, a `c_custom_api` TypedDict in Python.\n\nCreate custom resource types with JSON Schema:\n\n```json\n{\n \"name\": \"c_custom_api\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"base_url\": {\"type\": \"string\", \"format\": \"uri\"},\n \"api_key\": {\"type\": \"string\"},\n \"timeout\": {\"type\": \"integer\", \"default\": 30}\n },\n \"required\": [\"base_url\", \"api_key\"]\n },\n \"description\": \"Custom API connection\"\n}\n```\n\nSave as: `c_custom_api.resource-type.json`\n\n## OAuth Resources\n\nOAuth resources are managed through the Windmill UI and marked:\n\n```json\n{\n \"is_oauth\": true,\n \"account\": 123\n}\n```\n\nOAuth tokens are automatically refreshed by Windmill.\n\n## Using Resources in Scripts\n\n### TypeScript (Bun/Deno)\n```typescript\nexport async function main(db: RT.Postgresql) {\n // db contains the resource values\n const { host, port, user, password, dbname } = db;\n}\n```\n\n### Python\n```python\nclass postgresql(TypedDict):\n host: str\n port: int\n user: str\n password: str\n dbname: str\n\ndef main(db: postgresql):\n # db contains the resource values\n pass\n```\n\n", - "app": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u//` for bare names; only use `f//` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend//main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the TypeScript SDK. For a `python3` runnable, call `get_instructions` again with `subject: \"app\"` and `language: \"python3\"`.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `
` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render()\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**Set the browser tab title with `document.title = '...'`** (or a `` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.\n\n**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\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<any>\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<string>\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<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\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<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\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<string>): Promise<void>\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<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\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<any>\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<any>\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<any>\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<string>\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<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\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<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\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<string, any> | 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<string>\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<any>\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<void>\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<void>\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<void>\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<number | null>\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<boolean>\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<void>\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise<any>\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<any>\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<string>\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<void>\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<string>\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any>\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<DenoS3LightClientSettings>\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<Uint8Array | undefined>\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<Blob | undefined>\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<S3Object>\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<void>\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<S3Object[]>\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<S3Object>\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<string[]>\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<string>\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<string>\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<void>} 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<void>\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<void>} 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<void>\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise<void>\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<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>>\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<any>\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<any>\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<T>(fn: (...args: any[]) => Promise<T>): 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<T, R>(items: T[], fn: (item: T) => PromiseLike<R> | R, options?: { concurrency?: number },): Promise<R[]>\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<void>\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<any>\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<DucklakeMaterializeOptions, \"uniqueKey\">,): SqlStatement<any>\n", - "app.python3": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u/<current-user>/<name>` for bare names; only use `f/<folder>/<name>` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend/<key>/main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the Python SDK, for `python3` inline runnables. For a `bun` runnable, call `get_instructions` again with `subject: \"app\"` and no language.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id=\"root\">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.\n\n**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# Python SDK (wmill)\n\nImport: import wmill\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 functions below are the surface to prefer. For an endpoint none of them covers,\nwmill.Windmill().get(endpoint) and .post(endpoint) issue an authenticated request against this\ninstance. What does not exist is a function name you guessed at: if it is not listed below, do\nnot call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`os.environ.get(\"WM_END_USER_EMAIL\") or os.environ.get(\"WM_EMAIL\")`. WM_END_USER_EMAIL is the app\nviewer when the run was triggered from an app and empty otherwise (both variables are always\ndefined), WM_EMAIL is the user the job is permissioned as. WM_USERNAME is the matching username.\n\ndef worker_has_internal_server() -> bool\n\ndef get_mocked_api() -> Optional[dict]\n\n# Get the HTTP client instance.\n# \n# Returns:\n# Configured httpx.Client for API requests\ndef get_client() -> httpx.Client\n\n# Make an HTTP GET request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Make an HTTP POST request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.post\n# \n# Returns:\n# HTTP response object\ndef post(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Create a new authentication token.\n# \n# Args:\n# duration: Token validity duration (default: 1 day)\n# \n# Returns:\n# New authentication token string\ndef create_token(duration = dt.timedelta(days=1)) -> str\n\n# Create a script job by path and return its job id.\n# \n# ``retry`` re-runs the job when it fails, with the policy a schedule takes,\n# e.g. ``{\"constant\": {\"attempts\": 3, \"seconds\": 10}}``. The returned id is\n# the first attempt's; each retry is a job of its own, recorded as a child of it.\ndef run_script_by_path_async(path: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a script job by hash and return its job id. See ``run_script_by_path_async`` for ``retry``.\ndef run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a flow job and return its job id.\ndef run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str\n\n# Run script by path synchronously and return its result.\ndef run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run script by hash synchronously and return its result.\ndef run_script_by_hash(hash_: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run a script on the current worker without creating a job.\n# \n# On agent workers (no internal server), falls back to running a normal\n# preview job and waiting for the result.\ndef run_inline_script_preview(content: str, language: str, args: dict = None) -> Any\n\n# Wait for a job to complete and return its result.\n# \n# Args:\n# job_id: ID of the job to wait for\n# timeout: Maximum time to wait (seconds or timedelta)\n# verbose: Enable verbose logging\n# cleanup: Register cleanup handler to cancel job on exit\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result when completed\n# \n# Raises:\n# TimeoutError: If timeout is reached\n# Exception: If job fails\ndef wait_job(job_id, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False)\n\n# Cancel a specific job by ID.\n# \n# Args:\n# job_id: UUID of the job to cancel\n# reason: Optional reason for cancellation\n# \n# Returns:\n# Response message from the cancel endpoint\ndef cancel_job(job_id: str, reason: str = None) -> str\n\n# Cancel currently running executions of the same script.\ndef cancel_running() -> dict\n\n# Get job details by ID.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job details dictionary\ndef get_job(job_id: str) -> dict\n\n# Get the root job ID for a flow hierarchy.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Root job ID\ndef get_root_job_id(job_id: str | None = None) -> dict\n\n# Get an OIDC JWT token for authentication to external services.\n# \n# Args:\n# audience: Token audience (e.g., \"vault\", \"aws\")\n# expires_in: Optional expiration time in seconds\n# \n# Returns:\n# JWT token string\ndef get_id_token(audience: str, expires_in: int | None = None) -> str\n\n# Get the status of a job.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job status: \"RUNNING\", \"WAITING\", or \"COMPLETED\"\ndef get_job_status(job_id: str) -> JobStatus\n\n# Get the result of a completed job.\n# \n# Args:\n# job_id: UUID of the completed job\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result\ndef get_result(job_id: str, assert_result_is_not_none: bool = True) -> Any\n\n# Get a variable value by path.\n# \n# Args:\n# path: Variable path in Windmill\n# \n# Returns:\n# Variable value as string\ndef get_variable(path: str) -> str\n\n# Set a variable value by path, creating it if it doesn't exist.\n# \n# Args:\n# path: Variable path in Windmill\n# value: Variable value to set\n# is_secret: Whether the variable should be secret (default: False)\ndef set_variable(path: str, value: str, is_secret: bool = False) -> None\n\n# Get a resource value by path.\n# \n# Args:\n# path: Resource path in Windmill\n# none_if_undefined: Return None instead of raising if not found\n# interpolated: if variables and resources are fully unrolled\n# \n# Returns:\n# Resource value dictionary or None\ndef get_resource(path: str, none_if_undefined: bool = False, interpolated: bool = True) -> dict | None\n\n# Set a resource value by path, creating it if it doesn't exist.\n# \n# Args:\n# value: Resource value to set\n# path: Resource path in Windmill\n# resource_type: Resource type for creation\ndef set_resource(value: Any, path: str, resource_type: str)\n\n# List resources from Windmill workspace.\n# \n# Args:\n# resource_type: Optional resource type to filter by (e.g., \"postgresql\", \"mysql\", \"s3\")\n# page: Optional page number for pagination\n# per_page: Optional number of results per page\n# \n# Returns:\n# List of resource dictionaries\ndef list_resources(resource_type: str = None, page: int = None, per_page: int = None) -> list[dict]\n\n# Set the workflow state.\n# \n# Args:\n# value: State value to set\n# path: Optional state resource path override.\ndef set_state(value: Any, path: str | None = None) -> None\n\n# Get the workflow state.\n# \n# Args:\n# path: Optional state resource path override.\n# \n# Returns:\n# State value or None if not set\ndef get_state(path: str | None = None) -> Any\n\n# Set job progress percentage (0-99).\n# \n# Args:\n# value: Progress percentage\n# job_id: Job ID (defaults to current WM_JOB_ID)\ndef set_progress(value: int, job_id: Optional[str] = None)\n\n# Get job progress percentage.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Progress value (0-100) or None if not set\ndef get_progress(job_id: Optional[str] = None) -> Any\n\n# Whether the worker running the job has received its shutdown signal.\n# \n# A draining worker waits for its current job to finish before exiting. A long-running\n# script can poll this and return early so the worker can be replaced.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# True if the worker running the job is draining\ndef worker_is_draining(job_id: Optional[str] = None) -> bool\n\n# Set the user state of a flow at a given key\ndef set_flow_user_state(key: str, value: Any) -> None\n\n# Get the user state of a flow at a given key\ndef get_flow_user_state(key: str) -> Any\n\n# Get the Windmill server version.\n# \n# Returns:\n# Version string\ndef version()\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy\n# serves object reads, writes, deletes, listing and multipart uploads of that bucket only;\n# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials,\n# which passing the resource path returns.\ndef get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Load a file from the workspace s3 bucket and returns its content as bytes.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# my_obj_content = client.load_s3_file(s3_obj)\n# file_content = my_obj_content.decode(\"utf-8\")\n# '''\ndef load_s3_file(s3object: S3Object | str, s3_resource_path: str | None) -> bytes\n\n# Load a file from the workspace s3 bucket and returns the bytes stream.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# with wmill.load_s3_file_reader(s3object, s3_resource_path) as file_reader:\n# print(file_reader.read())\n# '''\ndef load_s3_file_reader(s3object: S3Object | str, s3_resource_path: str | None) -> BufferedReader\n\n# Write a file to the workspace S3 bucket\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# \n# # for an in memory bytes array:\n# file_content = b'Hello Windmill!'\n# client.write_s3_file(s3_obj, file_content)\n# \n# # for a file:\n# with open(\"my_file.txt\", \"rb\") as my_file:\n# client.write_s3_file(s3_obj, my_file)\n# '''\ndef write_s3_file(s3object: S3Object | str | None, file_content: BufferedReader | bytes, s3_resource_path: str | None, content_type: str | None = None, content_disposition: str | None = None) -> S3Object\n\n# Permanently delete a file from the workspace S3 bucket.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# client.delete_s3_object(s3_obj)\n# '''\ndef delete_s3_object(s3object: S3Object | str, s3_resource_path: str | None = None) -> None\n\n# Sign S3 objects for use by anonymous users in public apps.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed S3 objects\ndef sign_s3_objects(s3_objects: list[S3Object | str], expiry_secs: int | None = None) -> list[S3Object]\n\n# Sign a single S3 object for use by anonymous users in public apps.\n# \n# Args:\n# s3_object: S3 object to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed S3 object\ndef sign_s3_object(s3_object: S3Object | str, expiry_secs: int | None = None) -> S3Object\n\n# Generate presigned public URLs for an array of S3 objects.\n# If an S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# base_url: Optional base URL for the presigned URLs (defaults to WM_BASE_URL)\n# expiry_secs: How long the signatures stay valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed public URLs\n# \n# Example:\n# >>> s3_objs = [S3Object(s3=\"/path/to/file1.txt\"), S3Object(s3=\"/path/to/file2.txt\")]\n# >>> urls = client.get_presigned_s3_public_urls(s3_objs)\ndef get_presigned_s3_public_urls(s3_objects: list[S3Object | str], base_url: str | None = None, expiry_secs: int | None = None) -> list[str]\n\n# Generate a presigned public URL for an S3 object.\n# If the S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_object: S3 object to sign\n# base_url: Optional base URL for the presigned URL (defaults to WM_BASE_URL)\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed public URL\n# \n# Example:\n# >>> s3_obj = S3Object(s3=\"/path/to/file.txt\")\n# >>> url = client.get_presigned_s3_public_url(s3_obj)\ndef get_presigned_s3_public_url(s3_object: S3Object | str, base_url: str | None = None, expiry_secs: int | None = None) -> str\n\n# Get the current user information.\n# \n# Returns:\n# User details dictionary\ndef whoami() -> dict\n\n# Get the current user information (alias for whoami).\n# \n# Returns:\n# User details dictionary\ndef user() -> dict\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef state_path() -> str\n\n# Get the workflow state.\n# \n# Returns:\n# State value or None if not set\ndef state() -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state_pickle(value: Any, path: str = 'state.pickle') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state_pickle(path: str = 'state.pickle') -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state(value: Any, path: str = 'state.json') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state(path: str = 'state.json') -> None\n\n# Get URLs needed for resuming a flow after suspension.\n# \n# Args:\n# approver: Optional approver name\n# flow_level: If True, generate resume URLs for the parent flow instead of the\n# specific step. This allows pre-approvals that can be consumed by any later\n# suspend step in the same flow.\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_resume_urls(approver: str = None, flow_level: bool = None) -> dict\n\n# Get the resume URLs bound to one ``wait_for_approval`` step of this workflow.\n# \n# Args:\n# step_key: Checkpoint key of the approval step, as passed to\n# ``wait_for_approval(key=...)``\n# approver: Optional approver name\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_approval_urls(step_key: str = 'approval', approver: str = None) -> dict\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, use the \"Advanced -> Suspend -> Form\" functionality.\n# Learn more at: https://www.windmill.dev/docs/flows/flow_approval#form\n# \n# :param slack_resource_path: The path to the Slack resource in Windmill.\n# :type slack_resource_path: str\n# :param channel_id: The Slack channel ID where the approval request will be sent.\n# :type channel_id: str\n# :param message: Optional custom message to include in the Slack approval request.\n# :type message: str, optional\n# :param approver: Optional user ID or name of the approver for the request.\n# :type approver: str, optional\n# :param default_args_json: Optional dictionary defining or overriding the default arguments for form fields.\n# :type default_args_json: dict, optional\n# :param dynamic_enums_json: Optional dictionary overriding the enum default values of enum form fields.\n# :type dynamic_enums_json: dict, optional\n# \n# :raises Exception: If the function is not called within a flow or flow preview.\n# :raises Exception: If the required flow job or flow step environment variables are not set.\n# \n# :return: None\n# \n# **Usage Example:**\n# >>> client.request_interactive_slack_approval(\n# ... slack_resource_path=\"/u/alex/my_slack_resource\",\n# ... channel_id=\"admins-slack-channel\",\n# ... message=\"Please approve this request\",\n# ... approver=\"approver123\",\n# ... default_args_json={\"key1\": \"value1\", \"key2\": 42},\n# ... dynamic_enums_json={\"foo\": [\"choice1\", \"choice2\"], \"bar\": [\"optionA\", \"optionB\"]},\n# ... )\n# \n# **Notes:**\n# - This function must be executed within a Windmill flow or flow preview.\n# - The function checks for required environment variables (`WM_FLOW_JOB_ID`, `WM_FLOW_STEP_ID`) to ensure it is run in the appropriate context.\ndef request_interactive_slack_approval(slack_resource_path: str, channel_id: str, message: str = None, approver: str = None, default_args_json: dict = None, dynamic_enums_json: dict = None) -> None\n\n# Send a message to a Microsoft Teams conversation with conversation_id, where success is used to style the message\ndef send_teams_message(conversation_id: str, text: str, success: bool = True, card_block: dict = None)\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# 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\n# tenant of.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None)\n\n# Get a DuckLake client for DuckDB queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# \n# Returns:\n# DucklakeClient instance\ndef ducklake(name: str = 'main')\n\ndef init_global_client(f)\n\ndef deprecate(in_favor_of: str)\n\n# Get the current workspace ID.\n# \n# Returns:\n# Workspace ID string\ndef get_workspace() -> str\n\ndef get_version() -> str\n\n# Create a script job and return its job ID.\n# \n# Args:\n# hash_or_path: Script hash or path (determined by presence of '/')\n# args: Script arguments\n# scheduled_in_secs: Delay before execution in seconds\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Job ID string\ndef run_script_async(hash_or_path: str, args: Dict[str, Any] = None, scheduled_in_secs: int = None, tag: str = None) -> str\n\n# Run a script synchronously by hash and return its result.\n# \n# Args:\n# hash: Script hash\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_sync(hash: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Run a script synchronously by path and return its result.\n# \n# Args:\n# path: Script path\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_by_path_sync(path: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB\ndef duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars\ndef polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3\ndef boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef get_state_path() -> str\n\n# Parse resource syntax from string.\ndef parse_resource_syntax(s: str) -> Optional[str]\n\n# Parse S3 object from a `s3://<storage>/<key>` URI string (`s3:///<key>`\n# for the default storage) or S3Object format. Any other string raises\n# rather than falling back to an auto-generated key: an auto key is\n# requested by omitting the object, and a fallback would silently misplace\n# the upload on any typo.\ndef parse_s3_object(s3_object: S3Object | str) -> S3Object\n\n# Parse variable syntax from string.\ndef parse_variable_syntax(s: str) -> Optional[str]\n\n# Append a text to the result stream.\n# \n# Args:\n# text: text to append to the result stream\ndef append_to_result_stream(text: str) -> None\n\n# Stream to the result stream.\n# \n# Args:\n# stream: stream to stream to the result stream\ndef stream_result(stream) -> None\n\n# Execute a SQL query against the DataTable.\n# \n# Args:\n# sql: SQL query string with $1, $2, etc. placeholders\n# *args: Positional arguments to bind to query placeholders\n# \n# Returns:\n# SqlQuery instance for fetching results\ndef query(sql: str, *args) -> SqlQuery\n\n# Idempotently materialize the rows of `select_sql` into ducklake\n# `table` for one `partition` (or the whole table when `partition` is\n# None). Client-side equivalent of the `// materialize` engine: with\n# `unique_key` it upserts within the slice (delete-by-key + insert);\n# without it, it replaces (whole table → CREATE OR REPLACE; partition →\n# delete the partition + insert). Re-running the same slice is safe — the\n# backfill / failure-recovery contract.\n# \n# The partition value is bound as a DuckDB arg (never string-interpolated)\n# so it cannot inject SQL. `select_sql` is trusted (your own query).\ndef upsert_partition(table: str, select_sql: str, partition: str = None, unique_key: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# INSERT-only materialization (no dedup / no replace) for an immutable\n# event-log table — for one `partition`, or the whole table when\n# `partition` is None. NOTE: unlike `upsert_partition`, re-running the same\n# slice duplicates rows — use only for append-only sources.\ndef append_partition(table: str, select_sql: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Read a materialized ducklake table, optionally a single partition.\ndef read(table: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Execute query and fetch results.\n# \n# Args:\n# result_collection: Optional result collection mode\n# \n# Returns:\n# Query results\ndef fetch(result_collection: str | None = None)\n\n# Execute query and fetch first row of results.\n# \n# Returns:\n# First row of query results\ndef fetch_one()\n\n# Execute query and fetch first row of results. Return result as a scalar value.\n# \n# Returns:\n# First row of query result as a scalar value\ndef fetch_one_scalar()\n\n# Execute query and don't return any results.\n# \ndef execute()\n\n# DuckDB executor requires explicit argument types at declaration\n# These types exist in both DuckDB and Postgres\n# Check that the types exist if you plan to extend this function for other SQL engines.\ndef infer_sql_type(value) -> str\n\ndef parse_sql_client_name(name: str) -> tuple[str, Optional[str]]\n\n# Decorator that marks a function as a workflow task.\n# \n# Works in both WAC v1 (sync, HTTP-based dispatch) and WAC v2\n# (async, checkpoint/replay) modes:\n# \n# - **v2 (inside @workflow)**: dispatches as a checkpoint step.\n# - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API.\n# - **Standalone, or called from inside another v2 task**: executes the\n# function body directly. A task runs as a single job, so the tasks it\n# calls run in that same job, without their own options.\n# \n# A task runs as its own job, so its result is always encoded as JSON and\n# decoded back before the caller sees it: a ``datetime`` comes back as a\n# string, a tuple as a list.\n# \n# ``retry`` re-dispatches the task after a failure, inside ``@workflow`` only.\n# Every attempt is a step of its own (``call_api``, ``call_api#2``, ...) and\n# the wait between two of them is a durable sleep, so a retrying task holds no\n# worker while it backs off. Keys: ``attempts`` (retries after the first\n# failure, a whole number from 0 to 100), ``delay`` (seconds before the first\n# retry, sub-second delays dropped), ``multiplier`` (applied to the delay\n# after each attempt, 1 keeps it constant), ``max_delay`` (ceiling in\n# seconds). ``attempts`` is required, and an out-of-range or unknown key is\n# rejected where the policy is written.\n# \n# A workflow sleeps once per round, so tasks backing off in the same fan-out\n# wait one after another rather than together: the delay before a fan-out\n# retries is the sum of every backoff pending in it, not the longest one, and\n# it grows with both the width of the fan-out and ``attempts``. Retries with\n# no ``delay`` all go out in a single round.\n# \n# ``cache_ttl`` serves a previous result of the task for that many seconds\n# instead of running it again. A task is keyed on its step key (its name and\n# call order) and the workflow's input, not on the arguments it is called\n# with, so cache one only when whether it runs, and what it receives, follow\n# from the workflow's input alone. A ``task_script`` target is keyed on the\n# arguments it is called with. It has no effect on a ``task_flow`` target,\n# which keeps its flow's own cache policy.\n# \n# Usage::\n# \n# @task\n# async def extract_data(url: str): ...\n# \n# @task(path=\"f/external_script\", timeout=600, tag=\"gpu\")\n# async def run_external(x: int): ...\n# \n# @task(retry={\"attempts\": 3, \"delay\": 30, \"multiplier\": 2})\n# async def call_api(payload: dict): ...\ndef task(_func = None, *, path: Optional[str] = None, tag: Optional[str] = None, timeout: Optional[int] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill script.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# extract = task_script(\"f/data/extract\", timeout=600)\n# \n# @workflow\n# async def main():\n# data = await extract(url=\"https://...\")\ndef task_script(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill flow.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# pipeline = task_flow(\"f/etl/pipeline\", priority=10)\n# \n# @workflow\n# async def main():\n# result = await pipeline(input=data)\ndef task_flow(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Decorator marking 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.\ndef workflow(func)\n\n# Execute ``fn`` inline and checkpoint the result.\n# \n# On replay the cached value is returned without re-executing ``fn``.\n# Use for lightweight deterministic operations (timestamps, random IDs,\n# config reads) that should not incur the overhead of a child job.\n# \n# ``fn``'s result is encoded as JSON and decoded back before it is returned,\n# so the round that runs the body sees the same types every replay sees:\n# a ``datetime`` comes back as a string, a tuple as a list.\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.\nasync def step(name: str, fn)\n\n# Server-side sleep — suspend the workflow for the given duration without holding a worker.\n# \n# Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``.\n# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``.\nasync def sleep(seconds: int)\n\n# Suspend the workflow and wait for an external approval.\n# \n# Pass ``key`` to name the step, then ``get_approval_urls(key)`` yields the URLs\n# that resume exactly this approval — route them through your own channel.\n# Without a key the steps are named ``approval``, ``approval_2``, ...\n# \n# Returns a dict with ``value`` (form data), ``approver``, and ``approved``.\n# \n# Args:\n# timeout: Approval timeout in seconds (default 1800).\n# form: Optional form schema for the approval page.\n# self_approval: Whether the user who triggered the flow can approve it (default True).\n# key: Optional checkpoint key naming this approval step.\n# skin: ``\"minimal\"`` shows approvers only the request (form and approve/reject)\n# instead of the detailed page with the workflow's details.\n# description: Shown to approvers above the form: a string, or a rich value such as\n# ``{\"markdown\": \"...\"}``.\n# \n# Example::\n# \n# urls = await step(\"urls\", lambda: get_approval_urls(\"manager\"))\n# await step(\"notify\", lambda: send_email(urls[\"resume\"], urls[\"cancel\"]))\n# result = await wait_for_approval(key=\"manager\", timeout=3600)\nasync def wait_for_approval(timeout: int = 1800, form: dict | None = None, self_approval: bool = True, key: str | None = None, skin: Literal['detailed', 'minimal'] | None = None, description: str | dict | None = None) -> dict\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# \n# @task\n# async def process(item: str):\n# ...\n# \n# results = await parallel(items, process, concurrency=5)\nasync def parallel(items, fn, *, concurrency: Optional[int] = None)\n\n# Commit Kafka offsets for a trigger with auto_commit disabled.\n# \n# Args:\n# trigger_path: Path to the Kafka trigger (from event['wm_trigger']['trigger_path'])\n# topic: Kafka topic name (from event['topic'])\n# partition: Partition number (from event['partition'])\n# offset: Message offset to commit (from event['offset'])\ndef commit_kafka_offsets(trigger_path: str, topic: str, partition: int, offset: int) -> None\n\n", + "app": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u/<current-user>/<name>` for bare names; only use `f/<folder>/<name>` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend/<key>/main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the TypeScript SDK. For a `python3` runnable, call `get_instructions` again with `subject: \"app\"` and `language: \"python3\"`.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id=\"root\">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.\n\n**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.\n\n**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\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<any>\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<string>\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<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\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<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\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<string>): Promise<void>\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<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\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<any>\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<any>\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<any>\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<string>\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<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\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<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\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<string, any> | 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<string>\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<any>\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<void>\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<void>\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<void>\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<number | null>\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<boolean>\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<void>\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise<any>\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<any>\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<string>\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<void>\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<string>\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any>\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<DenoS3LightClientSettings>\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<Uint8Array | undefined>\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<Blob | undefined>\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<S3Object>\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<void>\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<S3Object[]>\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<S3Object>\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<string[]>\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<string>\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<string>\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<void>} 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<void>\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<void>} 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<void>\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise<void>\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<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>>\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<any>\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<any>\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<T>(fn: (...args: any[]) => Promise<T>): 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<T, R>(items: T[], fn: (item: T) => PromiseLike<R> | R, options?: { concurrency?: number },): Promise<R[]>\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<void>\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<any>\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<DucklakeMaterializeOptions, \"uniqueKey\">,): SqlStatement<any>\n", + "app.python3": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u/<current-user>/<name>` for bare names; only use `f/<folder>/<name>` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend/<key>/main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the Python SDK, for `python3` inline runnables. For a `bun` runnable, call `get_instructions` again with `subject: \"app\"` and no language.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id=\"root\">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.\n\n**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.\n\n**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# Python SDK (wmill)\n\nImport: import wmill\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 functions below are the surface to prefer. For an endpoint none of them covers,\nwmill.Windmill().get(endpoint) and .post(endpoint) issue an authenticated request against this\ninstance. What does not exist is a function name you guessed at: if it is not listed below, do\nnot call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`os.environ.get(\"WM_END_USER_EMAIL\") or os.environ.get(\"WM_EMAIL\")`. WM_END_USER_EMAIL is the app\nviewer when the run was triggered from an app and empty otherwise (both variables are always\ndefined), WM_EMAIL is the user the job is permissioned as. WM_USERNAME is the matching username.\n\ndef worker_has_internal_server() -> bool\n\ndef get_mocked_api() -> Optional[dict]\n\n# Get the HTTP client instance.\n# \n# Returns:\n# Configured httpx.Client for API requests\ndef get_client() -> httpx.Client\n\n# Make an HTTP GET request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Make an HTTP POST request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.post\n# \n# Returns:\n# HTTP response object\ndef post(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Create a new authentication token.\n# \n# Args:\n# duration: Token validity duration (default: 1 day)\n# \n# Returns:\n# New authentication token string\ndef create_token(duration = dt.timedelta(days=1)) -> str\n\n# Create a script job by path and return its job id.\n# \n# ``retry`` re-runs the job when it fails, with the policy a schedule takes,\n# e.g. ``{\"constant\": {\"attempts\": 3, \"seconds\": 10}}``. The returned id is\n# the first attempt's; each retry is a job of its own, recorded as a child of it.\ndef run_script_by_path_async(path: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a script job by hash and return its job id. See ``run_script_by_path_async`` for ``retry``.\ndef run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a flow job and return its job id.\ndef run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str\n\n# Run script by path synchronously and return its result.\ndef run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run script by hash synchronously and return its result.\ndef run_script_by_hash(hash_: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run a script on the current worker without creating a job.\n# \n# On agent workers (no internal server), falls back to running a normal\n# preview job and waiting for the result.\ndef run_inline_script_preview(content: str, language: str, args: dict = None) -> Any\n\n# Wait for a job to complete and return its result.\n# \n# Args:\n# job_id: ID of the job to wait for\n# timeout: Maximum time to wait (seconds or timedelta)\n# verbose: Enable verbose logging\n# cleanup: Register cleanup handler to cancel job on exit\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result when completed\n# \n# Raises:\n# TimeoutError: If timeout is reached\n# Exception: If job fails\ndef wait_job(job_id, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False)\n\n# Cancel a specific job by ID.\n# \n# Args:\n# job_id: UUID of the job to cancel\n# reason: Optional reason for cancellation\n# \n# Returns:\n# Response message from the cancel endpoint\ndef cancel_job(job_id: str, reason: str = None) -> str\n\n# Cancel currently running executions of the same script.\ndef cancel_running() -> dict\n\n# Get job details by ID.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job details dictionary\ndef get_job(job_id: str) -> dict\n\n# Get the root job ID for a flow hierarchy.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Root job ID\ndef get_root_job_id(job_id: str | None = None) -> dict\n\n# Get an OIDC JWT token for authentication to external services.\n# \n# Args:\n# audience: Token audience (e.g., \"vault\", \"aws\")\n# expires_in: Optional expiration time in seconds\n# \n# Returns:\n# JWT token string\ndef get_id_token(audience: str, expires_in: int | None = None) -> str\n\n# Get the status of a job.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job status: \"RUNNING\", \"WAITING\", or \"COMPLETED\"\ndef get_job_status(job_id: str) -> JobStatus\n\n# Get the result of a completed job.\n# \n# Args:\n# job_id: UUID of the completed job\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result\ndef get_result(job_id: str, assert_result_is_not_none: bool = True) -> Any\n\n# Get a variable value by path.\n# \n# Args:\n# path: Variable path in Windmill\n# \n# Returns:\n# Variable value as string\ndef get_variable(path: str) -> str\n\n# Set a variable value by path, creating it if it doesn't exist.\n# \n# Args:\n# path: Variable path in Windmill\n# value: Variable value to set\n# is_secret: Whether the variable should be secret (default: False)\ndef set_variable(path: str, value: str, is_secret: bool = False) -> None\n\n# Get a resource value by path.\n# \n# Args:\n# path: Resource path in Windmill\n# none_if_undefined: Return None instead of raising if not found\n# interpolated: if variables and resources are fully unrolled\n# \n# Returns:\n# Resource value dictionary or None\ndef get_resource(path: str, none_if_undefined: bool = False, interpolated: bool = True) -> dict | None\n\n# Set a resource value by path, creating it if it doesn't exist.\n# \n# Args:\n# value: Resource value to set\n# path: Resource path in Windmill\n# resource_type: Resource type for creation\ndef set_resource(value: Any, path: str, resource_type: str)\n\n# List resources from Windmill workspace.\n# \n# Args:\n# resource_type: Optional resource type to filter by (e.g., \"postgresql\", \"mysql\", \"s3\")\n# page: Optional page number for pagination\n# per_page: Optional number of results per page\n# \n# Returns:\n# List of resource dictionaries\ndef list_resources(resource_type: str = None, page: int = None, per_page: int = None) -> list[dict]\n\n# Set the workflow state.\n# \n# Args:\n# value: State value to set\n# path: Optional state resource path override.\ndef set_state(value: Any, path: str | None = None) -> None\n\n# Get the workflow state.\n# \n# Args:\n# path: Optional state resource path override.\n# \n# Returns:\n# State value or None if not set\ndef get_state(path: str | None = None) -> Any\n\n# Set job progress percentage (0-99).\n# \n# Args:\n# value: Progress percentage\n# job_id: Job ID (defaults to current WM_JOB_ID)\ndef set_progress(value: int, job_id: Optional[str] = None)\n\n# Get job progress percentage.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Progress value (0-100) or None if not set\ndef get_progress(job_id: Optional[str] = None) -> Any\n\n# Whether the worker running the job has received its shutdown signal.\n# \n# A draining worker waits for its current job to finish before exiting. A long-running\n# script can poll this and return early so the worker can be replaced.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# True if the worker running the job is draining\ndef worker_is_draining(job_id: Optional[str] = None) -> bool\n\n# Set the user state of a flow at a given key\ndef set_flow_user_state(key: str, value: Any) -> None\n\n# Get the user state of a flow at a given key\ndef get_flow_user_state(key: str) -> Any\n\n# Get the Windmill server version.\n# \n# Returns:\n# Version string\ndef version()\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy\n# serves object reads, writes, deletes, listing and multipart uploads of that bucket only;\n# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials,\n# which passing the resource path returns.\ndef get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Load a file from the workspace s3 bucket and returns its content as bytes.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# my_obj_content = client.load_s3_file(s3_obj)\n# file_content = my_obj_content.decode(\"utf-8\")\n# '''\ndef load_s3_file(s3object: S3Object | str, s3_resource_path: str | None) -> bytes\n\n# Load a file from the workspace s3 bucket and returns the bytes stream.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# with wmill.load_s3_file_reader(s3object, s3_resource_path) as file_reader:\n# print(file_reader.read())\n# '''\ndef load_s3_file_reader(s3object: S3Object | str, s3_resource_path: str | None) -> BufferedReader\n\n# Write a file to the workspace S3 bucket\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# \n# # for an in memory bytes array:\n# file_content = b'Hello Windmill!'\n# client.write_s3_file(s3_obj, file_content)\n# \n# # for a file:\n# with open(\"my_file.txt\", \"rb\") as my_file:\n# client.write_s3_file(s3_obj, my_file)\n# '''\ndef write_s3_file(s3object: S3Object | str | None, file_content: BufferedReader | bytes, s3_resource_path: str | None, content_type: str | None = None, content_disposition: str | None = None) -> S3Object\n\n# Permanently delete a file from the workspace S3 bucket.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# client.delete_s3_object(s3_obj)\n# '''\ndef delete_s3_object(s3object: S3Object | str, s3_resource_path: str | None = None) -> None\n\n# Sign S3 objects for use by anonymous users in public apps.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed S3 objects\ndef sign_s3_objects(s3_objects: list[S3Object | str], expiry_secs: int | None = None) -> list[S3Object]\n\n# Sign a single S3 object for use by anonymous users in public apps.\n# \n# Args:\n# s3_object: S3 object to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed S3 object\ndef sign_s3_object(s3_object: S3Object | str, expiry_secs: int | None = None) -> S3Object\n\n# Generate presigned public URLs for an array of S3 objects.\n# If an S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# base_url: Optional base URL for the presigned URLs (defaults to WM_BASE_URL)\n# expiry_secs: How long the signatures stay valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed public URLs\n# \n# Example:\n# >>> s3_objs = [S3Object(s3=\"/path/to/file1.txt\"), S3Object(s3=\"/path/to/file2.txt\")]\n# >>> urls = client.get_presigned_s3_public_urls(s3_objs)\ndef get_presigned_s3_public_urls(s3_objects: list[S3Object | str], base_url: str | None = None, expiry_secs: int | None = None) -> list[str]\n\n# Generate a presigned public URL for an S3 object.\n# If the S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_object: S3 object to sign\n# base_url: Optional base URL for the presigned URL (defaults to WM_BASE_URL)\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed public URL\n# \n# Example:\n# >>> s3_obj = S3Object(s3=\"/path/to/file.txt\")\n# >>> url = client.get_presigned_s3_public_url(s3_obj)\ndef get_presigned_s3_public_url(s3_object: S3Object | str, base_url: str | None = None, expiry_secs: int | None = None) -> str\n\n# Get the current user information.\n# \n# Returns:\n# User details dictionary\ndef whoami() -> dict\n\n# Get the current user information (alias for whoami).\n# \n# Returns:\n# User details dictionary\ndef user() -> dict\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef state_path() -> str\n\n# Get the workflow state.\n# \n# Returns:\n# State value or None if not set\ndef state() -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state_pickle(value: Any, path: str = 'state.pickle') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state_pickle(path: str = 'state.pickle') -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state(value: Any, path: str = 'state.json') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state(path: str = 'state.json') -> None\n\n# Get URLs needed for resuming a flow after suspension.\n# \n# Args:\n# approver: Optional approver name\n# flow_level: If True, generate resume URLs for the parent flow instead of the\n# specific step. This allows pre-approvals that can be consumed by any later\n# suspend step in the same flow.\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_resume_urls(approver: str = None, flow_level: bool = None) -> dict\n\n# Get the resume URLs bound to one ``wait_for_approval`` step of this workflow.\n# \n# Args:\n# step_key: Checkpoint key of the approval step, as passed to\n# ``wait_for_approval(key=...)``\n# approver: Optional approver name\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_approval_urls(step_key: str = 'approval', approver: str = None) -> dict\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, use the \"Advanced -> Suspend -> Form\" functionality.\n# Learn more at: https://www.windmill.dev/docs/flows/flow_approval#form\n# \n# :param slack_resource_path: The path to the Slack resource in Windmill.\n# :type slack_resource_path: str\n# :param channel_id: The Slack channel ID where the approval request will be sent.\n# :type channel_id: str\n# :param message: Optional custom message to include in the Slack approval request.\n# :type message: str, optional\n# :param approver: Optional user ID or name of the approver for the request.\n# :type approver: str, optional\n# :param default_args_json: Optional dictionary defining or overriding the default arguments for form fields.\n# :type default_args_json: dict, optional\n# :param dynamic_enums_json: Optional dictionary overriding the enum default values of enum form fields.\n# :type dynamic_enums_json: dict, optional\n# \n# :raises Exception: If the function is not called within a flow or flow preview.\n# :raises Exception: If the required flow job or flow step environment variables are not set.\n# \n# :return: None\n# \n# **Usage Example:**\n# >>> client.request_interactive_slack_approval(\n# ... slack_resource_path=\"/u/alex/my_slack_resource\",\n# ... channel_id=\"admins-slack-channel\",\n# ... message=\"Please approve this request\",\n# ... approver=\"approver123\",\n# ... default_args_json={\"key1\": \"value1\", \"key2\": 42},\n# ... dynamic_enums_json={\"foo\": [\"choice1\", \"choice2\"], \"bar\": [\"optionA\", \"optionB\"]},\n# ... )\n# \n# **Notes:**\n# - This function must be executed within a Windmill flow or flow preview.\n# - The function checks for required environment variables (`WM_FLOW_JOB_ID`, `WM_FLOW_STEP_ID`) to ensure it is run in the appropriate context.\ndef request_interactive_slack_approval(slack_resource_path: str, channel_id: str, message: str = None, approver: str = None, default_args_json: dict = None, dynamic_enums_json: dict = None) -> None\n\n# Send a message to a Microsoft Teams conversation with conversation_id, where success is used to style the message\ndef send_teams_message(conversation_id: str, text: str, success: bool = True, card_block: dict = None)\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# 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\n# tenant of.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None)\n\n# Get a DuckLake client for DuckDB queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# \n# Returns:\n# DucklakeClient instance\ndef ducklake(name: str = 'main')\n\ndef init_global_client(f)\n\ndef deprecate(in_favor_of: str)\n\n# Get the current workspace ID.\n# \n# Returns:\n# Workspace ID string\ndef get_workspace() -> str\n\ndef get_version() -> str\n\n# Create a script job and return its job ID.\n# \n# Args:\n# hash_or_path: Script hash or path (determined by presence of '/')\n# args: Script arguments\n# scheduled_in_secs: Delay before execution in seconds\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Job ID string\ndef run_script_async(hash_or_path: str, args: Dict[str, Any] = None, scheduled_in_secs: int = None, tag: str = None) -> str\n\n# Run a script synchronously by hash and return its result.\n# \n# Args:\n# hash: Script hash\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_sync(hash: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Run a script synchronously by path and return its result.\n# \n# Args:\n# path: Script path\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_by_path_sync(path: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB\ndef duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars\ndef polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3\ndef boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef get_state_path() -> str\n\n# Parse resource syntax from string.\ndef parse_resource_syntax(s: str) -> Optional[str]\n\n# Parse S3 object from a `s3://<storage>/<key>` URI string (`s3:///<key>`\n# for the default storage) or S3Object format. Any other string raises\n# rather than falling back to an auto-generated key: an auto key is\n# requested by omitting the object, and a fallback would silently misplace\n# the upload on any typo.\ndef parse_s3_object(s3_object: S3Object | str) -> S3Object\n\n# Parse variable syntax from string.\ndef parse_variable_syntax(s: str) -> Optional[str]\n\n# Append a text to the result stream.\n# \n# Args:\n# text: text to append to the result stream\ndef append_to_result_stream(text: str) -> None\n\n# Stream to the result stream.\n# \n# Args:\n# stream: stream to stream to the result stream\ndef stream_result(stream) -> None\n\n# Execute a SQL query against the DataTable.\n# \n# Args:\n# sql: SQL query string with $1, $2, etc. placeholders\n# *args: Positional arguments to bind to query placeholders\n# \n# Returns:\n# SqlQuery instance for fetching results\ndef query(sql: str, *args) -> SqlQuery\n\n# Idempotently materialize the rows of `select_sql` into ducklake\n# `table` for one `partition` (or the whole table when `partition` is\n# None). Client-side equivalent of the `// materialize` engine: with\n# `unique_key` it upserts within the slice (delete-by-key + insert);\n# without it, it replaces (whole table → CREATE OR REPLACE; partition →\n# delete the partition + insert). Re-running the same slice is safe — the\n# backfill / failure-recovery contract.\n# \n# The partition value is bound as a DuckDB arg (never string-interpolated)\n# so it cannot inject SQL. `select_sql` is trusted (your own query).\ndef upsert_partition(table: str, select_sql: str, partition: str = None, unique_key: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# INSERT-only materialization (no dedup / no replace) for an immutable\n# event-log table — for one `partition`, or the whole table when\n# `partition` is None. NOTE: unlike `upsert_partition`, re-running the same\n# slice duplicates rows — use only for append-only sources.\ndef append_partition(table: str, select_sql: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Read a materialized ducklake table, optionally a single partition.\ndef read(table: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Execute query and fetch results.\n# \n# Args:\n# result_collection: Optional result collection mode\n# \n# Returns:\n# Query results\ndef fetch(result_collection: str | None = None)\n\n# Execute query and fetch first row of results.\n# \n# Returns:\n# First row of query results\ndef fetch_one()\n\n# Execute query and fetch first row of results. Return result as a scalar value.\n# \n# Returns:\n# First row of query result as a scalar value\ndef fetch_one_scalar()\n\n# Execute query and don't return any results.\n# \ndef execute()\n\n# DuckDB executor requires explicit argument types at declaration\n# These types exist in both DuckDB and Postgres\n# Check that the types exist if you plan to extend this function for other SQL engines.\ndef infer_sql_type(value) -> str\n\ndef parse_sql_client_name(name: str) -> tuple[str, Optional[str]]\n\n# Decorator that marks a function as a workflow task.\n# \n# Works in both WAC v1 (sync, HTTP-based dispatch) and WAC v2\n# (async, checkpoint/replay) modes:\n# \n# - **v2 (inside @workflow)**: dispatches as a checkpoint step.\n# - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API.\n# - **Standalone, or called from inside another v2 task**: executes the\n# function body directly. A task runs as a single job, so the tasks it\n# calls run in that same job, without their own options.\n# \n# A task runs as its own job, so its result is always encoded as JSON and\n# decoded back before the caller sees it: a ``datetime`` comes back as a\n# string, a tuple as a list.\n# \n# ``retry`` re-dispatches the task after a failure, inside ``@workflow`` only.\n# Every attempt is a step of its own (``call_api``, ``call_api#2``, ...) and\n# the wait between two of them is a durable sleep, so a retrying task holds no\n# worker while it backs off. Keys: ``attempts`` (retries after the first\n# failure, a whole number from 0 to 100), ``delay`` (seconds before the first\n# retry, sub-second delays dropped), ``multiplier`` (applied to the delay\n# after each attempt, 1 keeps it constant), ``max_delay`` (ceiling in\n# seconds). ``attempts`` is required, and an out-of-range or unknown key is\n# rejected where the policy is written.\n# \n# A workflow sleeps once per round, so tasks backing off in the same fan-out\n# wait one after another rather than together: the delay before a fan-out\n# retries is the sum of every backoff pending in it, not the longest one, and\n# it grows with both the width of the fan-out and ``attempts``. Retries with\n# no ``delay`` all go out in a single round.\n# \n# ``cache_ttl`` serves a previous result of the task for that many seconds\n# instead of running it again. A task is keyed on its step key (its name and\n# call order) and the workflow's input, not on the arguments it is called\n# with, so cache one only when whether it runs, and what it receives, follow\n# from the workflow's input alone. A ``task_script`` target is keyed on the\n# arguments it is called with. It has no effect on a ``task_flow`` target,\n# which keeps its flow's own cache policy.\n# \n# Usage::\n# \n# @task\n# async def extract_data(url: str): ...\n# \n# @task(path=\"f/external_script\", timeout=600, tag=\"gpu\")\n# async def run_external(x: int): ...\n# \n# @task(retry={\"attempts\": 3, \"delay\": 30, \"multiplier\": 2})\n# async def call_api(payload: dict): ...\ndef task(_func = None, *, path: Optional[str] = None, tag: Optional[str] = None, timeout: Optional[int] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill script.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# extract = task_script(\"f/data/extract\", timeout=600)\n# \n# @workflow\n# async def main():\n# data = await extract(url=\"https://...\")\ndef task_script(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill flow.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# pipeline = task_flow(\"f/etl/pipeline\", priority=10)\n# \n# @workflow\n# async def main():\n# result = await pipeline(input=data)\ndef task_flow(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Decorator marking 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.\ndef workflow(func)\n\n# Execute ``fn`` inline and checkpoint the result.\n# \n# On replay the cached value is returned without re-executing ``fn``.\n# Use for lightweight deterministic operations (timestamps, random IDs,\n# config reads) that should not incur the overhead of a child job.\n# \n# ``fn``'s result is encoded as JSON and decoded back before it is returned,\n# so the round that runs the body sees the same types every replay sees:\n# a ``datetime`` comes back as a string, a tuple as a list.\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.\nasync def step(name: str, fn)\n\n# Server-side sleep — suspend the workflow for the given duration without holding a worker.\n# \n# Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``.\n# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``.\nasync def sleep(seconds: int)\n\n# Suspend the workflow and wait for an external approval.\n# \n# Pass ``key`` to name the step, then ``get_approval_urls(key)`` yields the URLs\n# that resume exactly this approval — route them through your own channel.\n# Without a key the steps are named ``approval``, ``approval_2``, ...\n# \n# Returns a dict with ``value`` (form data), ``approver``, and ``approved``.\n# \n# Args:\n# timeout: Approval timeout in seconds (default 1800).\n# form: Optional form schema for the approval page.\n# self_approval: Whether the user who triggered the flow can approve it (default True).\n# key: Optional checkpoint key naming this approval step.\n# skin: ``\"minimal\"`` shows approvers only the request (form and approve/reject)\n# instead of the detailed page with the workflow's details.\n# description: Shown to approvers above the form: a string, or a rich value such as\n# ``{\"markdown\": \"...\"}``.\n# \n# Example::\n# \n# urls = await step(\"urls\", lambda: get_approval_urls(\"manager\"))\n# await step(\"notify\", lambda: send_email(urls[\"resume\"], urls[\"cancel\"]))\n# result = await wait_for_approval(key=\"manager\", timeout=3600)\nasync def wait_for_approval(timeout: int = 1800, form: dict | None = None, self_approval: bool = True, key: str | None = None, skin: Literal['detailed', 'minimal'] | None = None, description: str | dict | None = None) -> dict\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# \n# @task\n# async def process(item: str):\n# ...\n# \n# results = await parallel(items, process, concurrency=5)\nasync def parallel(items, fn, *, concurrency: Optional[int] = None)\n\n# Commit Kafka offsets for a trigger with auto_commit disabled.\n# \n# Args:\n# trigger_path: Path to the Kafka trigger (from event['wm_trigger']['trigger_path'])\n# topic: Kafka topic name (from event['topic'])\n# partition: Partition number (from event['partition'])\n# offset: Message offset to commit (from event['offset'])\ndef commit_kafka_offsets(trigger_path: str, topic: str, partition: int, offset: int) -> None\n\n", "agent": "# Global draft agent instructions\n\n- An agent is drafted with `write_resource`: `{ path, resource_type: \"ai_agent\", description?, value }`, where `value` is the agent's configuration described below. To change an existing agent, read it with `read_workspace_item` type \"resource\" first and write back the whole value.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` for a bare name; only use `f/<folder>/<name>` when the folder is known to exist.\n- Test the draft with `test_run_agent` before handing it over, and fix what the run shows: a test runs the draft as it stands, its tools included. Reuse one `memory_id` across calls to test follow-ups.\n- The user can review the agent on its page, the url `write_resource` returns. Deploy it with `deploy_workspace_item` (type \"resource\") once they ask, as for any other draft.\n- Before writing an inline tool, look for a deployed script that already does the job with the workspace search tools.\n\n# Windmill agent authoring reference\n\n# Windmill AI Agents\n\nAn agent, as the Agents page lists it, is a saved LLM with its own system prompt, tools and\nmemory, stored as a resource of type `ai_agent`. It is built once and used in several places: it is\nrun from its own page (a chat, or a run form), a flow's AI agent step links to it by path, and it\ncan be shared in Slack channels from its page. Build a standalone agent when the user wants an\nassistant they talk to or reuse. Build a flow when the agent is one step of a larger process.\n\n## Structure\n\n```json\n{\n \"resource_type\": \"ai_agent\",\n \"description\": \"Answers support questions from the product docs\",\n \"value\": {\n \"provider\": { \"kind\": \"openai\", \"resource\": \"$res:f/ai_providers/openai\", \"model\": \"gpt-4o\" },\n \"system_prompt\": \"You are the support assistant for Acme. Answer from the docs; say so when they don't cover a question.\",\n \"memory\": { \"kind\": \"compaction\" },\n \"output_type\": \"text\",\n \"tools\": [\n {\n \"id\": \"search_docs\",\n \"summary\": \"search_documentation\",\n \"description\": \"Search the product documentation. Use it whenever the user asks how a feature works.\",\n \"value\": {\n \"tool_type\": \"flowmodule\",\n \"type\": \"script\",\n \"path\": \"f/support/search_docs\",\n \"input_transforms\": {\n \"query\": { \"type\": \"ai\" },\n \"index\": { \"type\": \"static\", \"value\": \"product_docs\" }\n }\n }\n }\n ]\n }\n}\n```\n\nThe agent's own settings are plain values, not the `input_transforms` an agent step in a flow uses:\neach is fixed when the agent is saved. Only a tool's arguments keep `input_transforms` (see Tools). `$res:` and `$var:` references inside it are resolved at run time.\n\n- `provider` (required): `{ \"kind\", \"resource\": \"$res:<path>\", \"model\" }`, plus an optional\n `reasoning_effort`. `resource` names the workspace's AI provider resource of that kind\n- `system_prompt`: how the agent behaves. Write it for the agent's job: who it serves, what it may\n do with its tools, and what it should refuse or hand back\n- `memory`: what lets the agent see earlier turns. `{ \"kind\": \"compaction\" }` keeps the whole\n conversation, summarizing its older part as it nears the model's context window; it is what a new\n agent starts with on its page. `{ \"kind\": \"off\" }` makes every run start from nothing, right for an\n agent that handles one request per run\n- `output_type`: `text` (default) or `image`. Image output ignores tools and needs S3 storage on the\n workspace\n- `output_schema`: a JSON schema the answer must follow, for an agent whose output a program reads\n- `max_iterations`: how many model and tool rounds a run may take, 1 to 1000 (default 10)\n- `streaming` (default on), `temperature`, `max_completion_tokens`: as their names say\n- `run_on_behalf_of`: runs from the agent's page take the identity the agent was deployed with\n rather than the caller's, so people can use it without access to what its tools touch.\n `slack_anyone` lets anyone in the Slack channels it is shared in ask it, and is kept only with\n `run_on_behalf_of`. Set either only when the user asks: both widen who acts with the deployer's\n rights\n- `on_behalf_of` is the identity itself. Deploying sets it, so never write it\n\n## Tools\n\n`tools` takes the same entries as a flow's AI agent step. `value.tool_type` is `flowmodule` for a\nscript or inline script the agent calls (or a nested agent or AI decision), `mcp` for an MCP server\n(`{ \"tool_type\": \"mcp\", \"resource_path\": \"$res:<path>\", \"include_tools\": [], \"exclude_tools\": [] }`),\nor `websearch` for web search (`{ \"tool_type\": \"websearch\" }`, summary `Web Search`).\n\n- Write logic made for this agent as an inline `rawscript` tool, as a flow writes its steps. Point a\n `script` tool at a deployed script (`path`) only when one already does the job: a run calls the\n deployed version, so a script that exists only as a draft fails the run. An inline tool's\n `value` is a flow's rawscript step:\n `{ \"tool_type\": \"flowmodule\", \"type\": \"rawscript\", \"language\": \"bun\", \"content\": \"export async function main(query: string) { ... }\", \"input_transforms\": { \"query\": { \"type\": \"ai\" } } }`\n- A flow cannot be a tool: a run offered one fails with `Unsupported tool`. Wrap it in a script\n that runs the flow\n- A flowmodule tool's `summary` is the name the agent calls it by: letters, numbers and underscores\n only, unique among the agent's tools, and neither a reserved step id (a JavaScript keyword, `ctx`,\n `state`, `bg`) nor `__wm_web_search`. Put the explanation in `description`, which tells the agent\n when to call it\n- Each argument of a tool is either the model's or fixed. `{ \"type\": \"ai\" }` (or no value) lets the\n model fill it; a static value fixes it and hides it from the model. Fix what the model must not\n choose, such as a resource, a table name or a limit\n\n## Using It From a Flow\n\nAn AI agent step links to a saved agent with `value.agent` instead of carrying its own `provider`,\nsystem prompt and tools:\n\n```json\n{\n \"id\": \"support\",\n \"value\": {\n \"type\": \"aiagent\",\n \"agent\": \"f/support/support_agent\",\n \"input_transforms\": {\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.question\" }\n },\n \"tools\": []\n }\n}\n```\n\nThe step holds only what belongs to one use of the agent: `user_message`, `user_attachments`,\n`enabled_tools`, `memory_id`, `previous_messages`, and the `model` and `reasoning_effort` overrides.\nIts `value.tool_inputs` (`{ \"<tool id>\": { \"<argument>\": <input transform> } }`) wires a saved\ntool's arguments to this flow, e.g. `flow_input.customer_id`, over the transforms the agent saved,\nwithout changing the agent. Everything else comes from the agent, so a change to the agent reaches\nevery flow linking it.\n", "datatable": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement<T> = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record<string, any>;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch<ResultCollectionT extends ResultCollection = \"last_statement_all_rows\">(\n params?: FetchParams<ResultCollectionT | ResultCollection> // The union is for auto-completion\n ): Promise<SqlResult<T, ResultCollectionT>>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<SqlResult<T, \"last_statement_first_row\">>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise<SqlResult<T, \"last_statement_first_row_scalar\">>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<void>;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n <T = any>(strings: TemplateStringsArray, ...values: any[]): SqlStatement<T>;\n query<T = any>(sql: string, ...params: any[]): SqlStatement<T>;\n};\n```\n\nCreate 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\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n", "datatable.python3": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", diff --git a/cli/src/commands/app/dev.ts b/cli/src/commands/app/dev.ts index a0483b7dba..6ff39462b5 100644 --- a/cli/src/commands/app/dev.ts +++ b/cli/src/commands/app/dev.ts @@ -230,7 +230,7 @@ const createHTML = (jsPath: string, cssPath: string, appCtx: unknown) => ` </div> </div> </div> - <script>window.ctx = ${JSON.stringify(appCtx).replace(/</g, "\\u003c")};</script> + <script>window.ctx = ${JSON.stringify(appCtx).replace(/</g, "\\u003c")}; window.ctx.query = Object.fromEntries(new URLSearchParams(location.search));</script> <script src="${jsPath}"></script> <script> // Live reload via EventSource diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index c271485d29..6a0f4bc7ff 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -6782,6 +6782,8 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! } **Set the browser tab title with \`document.title = '...'\`** (or a \`<title>\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes. +**Read the page's context from \`window.ctx\`**: \`ctx\` is the viewer (absent for anonymous visitors), \`workspace\` and \`path\` the app's (\`path\` is not set under \`wmill app dev\`), and \`query\` the page URL's query parameters as strings (\`…/apps/get/u/me/app?customer=42\` gives \`window.ctx.query.customer === '42'\`, and no query gives \`{}\`). Read it there, not from \`window.location\`, which in a sandboxed app is not the page's address. It is read once when the app loads. + **Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen. ### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`) diff --git a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte index 775a7314fd..1795cbe841 100644 --- a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte +++ b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte @@ -34,7 +34,7 @@ path, onEdit, onLoadState, - syncHashToUrl = true, + ownsPageUrl = true, ownsPageHeader = false }: { workspace: string @@ -50,8 +50,8 @@ /** How the load ended, for a host that renders its own state around this viewer. * A 403 is deliberately neither: the app exists, this member just cannot open it. */ onLoadState?: (state: 'loaded' | 'not_found') => void - /** Whether a raw app's route lives in the page URL's hash; see `RawAppPreview`. */ - syncHashToUrl?: boolean + /** Whether a raw app owns the page's address and title; see `RawAppPreview`. */ + ownsPageUrl?: boolean } = $props() // The app, its permission check and everything this viewer renders belong to `workspace`, @@ -291,7 +291,7 @@ jwtError={false} inWorkspace {hideRefreshBar} - {syncHashToUrl} + {ownsPageUrl} onLoginSuccess={() => loadApp()} ></PublicApp> {/snippet} diff --git a/frontend/src/lib/components/apps/editor/PublicApp.svelte b/frontend/src/lib/components/apps/editor/PublicApp.svelte index 64da63e727..e23fbf5876 100644 --- a/frontend/src/lib/components/apps/editor/PublicApp.svelte +++ b/frontend/src/lib/components/apps/editor/PublicApp.svelte @@ -23,7 +23,7 @@ license = undefined, inWorkspace = false, hideRefreshBar = false, - syncHashToUrl = true + ownsPageUrl = true }: { notExists: boolean noPermission: boolean @@ -48,8 +48,8 @@ */ inWorkspace?: boolean hideRefreshBar?: boolean - /** Whether a raw app's route lives in the page URL's hash; see `RawAppPreview`. */ - syncHashToUrl?: boolean + /** Whether a raw app owns the page's address and title; see `RawAppPreview`. */ + ownsPageUrl?: boolean } = $props() // Use workspace from props or from app.workspace_id (for custom path responses) @@ -114,7 +114,7 @@ secret={app.bundle_secret} path={app.path} runnables={(app.value?.runnables ?? {}) as Record<string, Runnable>} - {syncHashToUrl} + {ownsPageUrl} /> </div> {:else if app.raw_app && !effectiveWorkspace} diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 148b476211..ac5a7a213d 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -32,6 +32,7 @@ RAW_APP_SANDBOX_FLAGS, RAW_APP_PREVIEW_RELAY, rawAppStorageKey, + rawAppCtx, readRawAppStorage, applyRawAppStorageOp } from './utils' @@ -43,7 +44,7 @@ import type { Modules } from './RawAppModules.svelte' import { isRunnableByName, isRunnableByPath, type PathRunType } from '../apps/inputType' import { aiChatManager, AIMode } from '../copilot/chat/AIChatManager.svelte' - import { onMount, onDestroy, untrack } from 'svelte' + import { getContext, onMount, onDestroy, untrack } from 'svelte' import type { AppDatatableMetadata, LintResult, @@ -1921,9 +1922,17 @@ addEventListener('message', function (e) { }) } + // In a session pane the page's query is the session's (`?session=…`), not the app's. + const inSessionPane = !!getContext('aiChatManager') + // The deployed app's `window.ctx`: the viewer's membership in the app's workspace. function previewCtx() { - return $state.snapshot({ ctx: operatingUser.current, workspace: opWorkspace, path }) + return rawAppCtx( + $state.snapshot(operatingUser.current), + opWorkspace, + path, + inSessionPane ? '' : window.location.search + ) } // A build fed before the viewer is known keeps that viewer until the next one. A failed diff --git a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte index 1c82cdcd33..b8a316b235 100644 --- a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte @@ -7,6 +7,7 @@ RAW_APP_SANDBOX_FLAGS, applyRawAppStorageOp, rawAppStorageKey, + rawAppCtx, readRawAppStorage, unsandboxedRawAppHtml } from './utils' @@ -27,15 +28,17 @@ * (publish flow) needs it to read the app's DOM, which is only possible on * the unsandboxed path. */ oniframe?: (iframe: HTMLIFrameElement | undefined) => void - /** Mirror the app's own route into the page URL's hash, and start from it, and its - * `document.title` into the page's. Off where the app is embedded in a page that is - * not its own — an AI session preview tab — since there the hash and title belong to - * that page and to whichever app was opened first. */ - syncHashToUrl?: boolean + /** Mirror the app's own route into the page URL's hash, and start from it, its + * `document.title` into the page's, and hand it the page's query. Off where the app is + * embedded in a page that is not its own (an AI session preview tab, the demo + * recorder), since there the address and title belong to that page. */ + ownsPageUrl?: boolean } - let { workspace, user, secret, path, runnables, oniframe, syncHashToUrl = true }: Props = $props() - const pageHash = () => (syncHashToUrl ? window.location.hash : '') + let { workspace, user, secret, path, runnables, oniframe, ownsPageUrl = true }: Props = $props() + const pageHash = () => (ownsPageUrl ? window.location.hash : '') + const appCtx = (u: UserExt | undefined) => + rawAppCtx(u, workspace, path, ownsPageUrl ? window.location.search : '') $effect(() => { const el = unsandboxed ? iframe : undefined @@ -134,7 +137,7 @@ const html = unsandboxedRawAppHtml( workspace, secret, - { ctx: u, workspace, path }, + appCtx(u), window.location.origin, pageHash() ) @@ -207,7 +210,7 @@ // Same shape as the unsandboxed wrapper: always the object, so // `window.ctx.workspace` works for anonymous viewers too. Snapshotted: a // caller's `$state` user is a proxy, which postMessage cannot clone. - ctx: { ctx: $state.snapshot(user), workspace, path }, + ctx: appCtx($state.snapshot(user)), initialHash, storage: { local: bundleStorage ?? {}, session: {} }, // The wrapper turns this into `window.process.env` before it injects the @@ -298,11 +301,11 @@ } else if (data?.type === 'windmill:hashchange') { // Keep the parent URL hash in sync for shareable URLs. const newHash = data.hash || '' - if (syncHashToUrl && window.location.hash !== newHash) { - history.replaceState(null, '', newHash || window.location.pathname) + if (ownsPageUrl && window.location.hash !== newHash) { + history.replaceState(null, '', newHash || window.location.pathname + window.location.search) } } else if (data?.type === 'windmill:title') { - if (syncHashToUrl) setAppTitle(typeof data.title === 'string' ? data.title : '') + if (ownsPageUrl) setAppTitle(typeof data.title === 'string' ? data.title : '') } else if (runnerFailed) { refuseRequest(event) } else if (!runner) { diff --git a/frontend/src/lib/components/raw_apps/utils.test.ts b/frontend/src/lib/components/raw_apps/utils.test.ts index f5d1167c2f..dd55ea666c 100644 --- a/frontend/src/lib/components/raw_apps/utils.test.ts +++ b/frontend/src/lib/components/raw_apps/utils.test.ts @@ -7,6 +7,7 @@ import { formatRuntimeLogsForChat, genWmillTs, normalizeRawAppRuntimeLogs, + rawAppCtx, rawAppPreviewModules, stripRawAppDiffNoise, type Runnable @@ -53,6 +54,16 @@ const flowSchema = { } } as const +describe('rawAppCtx', () => { + it("carries the page's query without Windmill's own parameters", () => { + expect(rawAppCtx(undefined, 'ws', 'u/me/app', '?customer=42&wm_coep=1&tab=b').query).toEqual({ + customer: '42', + tab: 'b' + }) + expect(rawAppCtx(undefined, 'ws', 'u/me/app', '').query).toEqual({}) + }) +}) + describe('genWmillTs', () => { it('generates the correct flow args type for path runnables', () => { const runnables: Record<string, Runnable> = { diff --git a/frontend/src/lib/components/raw_apps/utils.ts b/frontend/src/lib/components/raw_apps/utils.ts index 107a255743..25b64615eb 100644 --- a/frontend/src/lib/components/raw_apps/utils.ts +++ b/frontend/src/lib/components/raw_apps/utils.ts @@ -5,6 +5,7 @@ import { isRunnableByName, isRunnableByPath, type RunnableWithFields } from '../ import type { InlineScript } from '../apps/sharedTypes' import { stateSnapshot } from '$lib/stateSnapshot.svelte' import { appSourceToDraftValue, normalizeRawAppData } from './rawAppDraftValue' +import { urlParamsToObject } from '$lib/utils/queryParams' // export type RunnableWithFields = any @@ -319,6 +320,22 @@ export function applyRawAppStorageOp(storeKey: string, d: any) { } catch (_) {} } +/** A full-code app's `window.ctx`, on every path that runs one. `query` is the viewer + * page's, built as a low-code app's `ctx.query`, and `{}` rather than absent. */ +export function rawAppCtx( + user: unknown, + workspace: string | undefined, + path: string, + search: string +) { + return { + ctx: user, + workspace, + path, + query: urlParamsToObject(new URLSearchParams(search), { stripReserved: true }) + } +} + // The sandboxed (isolated) raw-app wrapper is generated server-side and served as // a sandboxed, opaque-origin document (see `get_raw_app_data` in the backend // `apps.rs`, WIN-2006) — a blob: URL cannot carry the `CSP: sandbox` response diff --git a/frontend/src/lib/components/sessions/ItemViewerView.svelte b/frontend/src/lib/components/sessions/ItemViewerView.svelte index cd9772a331..53f6174a7d 100644 --- a/frontend/src/lib/components/sessions/ItemViewerView.svelte +++ b/frontend/src/lib/components/sessions/ItemViewerView.svelte @@ -320,7 +320,7 @@ {path} onEdit={() => onNavigate(`/apps_raw/edit/${path}`)} onLoadState={setLoadState} - syncHashToUrl={false} + ownsPageUrl={false} /> {/if} {/key} diff --git a/frontend/src/lib/components/workspaceSettings/RawAppRecordSession.svelte b/frontend/src/lib/components/workspaceSettings/RawAppRecordSession.svelte index 8a95f947bc..5ac93265c2 100644 --- a/frontend/src/lib/components/workspaceSettings/RawAppRecordSession.svelte +++ b/frontend/src/lib/components/workspaceSettings/RawAppRecordSession.svelte @@ -202,6 +202,7 @@ {path} runnables={(app.value?.runnables ?? {}) as Record<string, Runnable>} oniframe={onIframe} + ownsPageUrl={false} /> </div> {/if} diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 68178f8365..8061486141 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1107,6 +1107,8 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! } **Set the browser tab title with \`document.title = '...'\`** (or a \`<title>\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes. +**Read the page's context from \`window.ctx\`**: \`ctx\` is the viewer (absent for anonymous visitors), \`workspace\` and \`path\` the app's (\`path\` is not set under \`wmill app dev\`), and \`query\` the page URL's query parameters as strings (\`…/apps/get/u/me/app?customer=42\` gives \`window.ctx.query.customer === '42'\`, and no query gives \`{}\`). Read it there, not from \`window.location\`, which in a sandboxed app is not the page's address. It is read once when the app loads. + **Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen. ### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`) diff --git a/system_prompts/auto-generated/skills/raw-app/SKILL.md b/system_prompts/auto-generated/skills/raw-app/SKILL.md index a074291c2b..e2ba293020 100644 --- a/system_prompts/auto-generated/skills/raw-app/SKILL.md +++ b/system_prompts/auto-generated/skills/raw-app/SKILL.md @@ -313,6 +313,8 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`. **Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes. +**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads. + **Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen. ### Generated bindings (`wmill.d.ts` / `wmill.ts`) diff --git a/system_prompts/base/raw-app.md b/system_prompts/base/raw-app.md index d262c3d325..0f7589ce90 100644 --- a/system_prompts/base/raw-app.md +++ b/system_prompts/base/raw-app.md @@ -72,6 +72,8 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`. **Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes. +**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads. + **Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen. ### Generated bindings (`wmill.d.ts` / `wmill.ts`) From be05d964895b3e070af1612a49ea670b3692e3ec Mon Sep 17 00:00:00 2001 From: hugocasa <hugo@casademont.ch> Date: Tue, 3 Nov 2026 17:11:56 +0100 Subject: [PATCH 09/14] refactor: share one variable picker that reloads after a variable is created (#12177) * refactor: share one variable picker that reloads after a variable is created Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: format the trigger editors Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep the variable picker's Edit/View button where it was Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../lib/components/EditableSchemaForm.svelte | 53 +++---------- frontend/src/lib/components/EditorBar.svelte | 40 ++-------- .../components/InputTransformPickers.svelte | 53 +++---------- frontend/src/lib/components/SchemaForm.svelte | 47 +++--------- .../src/lib/components/VariablePicker.svelte | 75 +++++++++++++++++++ .../components/apps/editor/AppEditor.svelte | 43 +---------- .../triggers/http/RouteEditorInner.svelte | 44 ++--------- .../sqs/SqsTriggerEditorConfigSection.svelte | 46 +++--------- 8 files changed, 136 insertions(+), 265 deletions(-) create mode 100644 frontend/src/lib/components/VariablePicker.svelte diff --git a/frontend/src/lib/components/EditableSchemaForm.svelte b/frontend/src/lib/components/EditableSchemaForm.svelte index fd15c7f9e7..9d60dd1866 100644 --- a/frontend/src/lib/components/EditableSchemaForm.svelte +++ b/frontend/src/lib/components/EditableSchemaForm.svelte @@ -3,10 +3,11 @@ const bubble = createBubbler() import type { Schema } from '$lib/common' - import { VariableService, type ScriptLang } from '$lib/gen' + import { type ScriptLang } from '$lib/gen' import { Button } from './common' - import ItemPicker from './ItemPicker.svelte' - import VariableEditor from './VariableEditor.svelte' + import type ItemPicker from './ItemPicker.svelte' + import type VariableEditor from './VariableEditor.svelte' + import VariablePicker from './VariablePicker.svelte' import { Pen, Plus, X } from 'lucide-svelte' import { Pane, Splitpanes } from 'svelte-splitpanes' import { twMerge } from 'tailwind-merge' @@ -14,7 +15,6 @@ import PropertyEditor from './schema/PropertyEditor.svelte' import SimpleEditor from './SimpleEditor.svelte' import { createEventDispatcher, untrack } from 'svelte' - import { watch } from 'runed' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import Label from './Label.svelte' @@ -186,11 +186,6 @@ let itemPicker: ItemPicker | undefined = $state(undefined) let variableEditor: VariableEditor | undefined = $state(undefined) - watch( - () => ws, - () => itemPicker?.reloadItems() - ) - let keys: string[] = $state( (Array.isArray(schema?.order) ? [...schema.order] @@ -923,40 +918,16 @@ </div> {#if !noVariablePicker} - <ItemPicker - bind:this={itemPicker} - pickCallback={(path, _) => { - if (pickForField) { - if (args) { - args[pickForField] = '$var:' + path - } + <VariablePicker + bind:itemPicker + bind:variableEditor + workspace={ws} + onPick={(path) => { + if (pickForField && args) { + args[pickForField] = '$var:' + path } }} - itemName="Variable" - tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow." - documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" - extraField="path" - loadItems={async () => - (await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({ - name: x.path, - ...x - }))} - > - {#snippet submission()} - <div> - <Button - variant="default" - size="sm" - startIcon={{ icon: Plus }} - on:click={() => variableEditor?.initNew?.()} - > - New variable - </Button> - </div> - {/snippet} - </ItemPicker> - - <VariableEditor bind:this={variableEditor} workspace={ws} /> + /> {/if} <style> diff --git a/frontend/src/lib/components/EditorBar.svelte b/frontend/src/lib/components/EditorBar.svelte index 429c99c4a6..9a9e2c9741 100644 --- a/frontend/src/lib/components/EditorBar.svelte +++ b/frontend/src/lib/components/EditorBar.svelte @@ -24,7 +24,7 @@ import type Editor from './Editor.svelte' import ItemPicker from './ItemPicker.svelte' - import VariableEditor from './VariableEditor.svelte' + import VariablePicker from './VariablePicker.svelte' import Button from './common/button/Button.svelte' import HighlightCode from './HighlightCode.svelte' import DrawerContent from './common/drawer/DrawerContent.svelte' @@ -157,10 +157,9 @@ let ws = $derived(workspace ?? $operatingWorkspace) let contextualVariablePicker: ItemPicker | undefined = $state() - let variablePicker: ItemPicker | undefined = $state() + let variablePicker: VariablePicker | undefined = $state() let resourcePicker: ItemPicker | undefined = $state() let resourceTypePicker: ItemPicker | undefined = $state() - let variableEditor: VariableEditor | undefined = $state() let resourceEditor: ResourceEditorDrawer | undefined = $state() let s3FilePicker: S3FilePicker | undefined = $state() let ducklakePicker: ItemPicker | undefined = $state() @@ -372,10 +371,6 @@ editor && untrack(() => addEditorActions()) }) - async function loadVariables() { - return await VariableService.listVariable({ workspace: ws ?? '' }) - } - async function loadContextualVariables() { return await VariableService.listContextualVariables({ workspace: ws ?? 'NO_W' @@ -664,9 +659,11 @@ loadItems={loadContextualVariables} /> -<ItemPicker +<VariablePicker + editable bind:this={variablePicker} - pickCallback={(path, name) => { + workspace={ws} + onPick={(path, name) => { if (!editor) return if (['javascript', 'typescript'].includes(scriptLangToEditorLang(lang))) { if (!editor.getCode().includes('import * as wmill from')) { @@ -730,27 +727,7 @@ string ${windmillPathToCamelCaseName(path)} = await client.GetStringAsync(uri); } sendUserToast(`${name} inserted at cursor`) }} - tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow." - documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" - itemName="Variable" - extraField="path" - loadItems={loadVariables} - buttons={{ 'Edit/View': (x) => variableEditor?.editVariable(x) }} -> - {#snippet submission()} - <div class="flex flex-row"> - <Button - variant="accent" - startIcon={{ icon: Plus }} - on:click={() => { - variableEditor?.initNew() - }} - > - New variable - </Button> - </div> - {/snippet} -</ItemPicker> +/> <ItemPicker bind:this={resourcePicker} @@ -870,7 +847,6 @@ JsonNode ${windmillPathToCamelCaseName(path)} = JsonNode.Parse(await client.GetS workspace={ws} on:refresh={resourcePicker.openDrawer} /> -<VariableEditor bind:this={variableEditor} workspace={ws} on:create={variablePicker.openDrawer} /> {#if showDucklakePicker} <ItemPicker @@ -1081,7 +1057,7 @@ JsonNode ${windmillPathToCamelCaseName(path)} = JsonNode.Parse(await client.GetS aiDescription="Add variable" title="Add variable" variant="subtle" - on:click={variablePicker.openDrawer} + on:click={() => variablePicker?.openDrawer()} unifiedSize="sm" startIcon={{ icon: DollarSign }} {iconOnly} diff --git a/frontend/src/lib/components/InputTransformPickers.svelte b/frontend/src/lib/components/InputTransformPickers.svelte index d50a63786a..7c452f9130 100644 --- a/frontend/src/lib/components/InputTransformPickers.svelte +++ b/frontend/src/lib/components/InputTransformPickers.svelte @@ -1,13 +1,7 @@ <script lang="ts"> - import { VariableService } from '$lib/gen' - import { watch } from 'runed' - import { Plus } from 'lucide-svelte' - import { Button } from './common' - import ItemPicker from './ItemPicker.svelte' - import VariableEditor from './VariableEditor.svelte' - import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - - const operatingWorkspace = useOperatingWorkspace() + import type ItemPicker from './ItemPicker.svelte' + import type VariableEditor from './VariableEditor.svelte' + import VariablePicker from './VariablePicker.svelte' interface Props { /** The transforms being edited. A picked variable is written into `pickForField`'s. */ @@ -27,44 +21,15 @@ itemPicker = $bindable(), variableEditor = $bindable() }: Props = $props() - - let ws = $derived(workspace ?? $operatingWorkspace) - - watch( - () => ws, - () => itemPicker?.reloadItems() - ) </script> -<ItemPicker - bind:this={itemPicker} - pickCallback={(path, _) => { +<VariablePicker + bind:itemPicker + bind:variableEditor + {workspace} + onPick={(path) => { if (pickForField) { args[pickForField].value = '$var:' + path } }} - itemName="Variable" - extraField="path" - loadItems={async () => - (await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({ - name: x.path, - ...x - }))} -> - {#snippet submission()} - <div class="flex flex-row-reverse w-full border-t border-gray-200 rounded-bl-lg rounded-br-lg"> - <Button - variant="accent" - unifiedSize="sm" - startIcon={{ icon: Plus }} - on:click={() => { - variableEditor?.initNew?.() - }} - > - New variable - </Button> - </div> - {/snippet} -</ItemPicker> - -<VariableEditor bind:this={variableEditor} workspace={ws} /> +/> diff --git a/frontend/src/lib/components/SchemaForm.svelte b/frontend/src/lib/components/SchemaForm.svelte index d761101d76..e62294a5c9 100644 --- a/frontend/src/lib/components/SchemaForm.svelte +++ b/frontend/src/lib/components/SchemaForm.svelte @@ -3,19 +3,17 @@ const bubble = createBubbler() import type { Schema } from '$lib/common' - import { VariableService } from '$lib/gen' import { allTrue, type DynamicInput } from '$lib/utils' import { computeShow, quickjsSettled } from '$lib/utils/quickjsEval.svelte' import { Button } from './common' - import ItemPicker from './ItemPicker.svelte' - import VariableEditor from './VariableEditor.svelte' + import type ItemPicker from './ItemPicker.svelte' + import type VariableEditor from './VariableEditor.svelte' + import VariablePicker from './VariablePicker.svelte' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import { getResourceTypes } from './resourceTypesStore' - import { Plus } from 'lucide-svelte' import ArgInput from './ArgInput.svelte' import { createEventDispatcher, untrack } from 'svelte' - import { watch } from 'runed' import { deepEqual } from 'fast-equals' import { dragHandleZone, @@ -159,11 +157,6 @@ let itemPicker: ItemPicker | undefined = $state(undefined) let variableEditor: VariableEditor | undefined = $state(undefined) - watch( - () => ws, - () => itemPicker?.reloadItems() - ) - let resourceTypes: string[] | undefined = $state(undefined) async function loadResourceTypes() { @@ -506,36 +499,14 @@ {/if} </div> {#if !noVariablePicker} - <ItemPicker - bind:this={itemPicker} - pickCallback={(path, _) => { + <VariablePicker + bind:itemPicker + bind:variableEditor + workspace={ws} + onPick={(path) => { if (pickForField && args) { args[pickForField] = '$var:' + path } }} - itemName="Variable" - tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow." - documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" - extraField="path" - loadItems={async () => - (await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({ - name: x.path, - ...x - }))} - > - {#snippet submission()} - <div> - <Button - variant="default" - unifiedSize="md" - startIcon={{ icon: Plus }} - on:click={() => variableEditor?.initNew?.()} - > - New variable - </Button> - </div> - {/snippet} - </ItemPicker> - - <VariableEditor bind:this={variableEditor} workspace={ws} /> + /> {/if} diff --git a/frontend/src/lib/components/VariablePicker.svelte b/frontend/src/lib/components/VariablePicker.svelte new file mode 100644 index 0000000000..079dfbf01f --- /dev/null +++ b/frontend/src/lib/components/VariablePicker.svelte @@ -0,0 +1,75 @@ +<script lang="ts"> + import { VariableService } from '$lib/gen' + import { watch } from 'runed' + import { Plus } from 'lucide-svelte' + import { Button } from './common' + import ItemPicker from './ItemPicker.svelte' + import VariableEditor from './VariableEditor.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + + const operatingWorkspace = useOperatingWorkspace() + + interface Props { + onPick: (path: string, name: string) => void + workspace?: string | undefined + tooltip?: string + /** Adds an Edit/View button to each row. */ + editable?: boolean + /** Handed back for forms whose fields open the picker or a linked variable themselves. */ + itemPicker?: ItemPicker | undefined + variableEditor?: VariableEditor | undefined + } + + let { + onPick, + workspace = undefined, + tooltip = 'Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow.', + editable = false, + itemPicker = $bindable(), + variableEditor = $bindable() + }: Props = $props() + + let ws = $derived(workspace ?? $operatingWorkspace) + + watch( + () => ws, + () => itemPicker?.reloadItems() + ) + + export function openDrawer() { + itemPicker?.openDrawer() + } +</script> + +<ItemPicker + bind:this={itemPicker} + pickCallback={onPick} + itemName="Variable" + {tooltip} + documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" + extraField="path" + loadItems={async () => + (await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({ + name: x.path, + ...x + }))} + buttons={editable ? { 'Edit/View': (path) => variableEditor?.editVariable(path) } : {}} +> + {#snippet submission()} + <Button + variant="default" + unifiedSize="md" + startIcon={{ icon: Plus }} + onClick={() => variableEditor?.initNew()} + > + New variable + </Button> + {/snippet} +</ItemPicker> + +<!-- Creating one from the picker must refresh the list it is picking from. --> +<VariableEditor + bind:this={variableEditor} + workspace={ws} + onSaved={() => itemPicker?.reloadItems()} +/> diff --git a/frontend/src/lib/components/apps/editor/AppEditor.svelte b/frontend/src/lib/components/apps/editor/AppEditor.svelte index 813894a11f..20d13d8325 100644 --- a/frontend/src/lib/components/apps/editor/AppEditor.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditor.svelte @@ -39,9 +39,7 @@ import ComponentList from './componentsPanel/ComponentList.svelte' import ContextPanel from './contextPanel/ContextPanel.svelte' - import ItemPicker from '$lib/components/ItemPicker.svelte' - import VariableEditor from '$lib/components/VariableEditor.svelte' - import { VariableService } from '$lib/gen' + import VariablePicker from '$lib/components/VariablePicker.svelte' import { initHistory } from '$lib/history.svelte' import { Component, Minus, Paintbrush, Plus, Smartphone, Scan, Hand, Grab } from 'lucide-svelte' import { animateTo, findGridItemParentGrid } from './appUtils' @@ -340,9 +338,7 @@ } } - let itemPicker: ItemPicker | undefined = $state(undefined) - - let variableEditor: VariableEditor | undefined = $state(undefined) + let variablePicker: VariablePicker | undefined = $state(undefined) setContext<ContextPanelContext>('ContextPanel', { search: writable<string>(''), @@ -819,7 +815,7 @@ }) $effect(() => { if ($pickVariableCallback) { - itemPicker?.openDrawer() + variablePicker?.openDrawer() } }) // Animation logic for cssInput @@ -1299,38 +1295,7 @@ App editor not available to operators {/if} -<ItemPicker - bind:this={itemPicker} - pickCallback={(path, _) => { - $pickVariableCallback?.(path) - }} - itemName="Variable" - extraField="path" - loadItems={async () => - (await VariableService.listVariable({ workspace: $workspaceStore ?? '' })).map((x) => ({ - name: x.path, - ...x - }))} -> - {#snippet submission()} - <div - class="flex flex-row-reverse w-full bg-surface border-t border-gray-200 rounded-bl-lg rounded-br-lg" - > - <Button - variant="default" - size="sm" - startIcon={{ icon: Plus }} - on:click={() => { - variableEditor?.initNew?.() - }} - > - New variable - </Button> - </div> - {/snippet} -</ItemPicker> - -<VariableEditor bind:this={variableEditor} /> +<VariablePicker bind:this={variablePicker} onPick={(path) => $pickVariableCallback?.(path)} /> <style global> #o1 > .splitpanes__pane { diff --git a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte index fe94787167..10506263ab 100644 --- a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte +++ b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte @@ -13,7 +13,6 @@ import { HttpTriggerService, SettingService, - VariableService, type AuthenticationMethod, type HttpTrigger, type NewHttpTrigger, @@ -24,9 +23,9 @@ import { capitalize, emptyString, generateRandomString, sendUserToast } from '$lib/utils' import { useEditRights } from '$lib/operatorWriteRights' import Section from '$lib/components/Section.svelte' - import { Loader2, Pipette, Plus } from 'lucide-svelte' + import { Loader2, Pipette } from 'lucide-svelte' import Label from '$lib/components/Label.svelte' - import VariableEditor from '../../VariableEditor.svelte' + import VariablePicker from '../../VariablePicker.svelte' import { json } from 'svelte-highlight/languages' import { Highlight } from 'svelte-highlight' import JsonEditor from '$lib/components/JsonEditor.svelte' @@ -39,7 +38,6 @@ import SimpleEditor from '$lib/components/SimpleEditor.svelte' import { isCloudHosted } from '$lib/cloud' import ResourcePicker from '$lib/components/ResourcePicker.svelte' - import ItemPicker from '../../ItemPicker.svelte' import { Popover } from '$lib/components/meltComponents' import { HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING, @@ -174,8 +172,7 @@ // Component references let s3FilePicker = $state<S3FilePicker | undefined>(undefined) let s3Editor = $state<SimpleEditor | undefined>(undefined) - let variablePicker = $state<ItemPicker | undefined>(undefined) - let variableEditor = $state<VariableEditor | undefined>(undefined) + let variablePicker = $state<VariablePicker | undefined>(undefined) let drawer = $state<Drawer | undefined>(undefined) let initialConfig: NewHttpTrigger | undefined = undefined let deploymentLoading = $state(false) @@ -231,10 +228,6 @@ resource_type?: string } - async function loadVariables() { - return await VariableService.listVariable({ workspace: wsId ?? '' }) - } - const authentication_options: AuthenticationOption[] = [ { label: 'No Auth', @@ -1136,32 +1129,11 @@ </Section> {/if} -<ItemPicker +<VariablePicker + editable bind:this={variablePicker} - pickCallback={(path, _) => { + workspace={wsId} + onPick={(path) => { variable_path = path }} - tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow." - documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" - itemName="Variable" - extraField="path" - loadItems={loadVariables} - buttons={{ 'Edit/View': (x) => variableEditor?.editVariable(x) }} -> - {#snippet submission()} - <div class="flex flex-row"> - <Button - variant="default" - size="sm" - startIcon={{ icon: Plus }} - on:click={() => { - variableEditor?.initNew() - }} - > - New variable - </Button> - </div> - {/snippet} -</ItemPicker> - -<VariableEditor bind:this={variableEditor} on:create={(e) => variablePicker?.openDrawer()} /> +/> diff --git a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorConfigSection.svelte b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorConfigSection.svelte index f3daec431d..0c90ab9351 100644 --- a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorConfigSection.svelte +++ b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorConfigSection.svelte @@ -5,14 +5,13 @@ import { emptyStringTrimmed } from '$lib/utils' import TestTriggerConnection from '../TestTriggerConnection.svelte' import Subsection from '$lib/components/Subsection.svelte' - import { Plus } from 'lucide-svelte' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' import ArgInput from '$lib/components/ArgInput.svelte' - import ItemPicker from '$lib/components/ItemPicker.svelte' - import VariableEditor from '$lib/components/VariableEditor.svelte' - import { Button } from '$lib/components/common' - import { VariableService, type AwsAuthResourceType } from '$lib/gen' + import type ItemPicker from '$lib/components/ItemPicker.svelte' + import type VariableEditor from '$lib/components/VariableEditor.svelte' + import VariablePicker from '$lib/components/VariablePicker.svelte' + import { type AwsAuthResourceType } from '$lib/gen' import TestingBadge from '../testingBadge.svelte' import MultiSelect from '$lib/components/select/MultiSelect.svelte' import { safeSelectItems } from '$lib/components/select/utils.svelte' @@ -42,9 +41,6 @@ const operatingWorkspace = useOperatingWorkspace() const wsId = $derived($operatingWorkspace) - async function loadVariables() { - return await VariableService.listVariable({ workspace: wsId ?? '' }) - } let itemPicker: ItemPicker | undefined = $state() let variableEditor: VariableEditor | undefined = $state() let cached: string[] = $state([]) @@ -169,32 +165,12 @@ </Section> </div> -<ItemPicker - bind:this={itemPicker} - pickCallback={(path, _) => { +<VariablePicker + editable + bind:itemPicker + bind:variableEditor + workspace={wsId} + onPick={(path) => { queue_url = '$var:' + path }} - tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow." - documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" - itemName="Variable" - extraField="path" - loadItems={loadVariables} - buttons={{ 'Edit/View': (x) => variableEditor?.editVariable(x) }} -> - {#snippet submission()} - <div class="flex flex-row"> - <Button - variant="accent" - size="sm" - startIcon={{ icon: Plus }} - on:click={() => { - variableEditor?.initNew() - }} - > - New variable - </Button> - </div> - {/snippet} -</ItemPicker> - -<VariableEditor bind:this={variableEditor} workspace={wsId} on:create={itemPicker.openDrawer} /> +/> From 6133c709844ab7c861347e5fb66ee235c0839f43 Mon Sep 17 00:00:00 2001 From: Guilhem <guilhemlemouel@gmail.com> Date: Tue, 3 Nov 2026 17:12:40 +0100 Subject: [PATCH 10/14] feat: clear the chat composer on a double Escape (#12151) * feat: clear the chat composer on a double Escape Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: let an open picker take Escape before the composer clear Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: ignore a held Escape's repeats in the composer clear Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: overlay the clear hint in the box and take Escape from the field only Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: let the editor modes drop an @-mention's chip on a composer clear Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../copilot/chat/AIChatDisplay.svelte | 60 +++++++++++- .../copilot/chat/AIChatInput.svelte | 91 +++++++++++++++---- .../copilot/chat/ContextTextarea.svelte | 6 ++ 3 files changed, 134 insertions(+), 23 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index 87980ee691..2407ced07f 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -24,6 +24,7 @@ XIcon } from 'lucide-svelte' import Button from '$lib/components/common/button/Button.svelte' + import Kbd from '$lib/components/common/kbd/Kbd.svelte' import { fade } from 'svelte/transition' import Popover from '$lib/components/meltComponents/Popover.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' @@ -638,6 +639,33 @@ if (!isComposerOverlay(e.target) && !asksForComposer(e.target)) closeComposer() } + // The composer clears on a second Escape: the first only shows the hint, so a single + // stray press cannot throw a draft away. Any other key, a click in the composer or + // leaving it disarms it. + const CLEAR_ARM_MS = 2000 + let clearArmed = $state(false) + let clearArmTimer: ReturnType<typeof setTimeout> | undefined + function disarmClear() { + clearTimeout(clearArmTimer) + clearArmed = false + } + function onComposerEscape(repeat: boolean) { + if (!aiChatInput?.hasClearableContent()) return false + // A held key is one press: its repeats must not count as the second. + if (repeat) return true + if (clearArmed) { + // Still armed if refused (an attachment still being read): the next press retries. + if (aiChatInput.clearDraft()) disarmClear() + } else { + clearArmed = true + clearArmTimer = setTimeout(disarmClear, CLEAR_ARM_MS) + } + return true + } + $effect(() => () => clearTimeout(clearArmTimer)) + // Off once the draft is gone some other way, such as a send. + const clearHintShown = $derived(clearArmed && !!aiChatInput?.hasClearableContent()) + // While the box plays its accent outline (app.css, `data-composer-flash`). let flashing = $state(false) @@ -1051,9 +1079,29 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> onfocusin={(e) => { if (starterLayout && e.target instanceof HTMLTextAreaElement) composerOpened = true }} + oninput={() => disarmClear()} + onpointerdown={() => disarmClear()} + onfocusout={(e) => { + if (!composerEl?.contains(e.relatedTarget as Node | null)) disarmClear() + }} onkeydown={(e) => { - // A prevented Escape closed something inside first, such as the @-mention picker. - if (e.key !== 'Escape' || e.defaultPrevented) return + // A prevented Escape was handled inside, such as a running turn's stop. An IME + // cancel is the input method's. + if (e.key !== 'Escape') { + disarmClear() + return + } + if (e.defaultPrevented || e.isComposing) return + // The `@` and `/` pickers close on this press reaching `document` unprevented. + if (aiChatInput?.hasOpenPicker()) return + // The field's own presses only: a toolbar button keeps focus while the dialog it + // opened (assistant settings) closes on the same Escape. + if (e.target instanceof HTMLTextAreaElement && onComposerEscape(e.repeat)) { + // Kept from the panel or drawer around the chat, which would close on it. + e.preventDefault() + e.stopPropagation() + return + } if (!starterLayout || !composerOpened) return closeComposer() if (aiChatInput?.isDraftEmpty() ?? true) (document.activeElement as HTMLElement)?.blur() @@ -1128,6 +1176,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> collapsed={composerCollapsed} chatIcon={starterLayout} {onSent} + clearHint={!starterLayout && clearHintShown} > {#snippet collapsedControls()} {#if chatHost.mode === AIMode.GLOBAL} @@ -1481,7 +1530,12 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> <!-- Opens and closes with the box, so the page under it slides rather than jumps. --> <div use:smoothHeight={{ enabled: starterLayout, key: composerCollapsed }}> <div> - {#if starterLayout && starter && !disabled && !composerCollapsed && starter.suggestions.length > 0} + <!-- On Home the hint stands in for the suggestions, at their height. --> + {#if starterLayout && clearHintShown} + <div class="pt-2 h-9 flex items-center gap-1 text-xs text-hint" role="status"> + Press <Kbd small>Esc</Kbd> again to clear + </div> + {:else if starterLayout && starter && !disabled && !composerCollapsed && starter.suggestions.length > 0} <div class="pt-2"> <ComposerSuggestions suggestions={starter.suggestions} diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index cfc42cab73..f3b49d680b 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -32,7 +32,7 @@ import Portal from '$lib/components/Portal.svelte' import { zIndexes } from '$lib/zIndexes' import { ArrowUp, Loader2, Square, X } from 'lucide-svelte' - import { Button } from '$lib/components/common' + import { Button, Kbd } from '$lib/components/common' import { sendUserToast } from '$lib/toast' import { type PasteAttachment } from './pasteTokens' import { chatDraft, expanded } from './chatDraft' @@ -89,6 +89,8 @@ onSendRequest?: (instructions: string) => void showContext?: boolean bottomRightSnippet?: Snippet + /** Shows "Press Esc again to clear" next to the send button. */ + clearHint?: boolean onKeyDown?: (e: KeyboardEvent) => void // When provided, overrides `chatHost.loading` for the send/stop // button — useful for callers driving their own request lifecycle @@ -144,6 +146,7 @@ onSendRequest = undefined, showContext = true, bottomRightSnippet, + clearHint = false, onKeyDown = undefined, loading, onCancel, @@ -683,6 +686,42 @@ return draft.isEmpty } + // Only GLOBAL's context is chips the user added; the editors' modes seed theirs with the + // code being edited, which an Escape must neither count nor drop. + const userContext = $derived(chatHost.mode === AIMode.GLOBAL ? selectedContext : []) + + const attachmentsInFlight = $derived( + pendingImages > 0 || pendingFiles > 0 || pendingBlobs > 0 || ingestionHolds > 0 + ) + + /** Whether there is anything for `clearDraft` to drop: the draft, a context chip, or an + * attachment still being read. */ + export function hasClearableContent(): boolean { + return !draft.isEmpty || userContext.length > 0 || attachmentsInFlight + } + + /** Whether an `@` or `/` picker is open: an Escape then belongs to it. */ + export function hasOpenPicker(): boolean { + return showAppContextTooltip || (contextTextareaComponent?.hasOpenPicker() ?? false) + } + + /** Drops everything the user put in the composer: text, attachments and context chips. + * Refused while an attachment is still being read, as a send is: it would land after the + * clear. Returns whether it cleared. */ + export function clearDraft(): boolean { + if (attachmentsInFlight) return false + if (chatHost.mode === AIMode.GLOBAL) { + // GLOBAL drops every chip below, so the per-`@`-mention removals are skipped. The + // editor modes keep them: they are what drops a mention's chip with its text. + contextTextareaComponent?.clearForSend() + draft.clear() + selectedContext = [] + } else { + draft.clear() + } + return true + } + export function focusInput(selection?: ComposerSelection) { if (isContextEnabledMode) { contextTextareaComponent?.focus(selection) @@ -1305,25 +1344,37 @@ selectedContext.length === 0))} <!-- Accent only once there is something to send, so the button lights up as the draft becomes sendable; idle and Stop stay quiet. --> - <Button - variant={!isLoading && !sendDisabled ? 'accent' : 'subtle'} - unifiedSize={size} - iconOnly - title={isLoading - ? 'Stop' - : needsTextForAttachment - ? 'Write a message to send with the attachment' - : 'Send'} - startIcon={{ icon: isLoading ? Square : ArrowUp }} - disabled={!isLoading && sendDisabled} - on:click={() => { - if (isLoading) { - onCancel ? onCancel() : chatHost.cancel() - } else if (!sendDisabled) { - submitRequest() - } - }} - /> + <div class="relative flex shrink-0"> + <!-- Floats over the field so the box keeps its size; the field's colour hides the text + under it. --> + {#if clearHint} + <div + class="absolute right-full top-1/2 -translate-y-1/2 mr-1.5 flex items-center gap-1 whitespace-nowrap rounded bg-surface-input pl-2 text-xs text-hint pointer-events-none" + role="status" + > + Press <Kbd small>Esc</Kbd> again to clear + </div> + {/if} + <Button + variant={!isLoading && !sendDisabled ? 'accent' : 'subtle'} + unifiedSize={size} + iconOnly + title={isLoading + ? 'Stop' + : needsTextForAttachment + ? 'Write a message to send with the attachment' + : 'Send'} + startIcon={{ icon: isLoading ? Square : ArrowUp }} + disabled={!isLoading && sendDisabled} + on:click={() => { + if (isLoading) { + onCancel ? onCancel() : chatHost.cancel() + } else if (!sendDisabled) { + submitRequest() + } + }} + /> + </div> {/snippet} <!-- One wrapping row for every badge-shaped chip: selected context (or, when the diff --git a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte index 3b60c864db..4d3080386d 100644 --- a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte +++ b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte @@ -787,6 +787,12 @@ } } + /** Whether the `@` or `/` picker is open. It closes itself on an Escape reaching + * `document` unprevented. */ + export function hasOpenPicker(): boolean { + return showContextTooltip || showCommandTooltip + } + // Wipe after dispatching a send: pre-zero `prevMentionedTitles` so the effect // above sees no diff when `value` clears, leaving `selectedContext` for the // send that is already carrying it to settle (see the caller). A manual From 201d8f696758466b049a55830669b416ebb24b0a Mon Sep 17 00:00:00 2001 From: hugocasa <hugo@casademont.ch> Date: Tue, 3 Nov 2026 17:18:33 +0100 Subject: [PATCH 11/14] feat: tailor mcp instructions to the token scope and the caller's role (#12173) * feat: tailor mcp instructions to the token scope and the caller's role Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep consent, resource and draft-run guidance for restricted roles Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: drop stale comment on session_ctx_with Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: hold mcp sessions to read-and-run where direct deployment is disabled Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: serve mcp instructions from one template and per-profile flags Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: pin the mcp prompt profile key and template flags against drift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Ruben Fiszel <ruben@windmill.dev> --- AGENTS.md | 2 +- .../src/ai_session_tools/gen/prompt.json | 1000 ++++++++++++++++- .../src/ai_session_tools/instructions.rs | 344 +++++- .../windmill-api/src/ai_session_tools/mod.rs | 4 +- .../src/ai_session_tools/views.rs | 2 +- backend/windmill-api/src/mcp/core.rs | 81 +- backend/windmill-api/src/mcp/session.rs | 2 +- backend/windmill-mcp/src/server/backend.rs | 12 +- backend/windmill-mcp/src/server/session.rs | 12 +- .../components/copilot/chat/global/core.ts | 265 ++++- .../copilot/chat/global/mcpSessionGen.test.ts | 161 ++- .../copilot/chat/global/promptTemplate.ts | 31 + .../copilot/chat/global/sessionAccess.ts | 3 +- 13 files changed, 1764 insertions(+), 155 deletions(-) create mode 100644 frontend/src/lib/components/copilot/chat/global/promptTemplate.ts diff --git a/AGENTS.md b/AGENTS.md index a1fb608291..406a9bffd8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ Open-source platform for internal tools, workflows, API integrations, background - **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does. - **CLI commands**: when adding/modifying/removing a command, subcommand, option, or description in `cli/src/commands/`, run `python system_prompts/generate.py` to refresh `system_prompts/auto-generated/` and `cli/src/guidance/skills.gen.ts`. The CLI docs the agents use to operate `wmill` are derived from the source — stale generated files give agents the wrong flags. - **AI guidance** (chat prompts and CLI skills): what the AI knows about Windmill itself — how flows, scripts, apps, pipelines and resources work — is written once, in `system_prompts/base/` and `system_prompts/languages/`, and `system_prompts/generate.py` builds both the chat's `$system_prompts` exports and the CLI's skills from it. Add or change such guidance there, never inline in one consumer: a sentence only one side should see goes in a `<!-- cli-only -->` / `<!-- chat-only -->` block, and a new file reaches both through the `TOPICS` table. The chat prompt builders under `frontend/src/lib/components/copilot/chat/` add only tool plumbing and runtime values, and shared markdown names no chat tool, since it reaches every chat mode. Rerun `generate.py` after editing; `system_prompts/README.md` has the details. -- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v<N>` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`); the two copies of that rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v<N>` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/backend/windmill-api/src/ai_session_tools/gen/prompt.json b/backend/windmill-api/src/ai_session_tools/gen/prompt.json index 16af9df870..c88c8dd9e6 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/prompt.json +++ b/backend/windmill-api/src/ai_session_tools/gen/prompt.json @@ -1,12 +1,998 @@ { - "base": "This server works in a Windmill workspace as the user \"{{username}}\".\n\nRules:\n- What you write is a per-user draft, saved server-side and visible only to this user. Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks.\n- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (`url`), an app draft's editor with its live preview (`preview_url`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.\n- Find items with list_workspace_items and read one with read_workspace_item before changing it. An agent is a resource of type `ai_agent`: test it with test_run_agent and run a deployed one with run_agent, never run_flow or run_script.\n- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language. Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and get_db_schema before writing SQL against a database resource.\n- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying.\n- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version \"deployed\" so the arguments match.\n- To undo your own work, discard its draft with discard_local_draft. delete_workspace_item removes an item that is deployed.\n- Listings return only what this user can see. When an item they name is missing, say it may be in a folder they cannot read, not that it does not exist.\n- No one can read a variable's value through these tools. When editing a variable, pass only the fields that change.\n- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration.\n- Only raw apps (`rawApp` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words.\n- Datatables are set up in the workspace settings. Start from list_datatables; one with `migrations_enabled` changes its schema through migrations only.\n- create_resource_type adds a resource type: show the user the schema first and create it once they agree.\n- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.\n\nPath conventions:\n- A workspace path starts with one of two namespaces; its trailing <name> may itself contain \"/\", so a path has three or more segments:\n - `u/{{username}}/<name>` — your personal scope. Default for ad-hoc, exploratory, or scratch work.\n - `f/<folder>/<name>` — a shared folder scope; the <folder> must already exist (a bare `f/<name>` with no folder segment is INVALID and will fail).\n- If the user supplies a fully qualified `f/<folder>/...` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a `u/{{username}}/...` path unless a tool rejects it.\n- Default a bare name with no namespace prefix (e.g. \"create a flow called myflow\") to `u/{{username}}/<name>`. Never invent an `f/<folder>/...` path for a folder that does not exist; create one with `create_folder` only when the user explicitly asks for a new folder.{{folder_guidance}}", + "template": "This server works in a Windmill workspace as the user \"{{username}}\".{{#read_only}}{{#runs_deployed}}\n\nThis connection can read the workspace's items, runs and data, and run scripts, flows and agents that are already deployed. It cannot create, edit, deploy or delete anything, nor test-run code that is not deployed: when the user asks for such a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{^runs_deployed}}\n\nThis connection is read-only: it can read the workspace's items, runs and data, but cannot run, create, edit, deploy or delete anything. When the user asks for a run or a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{/read_only}}{{^read_only}}{{^can_write_draft}}\n\nThis user's role does not let them create or edit {{refused_kinds}} here, so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had, and suggest asking a workspace admin, who can grant their role more.{{#builds_flows}} Their role does let them compose flows out of scripts and flows that are already deployed: write flows with write_flow and patch_flow_json, every step calling a deployed script or flow by path. The server refuses inline code anywhere in the flow, so when a flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.{{/builds_flows}}{{#builds_apps}} Their role does let them build raw apps whose backend runnables are path runnables to deployed scripts or flows; call get_instructions with subject \"app\" first. The server refuses inline and hub runnables, and runs an app they deploy sandboxed, as the user who deployed it.{{/builds_apps}}{{#has_draft_tools}} They can draft with {{draft_tools}}.{{/has_draft_tools}}{{/can_write_draft}}{{/read_only}}\n\nRules:{{#can_write_any_draft}}\n- What you write is a per-user draft, saved server-side and visible only to this user. {{#can_deploy}}Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks.{{/can_deploy}}{{^can_deploy}}{{#can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, and this workspace's deploy rules let this user deploy only the schedules and triggers their role manages: call deploy_workspace_item for those only when the user asks, and for anything else give them the draft's link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{^can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, which this workspace's deploy rules do not let this user do: when a draft is ready, give them its link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{/can_deploy}}{{/can_write_any_draft}}\n{{#can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (`url`), an app draft's editor with its live preview (`preview_url`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}{{^can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, an item's page. Whenever the user will want to see what you found{{#runs}} or ran{{/runs}}, or has to do a step in Windmill themselves: show it with show_run, show_runs or show_item when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}\n- Find items with list_workspace_items and read one with read_workspace_item{{#can_write_any_draft}} before changing it{{/can_write_any_draft}}. An agent is a resource of type `ai_agent`{{#runs}}: {{#can_run_flow_preview}}test it with test_run_agent and {{/can_run_flow_preview}}run a deployed one with run_agent, never run_flow or run_script.{{/runs}}{{^runs}}.{{/runs}}{{#can_write_draft}}\n- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and{{/can_draft_triggers}}{{^can_draft_triggers}} Call{{/can_draft_triggers}} get_db_schema before writing SQL against a database resource.{{/can_write_draft}}{{^can_write_draft}}{{#can_draft_resources}}\n- Call get_instructions before writing a resource.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields.{{/can_draft_triggers}}{{/can_draft_resources}}{{/can_write_draft}}{{#can_write_draft}}{{#can_run_preview}}\n- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying.{{/can_run_preview}}{{/can_write_draft}}{{^can_write_draft}}{{#builds_flows}}{{#can_run_flow_preview}}\n- After writing a flow, test it with test_run_flow before saying it works. It runs the draft, so nothing needs deploying.{{/can_run_flow_preview}}{{/builds_flows}}{{/can_write_draft}}{{#can_run_preview}}\n- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version \"deployed\" so the arguments match.{{/can_run_preview}}{{^can_run_preview}}{{#can_run_flow_preview}}\n- A request to run a flow or agent also goes to test_run_flow or test_run_agent, which run the draft. Use run_flow or run_agent only when the user asks for the deployed version, and run_script for any script: those run the DEPLOYED item as this user, so read it with read_workspace_item version \"deployed\" first so the arguments match.{{/can_run_flow_preview}}{{^can_run_flow_preview}}{{#runs}}\n- run_script, run_flow and run_agent are how you run anything here: they run the DEPLOYED item as this user. Read it with read_workspace_item version \"deployed\" first so the arguments match.{{/runs}}{{/can_run_flow_preview}}{{/can_run_preview}}{{#can_write_any_draft}}\n- To undo your own work, discard its draft with discard_local_draft.{{#can_deploy_any_kind}} delete_workspace_item removes an item that is deployed.{{/can_deploy_any_kind}}{{/can_write_any_draft}}{{^can_write_any_draft}}{{^read_only}}\n- You cannot create or edit anything, but where the server allows it discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes a deployed item.{{/read_only}}{{/can_write_any_draft}}{{^read_only}}{{#unmanaged}}\n- This workspace does not let this user change {{unmanaged_kinds}}, here or in Windmill: suggest asking a workspace admin.{{/unmanaged}}{{/read_only}}\n- Listings return only what this user can see. When an item they name is missing, say it may be in a folder they cannot read, not that it does not exist.\n- No one can read a variable's value through these tools.{{#can_draft_variables}} When editing a variable, pass only the fields that change.{{/can_draft_variables}}{{#can_write_draft}}\n- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration.{{/can_write_draft}}\n- {{#can_write_app_draft}}Only raw apps (`rawApp` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words.{{/can_write_app_draft}}{{^can_write_app_draft}}Only raw apps (`rawApp` true) can be read here.{{/can_write_app_draft}}\n- Datatables are set up in the workspace settings. Start from list_datatables; one with `migrations_enabled` changes its schema through migrations only.{{#can_draft_resources}}{{#can_create_resource_type}}\n- create_resource_type adds a resource type: show the user the schema first and create it once they agree.{{/can_create_resource_type}}{{^can_create_resource_type}}\n- This user cannot create a resource type here, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin.{{/can_create_resource_type}}{{/can_draft_resources}}\n- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.{{#can_write_any_draft}}\n\nPath conventions:\n- A workspace path starts with one of two namespaces; its trailing <name> may itself contain \"/\", so a path has three or more segments:\n - `u/{{username}}/<name>` — your personal scope. Default for ad-hoc, exploratory, or scratch work.\n - `f/<folder>/<name>` — a shared folder scope; the <folder> must already exist (a bare `f/<name>` with no folder segment is INVALID and will fail).\n- If the user supplies a fully qualified `f/<folder>/...` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a `u/{{username}}/...` path unless a tool rejects it.\n- Default a bare name with no namespace prefix (e.g. \"create a flow called myflow\") to `u/{{username}}/<name>`. Never invent an `f/<folder>/...` path for a folder that does not exist{{#can_create_folder}}; create one with `create_folder` only when the user explicitly asks for a new folder{{/can_create_folder}}.{{folder_guidance}}{{/can_write_any_draft}}{{#can_create_folder}}{{^can_write_any_draft}}\n- You can create a shared folder with `create_folder` when the user explicitly asks for one. You cannot create anything inside it here, so do not offer to.{{/can_write_any_draft}}{{/can_create_folder}}", + "profiles": { + "read_only": { + "flags": "read_only unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, triggers, resources, or variables", + "draft_tools": "", + "unmanaged_kinds": "schedules or triggers" + } + }, + "read_run": { + "flags": "read_only runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, triggers, resources, or variables", + "draft_tools": "", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:11:1:full:full:11": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:10:1:full:full:11": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:none:none:11": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:none:none:10": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:none:none:01": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:none:none:00": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:none:compose:11": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows or scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:none:compose:10": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:none:compose:01": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:none:compose:00": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:none:full:11": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:none:full:10": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:none:full:01": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:none:full:00": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:compose:none:11": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:compose:none:10": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:compose:none:01": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:compose:none:00": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:compose:compose:11": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:compose:compose:10": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:compose:compose:01": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:compose:compose:00": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:compose:full:11": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:compose:full:10": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:compose:full:01": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:compose:full:00": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:full:none:11": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:full:none:10": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:full:none:01": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:full:none:00": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:full:compose:11": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows or scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:full:compose:10": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:full:compose:01": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:full:compose:00": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:1:full:full:11": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:full:full:10": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:1:full:full:01": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:1:full:full:00": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:0:none:none:11": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:none:none:10": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:none:none:01": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:0:none:none:00": { + "flags": "can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:0:none:compose:11": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows or scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:none:compose:10": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:none:compose:01": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:0:none:compose:00": { + "flags": "builds_apps can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:0:compose:none:11": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:compose:none:10": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:compose:none:01": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:0:compose:none:00": { + "flags": "builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:01:0:compose:compose:11": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:compose:compose:10": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:01:0:compose:compose:01": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:01:0:compose:compose:00": { + "flags": "builds_apps builds_flows can_create_folder can_create_resource_type can_deploy can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:none:none:11": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:none:none:10": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:none:none:01": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:none:none:00": { + "flags": "can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:none:compose:11": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows or scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:none:compose:10": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:none:compose:01": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:none:compose:00": { + "flags": "builds_apps can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:none:full:11": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:none:full:10": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:none:full:01": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:none:full:00": { + "flags": "can_draft_resources can_draft_variables can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:compose:none:11": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:compose:none:10": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:compose:none:01": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:compose:none:00": { + "flags": "builds_flows can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:compose:compose:11": { + "flags": "builds_apps builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:compose:compose:10": { + "flags": "builds_apps builds_flows can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:compose:compose:01": { + "flags": "builds_apps builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:compose:compose:00": { + "flags": "builds_apps builds_flows can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:compose:full:11": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:compose:full:10": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:compose:full:01": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:compose:full:00": { + "flags": "builds_flows can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:full:none:11": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:full:none:10": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:full:none:01": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:full:none:00": { + "flags": "can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:full:compose:11": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows or scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:full:compose:10": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:full:compose:01": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:full:compose:00": { + "flags": "builds_apps can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:1:full:full:11": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:full:full:10": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:1:full:full:01": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:1:full:full:00": { + "flags": "can_draft_resources can_draft_variables can_run_flow_preview can_run_preview can_write_any_draft can_write_app_draft can_write_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:0:none:none:11": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows, scripts, or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:none:none:10": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:none:none:01": { + "flags": "can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:0:none:none:00": { + "flags": "can_draft_resources can_draft_variables can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:0:none:compose:11": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "flows or scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:none:compose:10": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:none:compose:01": { + "flags": "builds_apps can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:0:none:compose:00": { + "flags": "builds_apps can_draft_resources can_draft_variables can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "flows, scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:0:compose:none:11": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts or apps", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:compose:none:10": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:compose:none:01": { + "flags": "builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:0:compose:none:00": { + "flags": "builds_flows can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, apps, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + }, + "full:00:0:compose:compose:11": { + "flags": "builds_apps builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed", + "vars": { + "refused_kinds": "scripts", + "draft_tools": "write_resource, write_variable, write_schedule, and write_trigger", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:compose:compose:10": { + "flags": "builds_apps builds_flows can_deploy_any_kind can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or triggers", + "draft_tools": "write_resource, write_variable, and write_schedule", + "unmanaged_kinds": "triggers" + } + }, + "full:00:0:compose:compose:01": { + "flags": "builds_apps builds_flows can_deploy_any_kind can_draft_resources can_draft_triggers can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts or schedules", + "draft_tools": "write_resource, write_variable, and write_trigger", + "unmanaged_kinds": "schedules" + } + }, + "full:00:0:compose:compose:00": { + "flags": "builds_apps builds_flows can_draft_resources can_draft_variables can_run_flow_preview can_write_any_draft can_write_app_draft has_draft_tools runs runs_deployed unmanaged", + "vars": { + "refused_kinds": "scripts, schedules, or triggers", + "draft_tools": "write_resource and write_variable", + "unmanaged_kinds": "schedules or triggers" + } + } + }, "folder_guidance": { - "admin": "\n- As a workspace admin you can write to any existing folder. Folders here include {{writable_folders}} (you can also write to others not listed; list_workspace_items with type \"folder\" lists them all). If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.", - "admin_no_folders": "\n- As a workspace admin you can write to any existing folder. If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.", - "member": "\n- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path. Use `create_folder` only when the user explicitly asks for a new folder.", - "member_no_folders": "\n- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, create one with `create_folder` (you become an owner); otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.", - "member_readonly": "\n- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path. Use `create_folder` only when the user explicitly asks for a new folder.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there.", - "member_no_folders_readonly": "\n- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, create one with `create_folder` (you become an owner); otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there." + "create_folder": { + "admin": "\n- As a workspace admin you can write to any existing folder. Folders here include {{writable_folders}} (you can also write to others not listed; list_workspace_items with type \"folder\" lists them all). If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.", + "admin_no_folders": "\n- As a workspace admin you can write to any existing folder. If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.", + "member": "\n- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path. Use `create_folder` only when the user explicitly asks for a new folder.", + "member_no_folders": "\n- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, create one with `create_folder` (you become an owner); otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.", + "member_readonly": "\n- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path. Use `create_folder` only when the user explicitly asks for a new folder.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there.", + "member_no_folders_readonly": "\n- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, create one with `create_folder` (you become an owner); otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there." + }, + "no_create_folder": { + "admin": "\n- As a workspace admin you can write to any existing folder. Folders here include {{writable_folders}} (you can also write to others not listed; list_workspace_items with type \"folder\" lists them all). If the user names a folder, use it; otherwise ask them which folder to use rather than guessing.", + "admin_no_folders": "\n- As a workspace admin you can write to any existing folder. If the user names a folder, use it; otherwise ask them which folder to use rather than guessing.", + "member": "\n- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path.", + "member_no_folders": "\n- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, say plainly that you cannot create one here; otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.", + "member_readonly": "\n- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there.", + "member_no_folders_readonly": "\n- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, say plainly that you cannot create one here; otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there." + } + }, + "rendered_sha256": { + "read_only": "a2a002ef12a3714f73938b5451482d5e226144c10f4f3bc09495f6f886dd3624", + "read_run": "b1dccd011a0bab7180e949e60f3637759e36dc167a99684c3e76e0d21666f827", + "full:11:1:full:full:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", + "full:10:1:full:full:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", + "full:01:1:none:none:11": "b7ac91e039c925eb34c58b8fb9a8c6840cd7eac5ab8eb91b35e44ea1cdfd3fbd", + "full:01:1:none:none:10": "a46e98609c159e1ece181e61e14e4180cfa619797fd638ce64080673c6c24119", + "full:01:1:none:none:01": "8bb8ee7c586040e15a43503c29fabe43852ee33d66288f6d35c37dd377d29540", + "full:01:1:none:none:00": "9f3b6d19101c7d644c2c8a8b0f6b75d2c45dd66e9360ef900ab48d610ff90a95", + "full:01:1:none:compose:11": "dafeeeb951a5a05441c555201081a510ea349d76fd65fa4a646222c7f31c62e0", + "full:01:1:none:compose:10": "dffa6d8f7e14b88eb763f8f52d4979a48620c50e09eb8bca6bc364945c6317e8", + "full:01:1:none:compose:01": "ef16520047e87d643618f36070cf255a4c3f0c9a7a6ca0d880225906e70dbd6f", + "full:01:1:none:compose:00": "8570d394f70635233118a2bbb70b3c035ffd26414034f484909cfd459d5e88f5", + "full:01:1:none:full:11": "dafeeeb951a5a05441c555201081a510ea349d76fd65fa4a646222c7f31c62e0", + "full:01:1:none:full:10": "dffa6d8f7e14b88eb763f8f52d4979a48620c50e09eb8bca6bc364945c6317e8", + "full:01:1:none:full:01": "ef16520047e87d643618f36070cf255a4c3f0c9a7a6ca0d880225906e70dbd6f", + "full:01:1:none:full:00": "8570d394f70635233118a2bbb70b3c035ffd26414034f484909cfd459d5e88f5", + "full:01:1:compose:none:11": "9f4ec78b6eb9ec845fe558ddb7cbf0047d5ac41ece2b4f1060585d34ab5873aa", + "full:01:1:compose:none:10": "404cbac8cdcfdea36f336a675fbb6ed81ee00e6f540b0970691b1b91080ce853", + "full:01:1:compose:none:01": "b276d7a4b1bec12b0f0b3a002c8bc291c51c00095afb287d9cddf703db91b3ed", + "full:01:1:compose:none:00": "4728593a56fe37c6f2f0108ae76a444494ef3b9b7d08178ca919dfe42f405044", + "full:01:1:compose:compose:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", + "full:01:1:compose:compose:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", + "full:01:1:compose:compose:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", + "full:01:1:compose:compose:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", + "full:01:1:compose:full:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", + "full:01:1:compose:full:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", + "full:01:1:compose:full:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", + "full:01:1:compose:full:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", + "full:01:1:full:none:11": "9f4ec78b6eb9ec845fe558ddb7cbf0047d5ac41ece2b4f1060585d34ab5873aa", + "full:01:1:full:none:10": "404cbac8cdcfdea36f336a675fbb6ed81ee00e6f540b0970691b1b91080ce853", + "full:01:1:full:none:01": "b276d7a4b1bec12b0f0b3a002c8bc291c51c00095afb287d9cddf703db91b3ed", + "full:01:1:full:none:00": "4728593a56fe37c6f2f0108ae76a444494ef3b9b7d08178ca919dfe42f405044", + "full:01:1:full:compose:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", + "full:01:1:full:compose:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", + "full:01:1:full:compose:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", + "full:01:1:full:compose:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", + "full:01:1:full:full:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", + "full:01:1:full:full:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", + "full:01:1:full:full:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", + "full:01:1:full:full:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", + "full:01:0:none:none:11": "6e298c3aa2c213e11284300395cffa5a50973c08ca99217a8527dac29a1edc39", + "full:01:0:none:none:10": "dc91d71b9d073ed7373719375889d3decad8ea8edb55f74592ab743d310c03f0", + "full:01:0:none:none:01": "1d57273309c06e5d471da0abf3fe20413766a4e9ec4b4a8844f44a8fee5ea41b", + "full:01:0:none:none:00": "291acf6c1aa45d0878839335592f5ad592187cf89bbc22ca2dc0bb3081077a9c", + "full:01:0:none:compose:11": "d758f422f6380b3ed8538d10080335fe1997c3d4c023bababe331bb5f6bb6bf4", + "full:01:0:none:compose:10": "99ebe299170d1446794ae7c5a3ea3d721719083d49465e73be28cdbf9959486f", + "full:01:0:none:compose:01": "63bacd0a11ff0b56da10f61d0b8d07f287bc4a60a6f55dbd9383c738e9b27e38", + "full:01:0:none:compose:00": "71121299c61f1317cd9d9cf3d1110e2cd8eeeeb750081ffab831d711d7579ec5", + "full:01:0:compose:none:11": "222da08c7bfd03cc4727f7f8b61d5a42f25c8411a94f935cf8b767afad9e4914", + "full:01:0:compose:none:10": "10e25b3903215e2187d2b7c073fb9fad3f6742080f6590b4c64fedaf83fcd223", + "full:01:0:compose:none:01": "7823826226be878294fcdaa56d2ed9758176527f2bcaac04195f7c4f03255701", + "full:01:0:compose:none:00": "c86c23430fbf494f63c71ceb885566e4dfebbf5bcc57f665a984a6fc8fffbb8a", + "full:01:0:compose:compose:11": "137549c360e6427c8ff8b04e98f3ad56102326fddd486a76155a2a601a2962ae", + "full:01:0:compose:compose:10": "5ea1a20c7f9b390d9bc3e4edc91529387876b7c547bee4a75472979f58c8f0cb", + "full:01:0:compose:compose:01": "b3d9ef9882e8d4e17e7899403ab0184c1313d003eebab4de6cf41b59819e2ebb", + "full:01:0:compose:compose:00": "f2c815c82abccfdcbf8a6e3c39b17c9a7cbe08db32e531b84cc0f1ae91655335", + "full:00:1:none:none:11": "ef4a2f66bd05eb22d92c6a88e5caf83d1a8b02db560db96ccc23755e8fd6d8d9", + "full:00:1:none:none:10": "fbb85e9d0036b16025b318ce9ace58d5a163ab0ceeaed918bfbf3b1ab0e93d6f", + "full:00:1:none:none:01": "c5bc889a27124519592086f0f94c8313d9ba8a225a50bf16bbb5bb04212f2952", + "full:00:1:none:none:00": "584f5d9dcfc95669518e1516e9c282b357024ee24be31047b97cbc035e1cd792", + "full:00:1:none:compose:11": "767778374b9da9e43adac84e9a19ea90100f1f1eef6abaca33476b332aa29081", + "full:00:1:none:compose:10": "7ae0803c0c47dd8199ad30dbfacae40669bf6e5eb0eed046904b583cf9a3888f", + "full:00:1:none:compose:01": "5ca874234ce2a52816e908e8e6b7363c3fe45651702eb4b219151589e5de7977", + "full:00:1:none:compose:00": "b37c3e7542d716546db196aa8358e8a0ef8e52dc37b50fbb57f62862d45fde23", + "full:00:1:none:full:11": "767778374b9da9e43adac84e9a19ea90100f1f1eef6abaca33476b332aa29081", + "full:00:1:none:full:10": "7ae0803c0c47dd8199ad30dbfacae40669bf6e5eb0eed046904b583cf9a3888f", + "full:00:1:none:full:01": "5ca874234ce2a52816e908e8e6b7363c3fe45651702eb4b219151589e5de7977", + "full:00:1:none:full:00": "b37c3e7542d716546db196aa8358e8a0ef8e52dc37b50fbb57f62862d45fde23", + "full:00:1:compose:none:11": "49165f1bbd9e26bc1bb0b32b14bab96c2daa50f816332806c2521b8d46b9134e", + "full:00:1:compose:none:10": "d77d7a0566f596c8ba3d34967e490d735618e5b1df95e9984d268b70fc44c432", + "full:00:1:compose:none:01": "d3c04033a12757b8b6ced60290084f3ac75344e36a770d6f093c68ac2c0773ad", + "full:00:1:compose:none:00": "7d4511f33441526e5653c0a0892fb7aa232b8890c7268eff7cd43ab5c3e6d0ec", + "full:00:1:compose:compose:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", + "full:00:1:compose:compose:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", + "full:00:1:compose:compose:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", + "full:00:1:compose:compose:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", + "full:00:1:compose:full:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", + "full:00:1:compose:full:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", + "full:00:1:compose:full:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", + "full:00:1:compose:full:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", + "full:00:1:full:none:11": "49165f1bbd9e26bc1bb0b32b14bab96c2daa50f816332806c2521b8d46b9134e", + "full:00:1:full:none:10": "d77d7a0566f596c8ba3d34967e490d735618e5b1df95e9984d268b70fc44c432", + "full:00:1:full:none:01": "d3c04033a12757b8b6ced60290084f3ac75344e36a770d6f093c68ac2c0773ad", + "full:00:1:full:none:00": "7d4511f33441526e5653c0a0892fb7aa232b8890c7268eff7cd43ab5c3e6d0ec", + "full:00:1:full:compose:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", + "full:00:1:full:compose:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", + "full:00:1:full:compose:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", + "full:00:1:full:compose:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", + "full:00:1:full:full:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", + "full:00:1:full:full:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", + "full:00:1:full:full:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", + "full:00:1:full:full:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", + "full:00:0:none:none:11": "636f56186fb922e1d8a0a2eb2e47ffcb50dffbc5ede80d1cd6070c31f0ba5d6f", + "full:00:0:none:none:10": "7107bcee6ec708a56bb154d6126a5fc50ee06c12f9b08601f4b916861e97bdf3", + "full:00:0:none:none:01": "c2f6200dfb97afd78860fe1d38a49992f177a5565d2ffd7bdf846c9c5116eeb5", + "full:00:0:none:none:00": "7dc058744dda38885db1952bc4fbf989f36d09a5d00498992d5906fb132d156c", + "full:00:0:none:compose:11": "dc5384ae37ad402ff5b70380c5333a4d6bbcd317b4add339fa3b43d87fff4abc", + "full:00:0:none:compose:10": "542a4866c165b7f753fda6e4cbee3cf8bdbc33e4f3ac03f009254146f29aa101", + "full:00:0:none:compose:01": "05aacb2dca48f9186e8d21b9e147b2761def418279169a79d62d814a3bd555ce", + "full:00:0:none:compose:00": "2056da0f3fe9e5fc82861c655808a1d093aabca4619a6d3e2dfabdeb784d007a", + "full:00:0:compose:none:11": "d7f332285e0a03bf906ef55b7178cd96bd7d9b6198fba4108d32bfbcc5369f6c", + "full:00:0:compose:none:10": "780577681385ce98328e9a15c8a3417cddb2086e2292e7070a77e2e02d5da448", + "full:00:0:compose:none:01": "471be94a0143cc25b7a8ac9b7c991fde9be35ad4b939771afb6ec4f5c1c675e4", + "full:00:0:compose:none:00": "297f68c33d0a1b93faf873b5406530313c43e40c7f8d678621ce9a44383c64a4", + "full:00:0:compose:compose:11": "725154189ee3c9122ed8cc724f4e063afe781d67ca2a3d0c5520b8f879e2eae8", + "full:00:0:compose:compose:10": "6d1f7510ad6b84212bd120614d57a38500146c97bf10c2fdcd7160bc3d3bd9a0", + "full:00:0:compose:compose:01": "48fd52f95e7fc135245b7028c527552a435a8999abcea57d97d2e8fa55382486", + "full:00:0:compose:compose:00": "36166430066476c6763bd29ab0efddf044d17627c4fd2d690b96aea15db843c6" }, "skills_header": "\n\nSkills:\n- This workspace keeps skills, guidance documents for specific kinds of tasks, listed below by path and description. read_skill returns one: read it when a request matches its description, then do the work with the tools above.\n", "skill_line": "- {{skill_path}}: {{skill_description}}", diff --git a/backend/windmill-api/src/ai_session_tools/instructions.rs b/backend/windmill-api/src/ai_session_tools/instructions.rs index 9b12293506..6d7ab2b6e7 100644 --- a/backend/windmill-api/src/ai_session_tools/instructions.rs +++ b/backend/windmill-api/src/ai_session_tools/instructions.rs @@ -1,26 +1,58 @@ //! The instructions a client receives on connecting: the session's system prompt as -//! rendered for an external client (`gen/prompt.json`), filled in for the caller. What -//! differs per workspace is cut out of it, so a connection spanning several workspaces -//! gets the rest up front and each workspace's part from `get_workspace_context`. +//! rendered for an external client, filled in for the caller. `gen/prompt.json` holds one +//! template (`EXTERNAL_PROMPT` in the chat's `global/core.ts`) and, per access profile, the +//! flags and variables the generator computed for it: what the caller may do is decided there, +//! and only rendered here. The profile is the token's scope and, for a full token, the caller's +//! role in the workspace. The folder guidance differs per workspace, so a connection spanning +//! several workspaces gets the rest up front and each workspace's part from +//! `get_workspace_context`. +use std::collections::{HashMap, HashSet}; use std::sync::LazyLock; use serde::Deserialize; +use windmill_common::{ + roles::{caller_capabilities, AuthorLevel, RoleCapabilities}, + workspaces::{check_deploy_rules, RuleCheckResult}, + DB, +}; use windmill_mcp::server::McpAuth; -use super::{guidance::list_skills, Ctx}; +use super::{guidance::list_skills, Ctx, SessionAccess}; -/// The prompt with a `{{folder_guidance}}` slot, the guidance once per folder situation, -/// and the sections appended when the workspace has something to put there. +/// As generated by `mcpSessionGen.test.ts`. #[derive(Deserialize)] struct PromptParts { - base: String, - folder_guidance: FolderGuidance, + template: String, + profiles: HashMap<String, Profile>, + folder_guidance: FolderGuidanceSets, + #[cfg_attr(not(test), allow(dead_code))] + rendered_sha256: HashMap<String, String>, skills_header: String, skill_line: String, workspace_instructions: String, } +#[derive(Deserialize)] +struct Profile { + /// The flags set, space-separated. + flags: String, + vars: HashMap<String, String>, +} + +impl Profile { + fn flags(&self) -> HashSet<&str> { + self.flags.split_whitespace().collect() + } +} + +#[derive(Deserialize)] +struct FolderGuidanceSets { + create_folder: FolderGuidance, + no_create_folder: FolderGuidance, +} + +/// The `{{folder_guidance}}` text per folder situation, with its leading newline. #[derive(Deserialize)] struct FolderGuidance { admin: String, @@ -35,6 +67,136 @@ static PARTS: LazyLock<PromptParts> = LazyLock::new(|| { serde_json::from_str(include_str!("gen/prompt.json")).expect("gen/prompt.json is valid") }); +/// `promptTemplate.ts`'s grammar, which this must render identically (the generator's +/// `rendered_sha256` pins it): `{{#flag}}…{{/flag}}` keeps its body when the flag is set, +/// `{{^flag}}…{{/flag}}` when it is not, `{{name}}` takes a variable, and a variable not given +/// stays as written for a later pass to fill. +fn render_template( + template: &str, + flags: &HashSet<&str>, + vars: &HashMap<String, String>, +) -> String { + let mut out = String::with_capacity(template.len()); + // Each open section, and whether it keeps its body. + let mut open: Vec<(&str, bool)> = Vec::new(); + let mut rest = template; + while let Some(start) = rest.find("{{") { + let keeping = open.iter().all(|(_, keep)| *keep); + let Some(tag) = rest[start + 2..] + .find("}}") + .map(|end| &rest[start + 2..start + 2 + end]) + else { + break; + }; + let (kind, name) = match tag.as_bytes().first() { + Some(b'#' | b'^' | b'/') => (Some(tag.as_bytes()[0]), &tag[1..]), + _ => (None, tag), + }; + if name.is_empty() || !name.bytes().all(|b| b.is_ascii_lowercase() || b == b'_') { + // Not a tag: keep the first brace as text, as the regex there scans on. + if keeping { + out.push_str(&rest[..start + 1]); + } + rest = &rest[start + 1..]; + continue; + } + if keeping { + out.push_str(&rest[..start]); + } + let whole = &rest[start..start + 4 + tag.len()]; + rest = &rest[start + whole.len()..]; + match kind { + Some(b'#') => open.push((name, flags.contains(name))), + Some(b'^') => open.push((name, !flags.contains(name))), + Some(_) => { + let closed = open.pop().map(|(n, _)| n); + debug_assert_eq!(closed, Some(name), "unbalanced prompt template"); + } + None if keeping => out.push_str(vars.get(name).map_or(whole, String::as_str)), + None => {} + } + } + if open.iter().all(|(_, keep)| *keep) { + out.push_str(rest); + } + out +} + +/// The key of a full-access caller holding every capability: what a connection spanning +/// several workspaces is told before it learns its role in each. +const UNRESTRICTED: &str = "full:11:1:full:full:11"; + +fn level(level: AuthorLevel) -> &'static str { + match level { + AuthorLevel::None => "none", + AuthorLevel::Compose => "compose", + AuthorLevel::Full => "full", + } +} + +fn bit(b: bool) -> char { + if b { + '1' + } else { + '0' + } +} + +/// Which generated prompt the caller reads, keyed as `mcpSessionGen.test.ts` generates them. +/// A failed lookup reads as allowed: the prompt only describes, the API still refuses. +pub(crate) async fn prompt_profile( + db: &DB, + auth: &crate::db::ApiAuthed, + w_id: &str, + access: SessionAccess, +) -> String { + match access { + SessionAccess::ReadOnly => return "read_only".to_string(), + SessionAccess::ReadAndRun => return "read_run".to_string(), + SessionAccess::Full => {} + } + let caps = caller_capabilities(db, w_id, auth) + .await + .unwrap_or(RoleCapabilities::FULL); + let deploy = !matches!( + check_deploy_rules(w_id, &auth.username, &auth.groups, auth.is_admin, db).await, + Ok(RuleCheckResult::Blocked(_)) + ); + full_profile(auth.is_admin, deploy, &caps) +} + +fn full_profile(is_admin: bool, deploy: bool, caps: &RoleCapabilities) -> String { + format!( + "full:{}{}:{}:{}:{}:{}{}", + bit(is_admin), + bit(deploy), + bit(caps.code), + level(caps.flows), + level(caps.apps), + bit(caps.manage_schedules), + bit(caps.manage_triggers), + ) +} + +fn profile_for(profile: &str) -> &'static Profile { + let parts = &*PARTS; + // A role no profile covers (full flows without code, which writes refuse) reads as the + // unrestricted one. + parts + .profiles + .get(profile) + .or_else(|| parts.profiles.get(UNRESTRICTED)) + .expect("the unrestricted profile is generated") +} + +/// The prompt for `profile`, with the caller's username and folder guidance filled in. +fn render(profile: &Profile, username: &str, folder_guidance: &str) -> String { + let mut vars = profile.vars.clone(); + vars.insert("username".to_string(), username.to_string()); + vars.insert("folder_guidance".to_string(), folder_guidance.to_string()); + render_template(&PARTS.template, &profile.flags(), &vars) +} + /// Folders named in the prompt before the rest are counted rather than listed, as the /// session does, so a folder-heavy workspace cannot dominate the instructions. const MAX_LISTED_FOLDERS: usize = 40; @@ -53,7 +215,17 @@ fn folder_list(names: &[&str]) -> String { } } -fn folder_guidance(auth: &crate::db::ApiAuthed) -> String { +/// Flags of `EXTERNAL_PROMPT` this file reads itself, which `folder_guidance_follows_the_template` +/// pins: the template shows the folder guidance only under the first, in path conventions that +/// name `create_folder` under the second. +const WRITES_FLAG: &str = "can_write_any_draft"; +const CREATE_FOLDER_FLAG: &str = "can_create_folder"; + +fn folder_guidance(auth: &crate::db::ApiAuthed, profile: &Profile) -> String { + let flags = profile.flags(); + if !flags.contains(WRITES_FLAG) { + return String::new(); + } let writable: Vec<&str> = auth .folders() .iter() @@ -67,7 +239,11 @@ fn folder_guidance(auth: &crate::db::ApiAuthed) -> String { .map(|(name, _, _)| name.as_str()) .collect(); - let guidance = &PARTS.folder_guidance; + let guidance = if flags.contains(CREATE_FOLDER_FLAG) { + &PARTS.folder_guidance.create_folder + } else { + &PARTS.folder_guidance.no_create_folder + }; let template = match (auth.is_admin(), writable.is_empty(), readonly.is_empty()) { (true, false, _) => &guidance.admin, (true, true, _) => &guidance.admin_no_folders, @@ -121,32 +297,142 @@ async fn appendix(ctx: &Ctx<'_>) -> String { } /// The whole prompt, for a connection that reaches one workspace. -pub(crate) async fn session_instructions(ctx: &Ctx<'_>) -> String { - let mut prompt = PARTS - .base - .replace("{{folder_guidance}}", &folder_guidance(ctx.auth)) - .replace("{{username}}", ctx.auth.username()); - prompt.push_str(&appendix(ctx).await); - prompt +pub(crate) async fn session_instructions(ctx: &Ctx<'_>, profile: &str) -> String { + let profile = profile_for(profile); + let mut text = render( + profile, + ctx.auth.username(), + &folder_guidance(ctx.auth, profile), + ); + text.push_str(&appendix(ctx).await); + text } /// The prompt without anything specific to a workspace, for a connection that reaches -/// several: usernames are per workspace, so paths read `u/<username>/...`. -pub(crate) fn generic_session_instructions() -> String { - PARTS - .base - .replace("{{folder_guidance}}", "") - .replace("{{username}}", "<username>") +/// several: usernames and roles are per workspace, so paths read `u/<username>/...` and a full +/// token reads the unrestricted prompt until `workspace_context` narrows it. +pub(crate) fn generic_session_instructions(access: SessionAccess) -> String { + render(profile_for(generic_profile(access)), "<username>", "") } -/// What `generic_session_instructions` leaves out, for one workspace. -pub(crate) async fn workspace_context(ctx: &Ctx<'_>) -> String { +fn generic_profile(access: SessionAccess) -> &'static str { + match access { + SessionAccess::ReadOnly => "read_only", + SessionAccess::ReadAndRun => "read_run", + SessionAccess::Full => UNRESTRICTED, + } +} + +/// What `generic_session_instructions(token_access)` leaves out, for one workspace. A role or +/// workspace that narrows the prompt gets its own in full, since its rules replace the general +/// ones; `ctx.access` may be narrower than the token's. +pub(crate) async fn workspace_context( + ctx: &Ctx<'_>, + profile: &str, + token_access: SessionAccess, +) -> String { let username = ctx.auth.username(); - format!( + let header = format!( "Workspace `{}`. Your username here is \"{username}\", so your personal paths are \ - `u/{username}/<name>`.\n{}{}", - ctx.w_id, - folder_guidance(ctx.auth).trim_end(), + `u/{username}/<name>`.\n", + ctx.w_id + ); + let profile = profile_for(profile); + let folders = folder_guidance(ctx.auth, profile); + // Roles that differ in name can read the same prompt, so the text decides. + let general = + render(profile, "", "") == render(profile_for(generic_profile(token_access)), "", ""); + let body = if general { + folders.trim_end().to_string() + } else { + format!( + "Your access in this workspace is narrower than the general instructions assume. \ + Here, these rules replace them:\n\n{}", + render(profile, username, &folders) + ) + }; + format!( + "{header}{}{}", + body.trim_start_matches('\n'), appendix(ctx).await ) } + +#[cfg(test)] +mod tests { + use super::*; + use sha2::{Digest, Sha256}; + + #[test] + fn folder_guidance_follows_the_template() { + for (key, profile) in &PARTS.profiles { + let flags = profile.flags(); + let mut vars = profile.vars.clone(); + vars.insert("folder_guidance".to_string(), "@@folders@@".to_string()); + let text = render_template(&PARTS.template, &flags, &vars); + assert_eq!( + text.contains("@@folders@@"), + flags.contains(WRITES_FLAG), + "{key}" + ); + assert_eq!( + text.contains("create_folder"), + flags.contains(CREATE_FOLDER_FLAG), + "{key}" + ); + } + } + + /// This renderer reads every profile as `promptTemplate.ts` rendered it when generating. + #[test] + fn renders_every_profile_as_the_generator_did() { + for (key, profile) in &PARTS.profiles { + let text = render_template(&PARTS.template, &profile.flags(), &profile.vars); + assert_eq!( + hex::encode(Sha256::digest(text.as_bytes())), + PARTS.rendered_sha256[key], + "{key}" + ); + } + } + + /// Every role a caller can hold reads a prompt generated for it, rather than falling back + /// to the unrestricted one: the keys here and in `mcpSessionGen.test.ts` must agree. + #[test] + fn every_valid_role_has_a_generated_prompt() { + let levels = [AuthorLevel::None, AuthorLevel::Compose, AuthorLevel::Full]; + for deploy in [true, false] { + assert!(PARTS.profiles.contains_key(&full_profile( + true, + deploy, + &RoleCapabilities::FULL + ))); + for code in [true, false] { + for flows in levels { + for apps in levels { + if !code && (flows == AuthorLevel::Full || apps == AuthorLevel::Full) { + continue; + } + for (manage_schedules, manage_triggers) in + [(true, true), (true, false), (false, true), (false, false)] + { + let caps = RoleCapabilities { + code, + flows, + apps, + manage_schedules, + manage_triggers, + ..RoleCapabilities::FULL + }; + let key = full_profile(false, deploy, &caps); + assert!(PARTS.profiles.contains_key(&key), "{key}"); + } + } + } + } + } + assert!( + PARTS.profiles.contains_key("read_only") && PARTS.profiles.contains_key("read_run") + ); + } +} diff --git a/backend/windmill-api/src/ai_session_tools/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs index 6928545039..045b87af39 100644 --- a/backend/windmill-api/src/ai_session_tools/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -75,7 +75,7 @@ mod workspace; #[cfg(feature = "mcp")] pub(crate) use instructions::{ - generic_session_instructions, session_instructions, workspace_context, + generic_session_instructions, prompt_profile, session_instructions, workspace_context, }; #[derive(Deserialize)] @@ -750,7 +750,7 @@ async fn call_generated_tool( _ => "is read-only", }; return Err(CallRefused::NotAllowed(format!( - "Tool '{name}' changes or runs something, and this token {token}" + "Tool '{name}' changes or runs something, and this session {token}" ))); } dispatch(ctx, name, args).await.ok_or_else(|| { diff --git a/backend/windmill-api/src/ai_session_tools/views.rs b/backend/windmill-api/src/ai_session_tools/views.rs index 9ecf77d493..596d8f0630 100644 --- a/backend/windmill-api/src/ai_session_tools/views.rs +++ b/backend/windmill-api/src/ai_session_tools/views.rs @@ -20,7 +20,7 @@ pub(crate) fn allowed(name: &str, access: SessionAccess) -> bool { pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { if !allowed(name, ctx.access) { return Err(format!( - "{name} shows drafts to deploy, and this token cannot deploy." + "{name} shows drafts to deploy, and this session cannot deploy." )); } match name { diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 7055aada3d..a691660b03 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -6,6 +6,7 @@ use async_trait::async_trait; use serde_json::Value; use std::collections::HashMap; +use windmill_common::workspaces::{get_protection_rules, ProtectionRules, ProtectionRuleset}; use windmill_common::{db::UserDB, runnable_ref::RunnableRef, DB}; use windmill_mcp::common::schema::enrich_resource_schemas; use windmill_mcp::common::transform::transform_property_keys; @@ -66,23 +67,36 @@ pub struct WindmillBackend { pub auth_cache: Arc<AuthCache>, } -impl WindmillBackend { - /// The instructions only read, so they are built at the token's own read-only flag. - fn session_ctx<'a>(&'a self, auth: &'a ApiAuthed, w_id: &'a str) -> session::Ctx<'a> { - let access = if auth.read_only { - SessionAccess::ReadOnly - } else { - SessionAccess::Full - }; - self.session_ctx_with(auth, w_id, access) +/// `DisableDirectDeployment` holds a session to reading and running deployed items for +/// everyone, admins and bypassers included: that workspace takes changes from its dev workspace +/// or a fork, where drafts can go somewhere. Unreadable rules (`None`) hold it too. The in-app +/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both. +fn workspace_access(access: SessionAccess, rules: Option<&[ProtectionRuleset]>) -> SessionAccess { + let locked = rules.map_or(true, |rules| { + rules + .iter() + .any(|r| r.rules.contains(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)) + }); + match access { + SessionAccess::Full if locked => SessionAccess::ReadAndRun, + other => other, } +} - fn session_ctx_with<'a>( +impl WindmillBackend { + async fn session_ctx_with<'a>( &'a self, auth: &'a ApiAuthed, w_id: &'a str, access: SessionAccess, ) -> session::Ctx<'a> { + let access = match access { + SessionAccess::Full => { + let rules = get_protection_rules(w_id, &self.db).await.ok(); + workspace_access(access, rules.as_deref().map(Vec::as_slice)) + } + other => other, + }; session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access)) } @@ -470,16 +484,26 @@ impl McpBackend for WindmillBackend { &self, auth: &ApiAuthed, workspace_id: &str, + access: SessionAccess, ) -> BackendResult<String> { - Ok(session::session_instructions(&self.session_ctx(auth, workspace_id)).await) + let ctx = self.session_ctx_with(auth, workspace_id, access).await; + let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await; + Ok(session::session_instructions(&ctx, &profile).await) } - fn generic_session_instructions(&self) -> String { - session::generic_session_instructions() + fn generic_session_instructions(&self, access: SessionAccess) -> String { + session::generic_session_instructions(session::access(access)) } - async fn workspace_context(&self, auth: &ApiAuthed, workspace_id: &str) -> String { - session::workspace_context(&self.session_ctx(auth, workspace_id)).await + async fn workspace_context( + &self, + auth: &ApiAuthed, + workspace_id: &str, + access: SessionAccess, + ) -> String { + let ctx = self.session_ctx_with(auth, workspace_id, access).await; + let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await; + session::workspace_context(&ctx, &profile, session::access(access)).await } fn session_tools(&self, access: SessionAccess) -> Vec<Tool> { @@ -499,7 +523,7 @@ impl McpBackend for WindmillBackend { access: SessionAccess, origin: Option<&str>, ) -> BackendResult<CallToolResult> { - let mut ctx = self.session_ctx_with(auth, workspace_id, access); + let mut ctx = self.session_ctx_with(auth, workspace_id, access).await; ctx.origin = origin; session::call_session_tool(&ctx, name, args).await } @@ -867,7 +891,30 @@ pub fn toolset_service() -> Router { #[cfg(test)] mod tests { - use super::{scoped_to_selection, serves_session_toolset}; + use super::{ + scoped_to_selection, serves_session_toolset, workspace_access, ProtectionRules, + ProtectionRuleset, SessionAccess, + }; + + #[test] + fn direct_deployment_lock_holds_full_sessions_to_read_and_run() { + let ruleset = |rules| ProtectionRuleset { + workspace_id: "w".to_string(), + name: "r".to_string(), + rules, + bypass_groups: vec![], + bypass_users: vec!["admin".to_string()], + fork_role_mapping: Default::default(), + }; + let locked = [ruleset(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)]; + let open = [ruleset(ProtectionRules::RESTRICT_DEPLOY_TO_DEPLOYERS)]; + use SessionAccess::*; + assert_eq!(workspace_access(Full, Some(&locked)), ReadAndRun); + assert_eq!(workspace_access(Full, None), ReadAndRun); + assert_eq!(workspace_access(Full, Some(&open)), Full); + assert_eq!(workspace_access(Full, Some(&[])), Full); + assert_eq!(workspace_access(ReadOnly, Some(&locked)), ReadOnly); + } #[test] fn only_a_token_without_mcp_all_is_a_selection() { diff --git a/backend/windmill-api/src/mcp/session.rs b/backend/windmill-api/src/mcp/session.rs index 0d1ee40b9f..32ccbb944f 100644 --- a/backend/windmill-api/src/mcp/session.rs +++ b/backend/windmill-api/src/mcp/session.rs @@ -9,7 +9,7 @@ use windmill_mcp::server::{ use crate::ai_session_tools::{self as tools, CallRefused}; pub(super) use tools::{ - generic_session_instructions, session_instructions, workspace_context, Ctx, + generic_session_instructions, prompt_profile, session_instructions, workspace_context, Ctx, }; pub(super) fn access(access: SessionAccess) -> tools::SessionAccess { diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 76613525db..98831279d5 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -261,18 +261,24 @@ pub trait McpBackend: Send + Sync + Clone + 'static { // ───────────────────────────────────────────────────────────────── /// The instructions a client reaching one workspace receives on connecting, built for - /// this user. + /// this user and what the token lets them do. async fn session_instructions( &self, auth: &Self::Auth, workspace_id: &str, + access: SessionAccess, ) -> BackendResult<String>; /// The instructions for a client reaching several workspaces: what holds in all of them. - fn generic_session_instructions(&self) -> String; + fn generic_session_instructions(&self, access: SessionAccess) -> String; /// What `generic_session_instructions` leaves out, for one workspace. - async fn workspace_context(&self, auth: &Self::Auth, workspace_id: &str) -> String; + async fn workspace_context( + &self, + auth: &Self::Auth, + workspace_id: &str, + access: SessionAccess, + ) -> String; /// The tools a token with this access is offered. fn session_tools(&self, access: SessionAccess) -> Vec<Tool>; diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs index 4632541d0c..25d9da8dea 100644 --- a/backend/windmill-mcp/src/server/session.rs +++ b/backend/windmill-mcp/src/server/session.rs @@ -196,7 +196,9 @@ impl<B: McpBackend> SessionRunner<B> { "Every tool takes a `workspace_id`: pass `{}`, the workspace this connection \ works in.\n\n{}", only.id, - self.backend.session_instructions(&auth, &only.id).await? + self.backend + .session_instructions(&auth, &only.id, access(&auth, &caller.scope)) + .await? ) } _ => { @@ -220,7 +222,8 @@ impl<B: McpBackend> SessionRunner<B> { below), the folders you can write to, and the workspace's skills and \ instructions. When the user has not said which workspace, ask rather than \ guess, and name the workspace whenever you change something.\n\n{}", - self.backend.generic_session_instructions() + self.backend + .generic_session_instructions(access(&caller.auth, &caller.scope)) ) } }; @@ -371,7 +374,10 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> { }; let auth = self.auth_in(&caller, &workspace_id).await?; if request.name == GET_WORKSPACE_CONTEXT { - let text = self.backend.workspace_context(&auth, &workspace_id).await; + let text = self + .backend + .workspace_context(&auth, &workspace_id, access(&auth, &caller.scope)) + .await; return Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into()); } let result = self diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 3a8882f8c5..504447195a 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -22,6 +22,7 @@ import { import { deepEqual } from 'fast-equals' import { promptSafe, type ArtifactVersionTarget } from '$lib/components/sessions/previewRouter' import { canDraftItem, roleCanDraft } from '$lib/editRights' +import { renderPromptTemplate } from './promptTemplate' import { $ScriptLang } from '$lib/gen/schemas.gen' import type { CreateVariable, @@ -1335,7 +1336,7 @@ type FolderPromptContext = { // write anywhere, but `folders` only carries their explicitly-permissioned subset, // so for admins it is a non-exhaustive hint and list_workspace_items has the rest. // Capped so a folder-heavy workspace can't dominate the prompt. -function buildFolderGuidance( +export function buildFolderGuidance( username: string, ctx: FolderPromptContext | undefined, canCreateFolder: boolean, @@ -1389,50 +1390,118 @@ function buildFolderGuidance( const listJoin = (items: (string | false)[], type: 'conjunction' | 'disjunction' = 'conjunction') => new Intl.ListFormat('en', { type }).format(items.filter((i): i is string => !!i)) -// The prompt an external MCP client reads. A directory reviewer reads it as a description of -// what the server does, so it names only the server's own tools and leaves how each one works -// to its description and to get_instructions. OpenAI asks for the most important details in -// the first 512 characters and some clients keep only the first 4096, so the drafts rule -// opens and the rules come before the path conventions. -function buildExternalPrompt(username: string, paths: string, skills: AiSkillListItem[]) { - return `This server works in a Windmill workspace as the user "${username}". +// Prompt templates: `{{#flag}}…{{/flag}}` keeps its body when the flag is set, `{{^flag}}…{{/flag}}` +// when it is not, and `{{name}}` takes a variable (`promptTemplate.ts`). A block carries its own +// leading newline, so a dropped one leaves no blank line behind. -Rules: -- What you write is a per-user draft, saved server-side and visible only to this user. Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks. -- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (\`url\`), an app draft's editor with its live preview (\`preview_url\`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link. -- Find items with list_workspace_items and read one with read_workspace_item before changing it. An agent is a resource of type \`ai_agent\`: test it with test_run_agent and run a deployed one with run_agent, never run_flow or run_script. -- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language. Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and get_db_schema before writing SQL against a database resource. -- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying. -- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version "deployed" so the arguments match. -- To undo your own work, discard its draft with discard_local_draft. delete_workspace_item removes an item that is deployed. +// Shared by the chat and the external prompt. Flags: can_write_any_draft, can_create_folder. +// Variables: username, folder_guidance (the folder lines, with their leading newline). +const PATH_CONVENTIONS = `{{#can_write_any_draft}} + +Path conventions: +- A workspace path starts with one of two namespaces; its trailing <name> may itself contain "/", so a path has three or more segments: + - \`u/{{username}}/<name>\` — your personal scope. Default for ad-hoc, exploratory, or scratch work. + - \`f/<folder>/<name>\` — a shared folder scope; the <folder> must already exist (a bare \`f/<name>\` with no folder segment is INVALID and will fail). +- If the user supplies a fully qualified \`f/<folder>/...\` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a \`u/{{username}}/...\` path unless a tool rejects it. +- Default a bare name with no namespace prefix (e.g. "create a flow called myflow") to \`u/{{username}}/<name>\`. Never invent an \`f/<folder>/...\` path for a folder that does not exist{{#can_create_folder}}; create one with \`create_folder\` only when the user explicitly asks for a new folder{{/can_create_folder}}.{{folder_guidance}}{{/can_write_any_draft}}{{#can_create_folder}}{{^can_write_any_draft}} +- You can create a shared folder with \`create_folder\` when the user explicitly asks for one. You cannot create anything inside it here, so do not offer to.{{/can_write_any_draft}}{{/can_create_folder}}` + +// The prompt an external MCP client reads, rendered with the flags `externalPromptProfile` gives +// an access profile: by the MCP server from `gen/prompt.json`, and by `buildGlobalSystemPrompt`. A directory reviewer reads it as a +// description of what the server does, so it names only the server's own tools and leaves how +// each one works to its description and to get_instructions. OpenAI asks for the most +// important details in the first 512 characters and some clients keep only the first 4096, so +// the drafts rule opens and the rules come before the path conventions. +// Each gated block mirrors a tool the server refuses this access: what a read-only token or a +// restricted role cannot do is stated up front rather than left to a failed call. +export const EXTERNAL_PROMPT = `This server works in a Windmill workspace as the user "{{username}}".{{#read_only}}{{#runs_deployed}} + +This connection can read the workspace's items, runs and data, and run scripts, flows and agents that are already deployed. It cannot create, edit, deploy or delete anything, nor test-run code that is not deployed: when the user asks for such a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{^runs_deployed}} + +This connection is read-only: it can read the workspace's items, runs and data, but cannot run, create, edit, deploy or delete anything. When the user asks for a run or a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{/read_only}}{{^read_only}}{{^can_write_draft}} + +This user's role does not let them create or edit {{refused_kinds}} here, so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had, and suggest asking a workspace admin, who can grant their role more.{{#builds_flows}} Their role does let them compose flows out of scripts and flows that are already deployed: write flows with write_flow and patch_flow_json, every step calling a deployed script or flow by path. The server refuses inline code anywhere in the flow, so when a flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.{{/builds_flows}}{{#builds_apps}} Their role does let them build raw apps whose backend runnables are path runnables to deployed scripts or flows; call get_instructions with subject "app" first. The server refuses inline and hub runnables, and runs an app they deploy sandboxed, as the user who deployed it.{{/builds_apps}}{{#has_draft_tools}} They can draft with {{draft_tools}}.{{/has_draft_tools}}{{/can_write_draft}}{{/read_only}} + +Rules:{{#can_write_any_draft}} +- What you write is a per-user draft, saved server-side and visible only to this user. {{#can_deploy}}Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks.{{/can_deploy}}{{^can_deploy}}{{#can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, and this workspace's deploy rules let this user deploy only the schedules and triggers their role manages: call deploy_workspace_item for those only when the user asks, and for anything else give them the draft's link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{^can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, which this workspace's deploy rules do not let this user do: when a draft is ready, give them its link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{/can_deploy}}{{/can_write_any_draft}} +{{#can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (\`url\`), an app draft's editor with its live preview (\`preview_url\`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}{{^can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, an item's page. Whenever the user will want to see what you found{{#runs}} or ran{{/runs}}, or has to do a step in Windmill themselves: show it with show_run, show_runs or show_item when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}} +- Find items with list_workspace_items and read one with read_workspace_item{{#can_write_any_draft}} before changing it{{/can_write_any_draft}}. An agent is a resource of type \`ai_agent\`{{#runs}}: {{#can_run_flow_preview}}test it with test_run_agent and {{/can_run_flow_preview}}run a deployed one with run_agent, never run_flow or run_script.{{/runs}}{{^runs}}.{{/runs}}{{#can_write_draft}} +- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and{{/can_draft_triggers}}{{^can_draft_triggers}} Call{{/can_draft_triggers}} get_db_schema before writing SQL against a database resource.{{/can_write_draft}}{{^can_write_draft}}{{#can_draft_resources}} +- Call get_instructions before writing a resource.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields.{{/can_draft_triggers}}{{/can_draft_resources}}{{/can_write_draft}}{{#can_write_draft}}{{#can_run_preview}} +- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying.{{/can_run_preview}}{{/can_write_draft}}{{^can_write_draft}}{{#builds_flows}}{{#can_run_flow_preview}} +- After writing a flow, test it with test_run_flow before saying it works. It runs the draft, so nothing needs deploying.{{/can_run_flow_preview}}{{/builds_flows}}{{/can_write_draft}}{{#can_run_preview}} +- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version "deployed" so the arguments match.{{/can_run_preview}}{{^can_run_preview}}{{#can_run_flow_preview}} +- A request to run a flow or agent also goes to test_run_flow or test_run_agent, which run the draft. Use run_flow or run_agent only when the user asks for the deployed version, and run_script for any script: those run the DEPLOYED item as this user, so read it with read_workspace_item version "deployed" first so the arguments match.{{/can_run_flow_preview}}{{^can_run_flow_preview}}{{#runs}} +- run_script, run_flow and run_agent are how you run anything here: they run the DEPLOYED item as this user. Read it with read_workspace_item version "deployed" first so the arguments match.{{/runs}}{{/can_run_flow_preview}}{{/can_run_preview}}{{#can_write_any_draft}} +- To undo your own work, discard its draft with discard_local_draft.{{#can_deploy_any_kind}} delete_workspace_item removes an item that is deployed.{{/can_deploy_any_kind}}{{/can_write_any_draft}}{{^can_write_any_draft}}{{^read_only}} +- You cannot create or edit anything, but where the server allows it discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes a deployed item.{{/read_only}}{{/can_write_any_draft}}{{^read_only}}{{#unmanaged}} +- This workspace does not let this user change {{unmanaged_kinds}}, here or in Windmill: suggest asking a workspace admin.{{/unmanaged}}{{/read_only}} - Listings return only what this user can see. When an item they name is missing, say it may be in a folder they cannot read, not that it does not exist. -- No one can read a variable's value through these tools. When editing a variable, pass only the fields that change. -- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration. -- Only raw apps (\`rawApp\` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words. -- Datatables are set up in the workspace settings. Start from list_datatables; one with \`migrations_enabled\` changes its schema through migrations only. -- create_resource_type adds a resource type: show the user the schema first and create it once they agree. -- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.${paths}${ - skills.length > 0 - ? ` +- No one can read a variable's value through these tools.{{#can_draft_variables}} When editing a variable, pass only the fields that change.{{/can_draft_variables}}{{#can_write_draft}} +- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration.{{/can_write_draft}} +- {{#can_write_app_draft}}Only raw apps (\`rawApp\` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words.{{/can_write_app_draft}}{{^can_write_app_draft}}Only raw apps (\`rawApp\` true) can be read here.{{/can_write_app_draft}} +- Datatables are set up in the workspace settings. Start from list_datatables; one with \`migrations_enabled\` changes its schema through migrations only.{{#can_draft_resources}}{{#can_create_resource_type}} +- create_resource_type adds a resource type: show the user the schema first and create it once they agree.{{/can_create_resource_type}}{{^can_create_resource_type}} +- This user cannot create a resource type here, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin.{{/can_create_resource_type}}{{/can_draft_resources}} +- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.${PATH_CONVENTIONS}` + +/** The flags and variables `EXTERNAL_PROMPT` renders with for one access profile, which the + * generator exports per `prompt_profile` key: the server only fills the template. */ +export function externalPromptProfile(access: SessionAccess | undefined, runsDeployed: boolean) { + const a = accessFlags(access) + const flags: Record<string, boolean> = { + read_only: a.readOnly, + runs_deployed: runsDeployed, + runs: !a.readOnly || runsDeployed, + can_write_any_draft: a.canWriteAnyDraft, + can_write_draft: a.canWriteDraft, + can_write_app_draft: a.canWriteAppDraft, + builds_flows: a.buildsFlows, + builds_apps: a.buildsApps, + has_draft_tools: + a.canDraftResources || a.canDraftVariables || a.canDraftSchedules || a.canDraftTriggers, + can_draft_triggers: a.canDraftTriggers, + can_draft_resources: a.canDraftResources, + can_draft_variables: a.canDraftVariables, + can_deploy: a.canDeploy, + can_deploy_any_kind: a.canDeployAnyKind, + can_run_preview: a.canRunPreview, + can_run_flow_preview: a.canRunFlowPreview, + unmanaged: !a.canManageSchedules || !a.canManageTriggers, + can_create_resource_type: a.canCreateResourceType, + can_create_folder: a.canCreateFolder + } + return { + flags: new Set(Object.keys(flags).filter((f) => flags[f])), + vars: { + refused_kinds: listJoin(a.refusedKinds, 'disjunction'), + draft_tools: listJoin([ + a.canDraftResources && 'write_resource', + a.canDraftVariables && 'write_variable', + a.canDraftSchedules && 'write_schedule', + a.canDraftTriggers && 'write_trigger' + ]), + unmanaged_kinds: + !a.canManageSchedules && !a.canManageTriggers + ? 'schedules or triggers' + : !a.canManageSchedules + ? 'schedules' + : 'triggers' + } + } +} + +function externalSkills(skills: AiSkillListItem[]): string { + return skills.length > 0 + ? ` Skills: - This workspace keeps skills, guidance documents for specific kinds of tasks, listed below by path and description. read_skill returns one: read it when a request matches its description, then do the work with the tools above. ${skills.map((s) => `- ${s.path}: ${s.description}`).join('\n')}` - : '' - }` + : '' } -const buildGlobalSystemPrompt = ( - username: string, - previewTools: boolean, - folderCtx?: FolderPromptContext, - skills: AiSkillListItem[] = [], - mcpServers: McpServer[] = [], - access?: SessionAccess, - // The prompt an external MCP client reads (`buildExternalPrompt`): it shares only the path - // conventions, which carry the folder guidance. - external = false -) => { +function accessFlags(access: SessionAccess | undefined) { // Each `can*` mirrors the capability the matching tools declare in `requires`, so a // rule cannot outlive the tool it describes. An unresolved profile keeps every block. const canWriteDraft = !access || access.has('write_draft') @@ -1502,6 +1571,76 @@ const buildGlobalSystemPrompt = ( // resource type text. const canCreateFolder = !access || access.has('deploy') const canCreateResourceType = !access || access.has('deploy') + return { + canWriteDraft, + canWriteFlowDraft, + canWriteAppDraft, + canDraftSchedules, + canDraftTriggers, + canDraftResources, + canDraftVariables, + inlineFlowCode, + buildsFlows, + buildsApps, + canWriteAnyDraft, + canDeploy, + readOnly, + canDeployAnyKind, + draftedKinds, + draftedOperatorKinds, + deployableKinds, + refusedKinds, + refusedCode, + canRunPreview, + canRunFlowPreview, + testRunTools, + canManageSchedules, + canManageTriggers, + canCreateFolder, + canCreateResourceType + } +} + +const buildGlobalSystemPrompt = ( + username: string, + previewTools: boolean, + folderCtx?: FolderPromptContext, + skills: AiSkillListItem[] = [], + mcpServers: McpServer[] = [], + access?: SessionAccess, + // The prompt an external MCP client reads (`EXTERNAL_PROMPT`): it shares only the path + // conventions, which carry the folder guidance. + external = false, + // Whether a read-only external session may still run deployed items (`mcp:read_run`). + runsDeployed = true +) => { + const { + canWriteDraft, + canWriteFlowDraft, + canWriteAppDraft, + canDraftSchedules, + canDraftTriggers, + canDraftResources, + canDraftVariables, + inlineFlowCode, + buildsFlows, + buildsApps, + canWriteAnyDraft, + readOnly, + canDeployAnyKind, + draftedKinds, + draftedOperatorKinds, + deployableKinds, + refusedKinds, + refusedCode, + canRunPreview, + canRunFlowPreview, + testRunTools, + canManageSchedules, + canManageTriggers, + canCreateFolder, + canCreateResourceType + } = accessFlags(access) // Each gated block carries its own leading newline, so dropping one leaves no blank // line behind and a full-access prompt is byte-for-byte the ungated text. const when = (cond: boolean, block: string) => (cond ? block : '') @@ -1562,6 +1701,9 @@ const buildGlobalSystemPrompt = ( ` - Use deploy_workspace_item only after the user explicitly asks to deploy. It persists a draft to the workspace.` ) + const resourceTypeRule = canCreateResourceType + ? '- create_resource_type creates a resource type the workspace lacks. The user confirms the schema in the call itself, so that is where you propose it rather than asking first in chat.\n' + : '- This user cannot create a resource type here, in chat or on the Resources page, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin, who can add it.\n' const instructionsRule = '- Use get_instructions before writing scripts, flows, resources, or apps. For scripts, pass the target language.' const testDraftRule = `- After creating or editing a script${canWriteFlowDraft ? ' or flow' : ''} draft, run ${testRunTools} with representative args before reporting that it works. These tools prefer drafts, so testing does not require deployment.` @@ -1573,7 +1715,11 @@ const buildGlobalSystemPrompt = ( ` - Default to ${testRunTools} for any run request, an existing script included; they prefer drafts and need no deployment. Use run_script or run_flow only when the user names the deployed version ("the deployed X", "in production", "for real") — a bare "run X" is not that. For those two, read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema. ${testRunList}, run_script and run_flow all show the user an argument form prefilled with what you sent, so fill in every argument you can infer rather than asking for it in chat. test_run_step's form is the step's own inputs, not the flow's.` )}${when( - !canRunPreview, + !canRunPreview && canRunFlowPreview, + ` +- A request to run a flow goes to test_run_flow, which prefers the draft and needs no deployment. Use run_flow only when the user names the deployed version, and run_script for any script: those run the DEPLOYED item under this user's own permissions, so read it with read_workspace_item version: "deployed" first so the arguments match the deployed schema. Each shows the user an argument form prefilled with what you sent, so fill in every argument you can infer rather than asking for it in chat.` + )}${when( + !canRunPreview && !canRunFlowPreview, ` - run_script and run_flow are how you run anything here: they run the DEPLOYED item under this user's own permissions, and show them an argument form prefilled with what you sent. Read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema, and fill in every argument you can infer rather than asking for it in chat.` )}` @@ -1613,24 +1759,22 @@ ${ }.` )}` }` - const paths = `${when( - canWriteAnyDraft, - ` - -Path conventions: -- A workspace path starts with one of two namespaces; its trailing <name> may itself contain "/", so a path has three or more segments: - - \`u/${username}/<name>\` — your personal scope. Default for ad-hoc, exploratory, or scratch work. - - \`f/<folder>/<name>\` — a shared folder scope; the <folder> must already exist (a bare \`f/<name>\` with no folder segment is INVALID and will fail). -- If the user supplies a fully qualified \`f/<folder>/...\` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a \`u/${username}/...\` path unless a tool rejects it. -- Default a bare name with no namespace prefix (e.g. "create a flow called myflow") to \`u/${username}/<name>\`. Never invent an \`f/<folder>/...\` path for a folder that does not exist${when( - canCreateFolder, - '; create one with `create_folder` only when the user explicitly asks for a new folder' - )}.${folderGuidanceBlock}` - )}${when( - canCreateFolder && !canWriteAnyDraft, - '\n- You can create a shared folder with `create_folder` when the user explicitly asks for one. You cannot create anything inside it here, so do not offer to.' - )}` - if (external) return buildExternalPrompt(username, paths, skills) + const runtimeVars = { username, folder_guidance: folderGuidanceBlock } + if (external) { + const profile = externalPromptProfile(access, runsDeployed) + return ( + renderPromptTemplate(EXTERNAL_PROMPT, profile.flags, { ...profile.vars, ...runtimeVars }) + + externalSkills(skills) + ) + } + const paths = renderPromptTemplate( + PATH_CONVENTIONS, + new Set([ + ...(canWriteAnyDraft ? ['can_write_any_draft'] : []), + ...(canCreateFolder ? ['can_create_folder'] : []) + ]), + runtimeVars + ) return `${intro}${paths} @@ -1686,9 +1830,9 @@ ${groupMembershipRule}- Listings and reads return only what this user can see: i - Hub scripts are prebuilt, vetted integrations for third-party services, hosted outside the workspace under \`hub/<version>/<app>/<name>\` paths. Check search_hub_scripts before hand-writing code against a third-party API, even when the user never mentions the hub; read a result with read_workspace_item type "script" and its hub path to get its code, language, and input schema. Use what you find in whichever way fits: reference the hub path directly from a flow module or app runnable when a script already does the job, copy it into a workspace draft and adapt it when it is close (note the source hub path in a comment at the top of the code), or take it as a worked example and write your own. A script that does not do what the user asked is still worth reading when it is the only example of that integration: pass its \`integration\` back to search_hub_scripts to list that integration's other scripts with their descriptions, or use the \`suggested_integrations\` a search hands back when it finds nothing. - Before writing your own code against an integration the hub covers, call get_hub_integration with its slug: it returns the resource type to take, its auth fields and the integration's most-used scripts, which beats inferring them from script bodies. Call it for the integration you are about to write against, whichever it is. A search marks an integration \`documented\` when the hub additionally holds provider knowledge checked against the live API — pagination, enums, error codes and gotchas — so read that closely where it appears rather than trusting your own memory of the API. - If you have a web search tool and the hub does not cover a third-party API, search for the vendor's own API documentation rather than writing its endpoints and auth from memory, and link the page you relied on. Reserve it for external APIs: search_docs answers questions about Windmill itself. -${when(canCreateResourceType, `- create_resource_type creates a resource type the workspace lacks. The user confirms the schema in the call itself, so that is where you propose it rather than asking first in chat.\n`)}${when(!canCreateResourceType, '- This user cannot create a resource type here, in chat or on the Resources page, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin, who can add it.\n')}${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}${instructionsRule} +${resourceTypeRule}${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}${instructionsRule} ${pipelineBullet}` - )}${when( + )}${when(!canWriteDraft && canDraftResources, `\n${resourceTypeRule.trimEnd()}`)}${when( canRunPreview && canWriteDraft, ` ${testDraftRule} @@ -7348,6 +7492,8 @@ export function prepareGlobalSystemMessage( access?: SessionAccess /** Render for an external MCP client rather than the Windmill chat. */ external?: boolean + /** For `external` with read-only `access`: whether deployed items may still be run. */ + runsDeployed?: boolean } ): ChatCompletionSystemMessageParam { const user = opts?.user ?? get(userStore) @@ -7367,7 +7513,8 @@ export function prepareGlobalSystemMessage( opts?.skills ?? [], opts?.mcpServers ?? [], opts?.access, - opts?.external ?? false + opts?.external ?? false, + opts?.runsDeployed ?? true ) if (instructions?.workspace?.trim()) { content = `${content}\n\nWORKSPACE INSTRUCTIONS (configured by a workspace admin, shared by everyone in this workspace — you cannot modify these):\n${instructions.workspace.trim()}` diff --git a/frontend/src/lib/components/copilot/chat/global/mcpSessionGen.test.ts b/frontend/src/lib/components/copilot/chat/global/mcpSessionGen.test.ts index c712a73109..17f6e910d7 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpSessionGen.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpSessionGen.test.ts @@ -12,13 +12,21 @@ import { describe, expect, it } from 'vitest' import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { join } from 'node:path' +import { createHash } from 'node:crypto' import { ALL_INSTRUCTION_SUBJECTS, + buildFolderGuidance, + EXTERNAL_PROMPT, + externalPromptProfile, getInstructions, globalToolsFor, prepareGlobalSystemMessage } from './core' -import type { ScriptLang } from '$lib/gen' +import { renderPromptTemplate } from './promptTemplate' +import type { AuthorLevel, ScriptLang } from '$lib/gen' +import { FULL_CAPABILITIES } from '$lib/roleCapabilities' +import { capabilitiesForRole } from './sessionAccess' +import { USE_MODE_ACCESS } from '../sessionCapabilities' import { BUILDER_FRAMEWORK_TEMPLATES, FRAMEWORK_TEMPLATES, @@ -161,9 +169,11 @@ function toolDefs() { const WRITABLE = '{{writable_folders}}' const READONLY = '{{readonly_folders}}' +type PromptOpts = Parameters<typeof prepareGlobalSystemMessage>[1] + function prompt( user: { is_admin: boolean; folders?: string[]; folders_read?: string[] }, - extra: Parameters<typeof prepareGlobalSystemMessage>[1] = {}, + extra: PromptOpts = {}, instructions?: { workspace?: string } ): string { const content = prepareGlobalSystemMessage(instructions, { @@ -182,6 +192,71 @@ function suffixOf(longer: string, base: string, what: string): string { return longer.slice(base.length) } +/** The `{{folder_guidance}}` the server puts in the template, once per folder situation, as + * `buildGlobalSystemPrompt` inserts it: with its leading newline. */ +function folderGuidance(canCreateFolder: boolean) { + const variant = (isAdmin: boolean, folders: string[], foldersRead = folders) => { + const text = buildFolderGuidance( + '{{username}}', + { isAdmin, folders, foldersRead }, + canCreateFolder, + true + ) + return (text ? `\n${text}` : '') + .replaceAll('`f/' + WRITABLE + '`', WRITABLE) + .replaceAll('`f/' + READONLY + '`', READONLY) + } + return { + admin: variant(true, [WRITABLE]), + admin_no_folders: variant(true, []), + member: variant(false, [WRITABLE]), + member_no_folders: variant(false, []), + member_readonly: variant(false, [WRITABLE], [WRITABLE, READONLY]), + member_no_folders_readonly: variant(false, [], [READONLY]) + } +} + +const LEVELS: AuthorLevel[] = ['none', 'compose', 'full'] +const bit = (b: boolean) => (b ? '1' : '0') + +/** Every access profile the server can resolve a caller to, keyed as `prompt_profile` in + * `ai_session_tools/instructions.rs` builds the key: the token's scope, then for a full token + * the caller's role as `caller_capabilities` and `check_deploy_rules` give it. */ +function profiles(): [key: string, extra: PromptOpts][] { + const out: [string, PromptOpts][] = [ + ['read_only', { access: USE_MODE_ACCESS, runsDeployed: false }], + ['read_run', { access: USE_MODE_ACCESS, runsDeployed: true }] + ] + for (const isAdmin of [true, false]) + for (const deploy of [true, false]) + for (const code of [true, false]) + for (const flows of LEVELS) + for (const apps of LEVELS) + for (const manage_schedules of [true, false]) + for (const manage_triggers of [true, false]) { + const caps = { + ...FULL_CAPABILITIES, + code, + flows, + apps, + manage_schedules, + manage_triggers + } + // Full flows or apps without code is refused at write. + if (!code && (flows === 'full' || apps === 'full')) continue + // An admin holds every capability, so only the full role is reachable. + if (isAdmin && JSON.stringify(caps) !== JSON.stringify(FULL_CAPABILITIES)) continue + const key = `full:${bit(isAdmin)}${bit(deploy)}:${bit(code)}:${flows}:${apps}:${bit(manage_schedules)}${bit(manage_triggers)}` + const access = capabilitiesForRole({ + isAdmin, + deployRulesPass: deploy, + capabilities: caps + }) + out.push([key, { access }]) + } + return out +} + function promptParts() { const member = prompt({ is_admin: false, folders: [WRITABLE] }) const skills = suffixOf( @@ -193,37 +268,25 @@ function promptParts() { 'the skills section' ) const skillLine = skills.split('\n').pop()! - // The folder guidance differs per workspace, so it is cut out of the prompt: the server - // puts it back for a single workspace, and serves it from `get_workspace_context` otherwise. - const withoutFolders = prompt({ is_admin: false }) - const variants = { - admin: prompt({ is_admin: true, folders: [WRITABLE] }), - admin_no_folders: prompt({ is_admin: true, folders: [] }), - member, - member_no_folders: prompt({ is_admin: false, folders: [] }), - member_readonly: prompt({ - is_admin: false, - folders: [WRITABLE], - folders_read: [WRITABLE, READONLY] - }), - member_no_folders_readonly: prompt({ is_admin: false, folders: [], folders_read: [READONLY] }) + const index: Record<string, { flags: string; vars: Record<string, string> }> = {} + // What each profile renders to before the server fills the runtime variables, so a Rust + // test can check its renderer against this one. + const renderedSha256: Record<string, string> = {} + for (const [key, extra] of profiles()) { + const { flags, vars } = externalPromptProfile(extra?.access, extra?.runsDeployed ?? true) + index[key] = { flags: [...flags].sort().join(' '), vars } + renderedSha256[key] = createHash('sha256') + .update(renderPromptTemplate(EXTERNAL_PROMPT, flags, vars)) + .digest('hex') } - let at: number | undefined - const folder_guidance = Object.fromEntries( - Object.entries(variants).map(([name, full]) => { - let i = 0 - while (full[i] === withoutFolders[i]) i++ - const rest = withoutFolders.slice(i) - if ((at !== undefined && at !== i) || !full.endsWith(rest)) { - throw new Error(`the folder guidance (${name}) is no longer one inserted block`) - } - at = i - return [name, full.slice(i, full.length - rest.length)] - }) - ) return { - base: withoutFolders.slice(0, at) + '{{folder_guidance}}' + withoutFolders.slice(at), - folder_guidance, + template: EXTERNAL_PROMPT, + profiles: index, + folder_guidance: { + create_folder: folderGuidance(true), + no_create_folder: folderGuidance(false) + }, + rendered_sha256: renderedSha256, skills_header: skills.slice(0, skills.length - skillLine.length), skill_line: skillLine, workspace_instructions: suffixOf( @@ -333,4 +396,40 @@ describe('MCP session server generated definitions', () => { expect(readFileSync(join(OUT_DIR, name), 'utf8'), name).toBe(content) } }) + + // A capability that changes the prompt but is missing from the profile key would serve every + // role the prompt of whatever value `profiles()` fixed it at. + it('key every role capability that changes the prompt', () => { + const keyed = ['code', 'flows', 'apps', 'manage_schedules', 'manage_triggers'] + const render = (capabilities: typeof FULL_CAPABILITIES) => { + const access = capabilitiesForRole({ isAdmin: false, deployRulesPass: true, capabilities }) + const { flags, vars } = externalPromptProfile(access, true) + return renderPromptTemplate(EXTERNAL_PROMPT, flags, vars) + } + const roles = [ + FULL_CAPABILITIES, + { + ...FULL_CAPABILITIES, + code: false, + flows: 'compose' as AuthorLevel, + apps: 'none' as AuthorLevel + } + ] + for (const role of roles) + for (const [field, value] of Object.entries(role)) { + if (keyed.includes(field)) continue + const others = + typeof value === 'boolean' + ? [!value] + : typeof value === 'string' + ? LEVELS.filter((l) => l !== value) + : [Object.fromEntries(Object.keys(value).map((k) => [k, false]))] + for (const other of others) { + expect( + render({ ...role, [field]: other }), + `role capability "${field}" changes the MCP prompt: add it to the profile key in profiles() and prompt_profile (instructions.rs)` + ).toBe(render(role)) + } + } + }) }) diff --git a/frontend/src/lib/components/copilot/chat/global/promptTemplate.ts b/frontend/src/lib/components/copilot/chat/global/promptTemplate.ts new file mode 100644 index 0000000000..f8d08ee812 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/global/promptTemplate.ts @@ -0,0 +1,31 @@ +// The MCP server renders the same templates in Rust (`ai_session_tools/instructions.rs`, +// `render_template`); `mcpSessionGen.test.ts` hashes every profile's render so the two cannot +// drift. Keep the grammar to what both implement: `{{#flag}}…{{/flag}}` keeps its body when +// the flag is set, `{{^flag}}…{{/flag}}` when it is not, `{{name}}` takes a variable, and a +// variable not given stays as written for a later pass to fill. +const TAG = /\{\{([#^/]?)([a-z_]+)\}\}/g + +export function renderPromptTemplate( + template: string, + flags: ReadonlySet<string>, + vars: Readonly<Record<string, string>> +): string { + let out = '' + let last = 0 + const open: { name: string; keep: boolean }[] = [] + const keeping = () => open.every((s) => s.keep) + for (const m of template.matchAll(TAG)) { + const [tag, kind, name] = m + if (keeping()) out += template.slice(last, m.index) + last = m.index + tag.length + if (kind === '#' || kind === '^') { + open.push({ name, keep: flags.has(name) === (kind === '#') }) + } else if (kind === '/') { + if (open.pop()?.name !== name) throw new Error(`unbalanced {{/${name}}} in prompt template`) + } else if (keeping()) { + out += Object.hasOwn(vars, name) ? vars[name] : tag + } + } + if (open.length) throw new Error(`unclosed {{#${open[0].name}}} in prompt template`) + return out + template.slice(last) +} diff --git a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts index 6c58900eab..4bb66f11b4 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts @@ -111,7 +111,8 @@ export function capabilitiesForRole(role: { /** Whether `rulesets` make a session read-only. `DisableDirectDeployment` holds everyone, admins * and bypassers included, since production changes go through its dev workspace or a fork; * `RestrictDeployToDeployers` alone leaves its users their drafts. Unreadable rules protect too: - * the server holds deploys to the rule but not drafts. */ + * the server holds deploys to the rule but not drafts. The MCP server applies the same rule + * (`workspace_access` in `backend/windmill-api/src/mcp/core.rs`): change both. */ function protects(rulesets: ProtectionRuleset[] | undefined): boolean { return !rulesets || isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment') } From 2ce5a3a603746c65b8d3bf368e4a56d99fa4bdcd Mon Sep 17 00:00:00 2001 From: hugocasa <hugo@casademont.ch> Date: Tue, 3 Nov 2026 17:18:57 +0100 Subject: [PATCH 12/14] fix: keep a resource whose whole value is a variable reference (#12171) * fix: keep a resource whose whole value is a variable reference Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: open a referenced resource in the form's workspace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: say the variable's content is parsed as JSON in the menu Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep the JSON editor while a reference is typed into it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show the reference as text and reload the picker after creating a variable Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: pick the whole-value variable with the shared variable picker Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: pick another variable from the reference's own button only Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../src/lib/components/ApiConnectForm.svelte | 220 +++++++++++------- .../src/lib/components/ResourceForm.svelte | 189 +++++++++------ .../components/ResourceValueReference.svelte | 110 +++++++++ 3 files changed, 361 insertions(+), 158 deletions(-) create mode 100644 frontend/src/lib/components/ResourceValueReference.svelte diff --git a/frontend/src/lib/components/ApiConnectForm.svelte b/frontend/src/lib/components/ApiConnectForm.svelte index 37342912c7..5771e73910 100644 --- a/frontend/src/lib/components/ApiConnectForm.svelte +++ b/frontend/src/lib/components/ApiConnectForm.svelte @@ -20,6 +20,12 @@ import SyncResourceTypes from './SyncResourceTypes.svelte' import { parsePostgresConnectionString } from '$lib/utils/postgresConnectionString' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import DropdownV2 from './DropdownV2.svelte' + import ResourceValueReference, { + canReferenceWholeValue, + resourceValueMenuItems, + resourceValueReference + } from './ResourceValueReference.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -72,6 +78,7 @@ if (!resourceTypeInfo) return rawCode = '{}' viewJsonSchema = false + referencePinned = false try { schema = resourceTypeInfo.schema as any // A resource type may declare no properties at all — `dbt_profile` is a @@ -111,6 +118,23 @@ } } + let reference = $derived(resourceValueReference(args)) + // Pinned only by the picker: text typed into the JSON editor that parses to a reference keeps + // that editor, while any other form would replace the string with its own fields. + let referencePinned = $state(false) + let showReference = $derived( + !!reference && (referencePinned || !(notFound || viewJsonSchema || !schema?.properties)) + ) + let valueReference: ResourceValueReference | undefined = $state(undefined) + + function setWholeValue(v: Record<string, any> | string) { + referencePinned = typeof v === 'string' + // The "As JSON" toggle holds its own state and remounts unchecked with the form. + viewJsonSchema = false + rawCode = JSON.stringify(v, null, 2) + args = v + } + let connectionString = $state('') let validConnectionString = $state(true) function parseConnectionString(close: (_: any) => void) { @@ -171,101 +195,113 @@ {#if !notFound} <div class="w-full flex gap-2 flex-row-reverse items-center"> - <Toggle - on:change={(e) => switchTab(e.detail)} - options={{ - right: 'As JSON' - }} - class="as-json-toggle" - /> - <ResourceGen - bind:args - {resourceType} - resourceSchema={notFound ? undefined : schema} - isFileset={resourceTypeInfo?.is_fileset ?? false} - /> - <TestConnection {resourceType} {args} /> - {#if aiProvider} - <TestAiKey - {aiProvider} - workspace={workspace ?? $operatingWorkspace} - resourceValue={args} - model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model} + {#if showReference || canReferenceWholeValue(resourceTypeInfo)} + <DropdownV2 + placement="bottom-end" + items={() => + resourceValueMenuItems(showReference ? reference : undefined, { + pickVariable: () => valueReference?.pickVariable(), + editFields: () => setWholeValue({}) + })} /> {/if} - {#if resourceType == 'postgresql'} - <Popover - floatingConfig={{ - placement: 'bottom' + {#if !showReference} + <Toggle + on:change={(e) => switchTab(e.detail)} + options={{ + right: 'As JSON' }} - > - {#snippet trigger()} - <Button spacingSize="sm" size="xs" unifiedSize="md" variant="default" nonCaptureEvent> - From connection string - </Button> - {/snippet} - {#snippet content({ close })} - <div class="block text-primary p-4"> - <div class="w-[550px] flex flex-col items-start gap-1"> - <div class="flex flex-row gap-1 w-full"> - <input - type="text" - bind:value={connectionString} - placeholder="postgres://user:password@host:5432/dbname?sslmode=disable" - /> - <Button - size="xs" - color="blue" - buttonType="button" - on:click={() => { - parseConnectionString(close) - }} - disabled={connectionString.length <= 0} - > - Apply - </Button> + class="as-json-toggle" + /> + <ResourceGen + bind:args + {resourceType} + resourceSchema={notFound ? undefined : schema} + isFileset={resourceTypeInfo?.is_fileset ?? false} + /> + <TestConnection {resourceType} {args} /> + {#if aiProvider} + <TestAiKey + {aiProvider} + workspace={workspace ?? $operatingWorkspace} + resourceValue={args} + model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model} + /> + {/if} + {#if resourceType == 'postgresql'} + <Popover + floatingConfig={{ + placement: 'bottom' + }} + > + {#snippet trigger()} + <Button spacingSize="sm" size="xs" unifiedSize="md" variant="default" nonCaptureEvent> + From connection string + </Button> + {/snippet} + {#snippet content({ close })} + <div class="block text-primary p-4"> + <div class="w-[550px] flex flex-col items-start gap-1"> + <div class="flex flex-row gap-1 w-full"> + <input + type="text" + bind:value={connectionString} + placeholder="postgres://user:password@host:5432/dbname?sslmode=disable" + /> + <Button + size="xs" + color="blue" + buttonType="button" + on:click={() => { + parseConnectionString(close) + }} + disabled={connectionString.length <= 0} + > + Apply + </Button> + </div> + {#if !validConnectionString} + <p class="text-red-500 text-xs">Could not parse connection string</p> + {/if} </div> - {#if !validConnectionString} - <p class="text-red-500 text-xs">Could not parse connection string</p> - {/if} </div> - </div> - {/snippet} - </Popover> - {/if} - {#if resourceType == 'postgresql' && supabaseWizard} - <!-- Imported here rather than at the top so the wizard's Supabase graph stays out of + {/snippet} + </Popover> + {/if} + {#if resourceType == 'postgresql' && supabaseWizard} + <!-- Imported here rather than at the top so the wizard's Supabase graph stays out of this form's chunk, which loads on the resources page and in every resource drawer. --> - {#await import('./workspaceSettings/SupabaseResourceConnect.svelte')} - <Loader2 class="animate-spin" /> - {:then Module} - <Module.default onPicked={applySupabasePick} /> - {/await} - {/if} - <GitHubAppIntegration - {resourceType} - {args} - {description} - onArgsUpdate={(newArgs) => { - args = newArgs - rawCode = JSON.stringify(args, null, 2) - rawCodeEditor?.setCode(rawCode) - }} - onDescriptionUpdate={(newDescription) => (description = newDescription)} - /> - <!-- Last in a `flex-row-reverse` row, so it lands beside the GitHub App + {#await import('./workspaceSettings/SupabaseResourceConnect.svelte')} + <Loader2 class="animate-spin" /> + {:then Module} + <Module.default onPicked={applySupabasePick} /> + {/await} + {/if} + <GitHubAppIntegration + {resourceType} + {args} + {description} + onArgsUpdate={(newArgs) => { + args = newArgs + rawCode = JSON.stringify(args, null, 2) + rawCodeEditor?.setCode(rawCode) + }} + onDescriptionUpdate={(newDescription) => (description = newDescription)} + /> + <!-- Last in a `flex-row-reverse` row, so it lands beside the GitHub App button without splitting it from its own refresh control. --> - <GitLabIntegration - {resourceType} - {args} - {workspace} - {onCredentialStored} - onArgsUpdate={(newArgs) => { - args = newArgs - rawCode = JSON.stringify(args, null, 2) - rawCodeEditor?.setCode(rawCode) - }} - /> + <GitLabIntegration + {resourceType} + {args} + {workspace} + {onCredentialStored} + onArgsUpdate={(newArgs) => { + args = newArgs + rawCode = JSON.stringify(args, null, 2) + rawCodeEditor?.setCode(rawCode) + }} + /> + {/if} </div> {#if resourceType?.includes('bedrock') && !isCloudHosted()} <BedrockCredentialsCheck /> @@ -277,7 +313,13 @@ > <SyncResourceTypes {resourceType} {onSynced} /> {/if} -{#if notFound || viewJsonSchema || !schema?.properties} +<ResourceValueReference + bind:this={valueReference} + reference={showReference ? reference : undefined} + workspace={workspace ?? $operatingWorkspace} + onPick={setWholeValue} +/> +{#if showReference}{:else if notFound || viewJsonSchema || !schema?.properties} {#if !emptyString(error)}<span class="text-red-400 text-xs mb-1 flex flex-row-reverse" >{error}</span >{:else}<div class="py-2"></div>{/if} diff --git a/frontend/src/lib/components/ResourceForm.svelte b/frontend/src/lib/components/ResourceForm.svelte index 0a6e3edfc5..c2404df0c0 100644 --- a/frontend/src/lib/components/ResourceForm.svelte +++ b/frontend/src/lib/components/ResourceForm.svelte @@ -2,7 +2,7 @@ import ResourceDescriptionField from './ResourceDescriptionField.svelte' import type { Schema } from '$lib/common' import type { Resource, ResourceType } from '$lib/gen' - import { onDestroy } from 'svelte' + import { onDestroy, untrack } from 'svelte' import { setEditorUnparseable } from './pendingEditorFlush' import { emptyString, isOwner, urlize } from '$lib/utils' import { Alert, Skeleton } from './common' @@ -26,6 +26,12 @@ import Label from './Label.svelte' import ResourcePathHint from './ResourcePathHint.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import DropdownV2 from './DropdownV2.svelte' + import ResourceValueReference, { + canReferenceWholeValue, + resourceValueMenuItems, + resourceValueReference + } from './ResourceValueReference.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -93,6 +99,30 @@ let rawCode: string | undefined = $state(undefined) let textFileContent: string = $state('') + let reference = $derived(resourceValueReference(args)) + let rawMode = $derived( + viewJsonSchema || + (!resourceTypeInfo?.is_fileset && !(resourceSchema && resourceSchema.properties)) + ) + // Pinned when the value arrives as a reference (loaded or picked), not when the JSON editor's + // text parses to one: that editor stays mounted while it is being typed into. Any other form + // would replace the string with its own fields, so it never renders over a reference. + let referencePinned = $state(untrack(() => !!resourceValueReference(args))) + let showReference = $derived(!!reference && (referencePinned || !rawMode)) + let valueReference: ResourceValueReference | undefined = $state(undefined) + + function setWholeValue(v: Record<string, any> | string) { + args = v as Record<string, any> + referencePinned = typeof v === 'string' + jsonError = '' + // Reseeded from the new value by the effect below once the raw editor is the input again. + rawCode = undefined + } + + $effect(() => { + if (showReference) isValid = true + }) + // This field is a bare SimpleEditor parsed here, so it never passes through JsonEditor — // it has to register itself, or a caller persisting what is on screen would save the // last value that parsed and leave without the text in front of the user. @@ -115,11 +145,7 @@ // The raw JSON editor is the active input whenever the "As JSON" toggle is on, // or no schema-based form can be rendered (e.g. the resource type is missing // from the workspace). In both cases rawCode must be seeded from args. - let usesRawEditor = $derived( - !loadingSchema && - (viewJsonSchema || - (!resourceTypeInfo?.is_fileset && !(resourceSchema && resourceSchema.properties))) - ) + let usesRawEditor = $derived(!loadingSchema && !showReference && rawMode) $effect(() => { if (rawCode !== undefined) parseJson() @@ -142,7 +168,13 @@ // Seed the JSON editor when the resource type schema is missing // (restores the old ResourceEditor's catch-block behavior) $effect(() => { - if (resource_type && !loadingSchema && !resourceSchema && rawCode === undefined) { + if ( + resource_type && + !loadingSchema && + !resourceSchema && + !showReference && + rawCode === undefined + ) { rawCode = JSON.stringify(args, null, 2) } }) @@ -200,79 +232,98 @@ <div class="flex flex-col gap-1"> <div class="w-full flex gap-4 flex-row-reverse items-center"> - <Toggle - bind:checked={viewJsonSchema} - on:change={(e) => { - if (e.detail) { - rawCode = JSON.stringify(args, null, 2) - } else if (resourceTypeInfo?.format_extension && !resourceTypeInfo?.is_fileset) { - textFileContent = args?.content ?? '' - } - }} - options={{ - right: 'As JSON' - }} - /> - <ResourceGen - bind:args - resourceType={resource_type} - resourceName={path} - resourceDescription={description} - {resourceSchema} - /> - {#if resourceToEdit?.resource_type === 'nats' || resourceToEdit?.resource_type === 'kafka'} - <TestTriggerConnection kind={resourceToEdit?.resource_type} args={{ connection: args }} /> - {:else} - <TestConnection - resourceType={resourceToEdit?.resource_type} - {args} - workspaceOverride={workspace} + {#if can_write && (showReference || canReferenceWholeValue(resourceTypeInfo))} + <DropdownV2 + placement="bottom-end" + items={() => + resourceValueMenuItems(showReference ? reference : undefined, { + pickVariable: () => valueReference?.pickVariable(), + editFields: () => setWholeValue({}) + })} /> {/if} - {#if aiProvider} - <TestAiKey - {aiProvider} - workspace={ws} - resourceValue={args} - model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model} - /> - {/if} - {#if resource_type === 'git_repository' && ws && (actingUser?.is_admin || actingUser?.is_super_admin)} - <GitHubAppIntegration - resourceType={resource_type} - {args} - {description} - onArgsUpdate={(newArgs) => { - args = newArgs - // The raw editor is also what a workspace missing the resource type - // gets, and it holds its own copy of the value: without this the - // picker fills in a URL nothing on screen ever shows. - if (viewJsonSchema || !resourceSchema) { + {#if !showReference} + <Toggle + bind:checked={viewJsonSchema} + on:change={(e) => { + if (e.detail) { rawCode = JSON.stringify(args, null, 2) + } else if (resourceTypeInfo?.format_extension && !resourceTypeInfo?.is_fileset) { + textFileContent = args?.content ?? '' } }} - onDescriptionUpdate={(newDescription) => (description = newDescription)} - /> - <GitLabIntegration - resourceType={resource_type} - {args} - workspace={ws} - {onCredentialStored} - onArgsUpdate={(newArgs) => { - args = newArgs - // The raw editor is also what a workspace missing the resource type - // gets, and it holds its own copy of the value: without this the - // picker fills in a URL nothing on screen ever shows. - if (viewJsonSchema || !resourceSchema) { - rawCode = JSON.stringify(args, null, 2) - } + options={{ + right: 'As JSON' }} /> + <ResourceGen + bind:args + resourceType={resource_type} + resourceName={path} + resourceDescription={description} + {resourceSchema} + /> + {#if resourceToEdit?.resource_type === 'nats' || resourceToEdit?.resource_type === 'kafka'} + <TestTriggerConnection kind={resourceToEdit?.resource_type} args={{ connection: args }} /> + {:else} + <TestConnection + resourceType={resourceToEdit?.resource_type} + {args} + workspaceOverride={workspace} + /> + {/if} + {#if aiProvider} + <TestAiKey + {aiProvider} + workspace={ws} + resourceValue={args} + model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model} + /> + {/if} + {#if resource_type === 'git_repository' && ws && (actingUser?.is_admin || actingUser?.is_super_admin)} + <GitHubAppIntegration + resourceType={resource_type} + {args} + {description} + onArgsUpdate={(newArgs) => { + args = newArgs + // The raw editor is also what a workspace missing the resource type + // gets, and it holds its own copy of the value: without this the + // picker fills in a URL nothing on screen ever shows. + if (viewJsonSchema || !resourceSchema) { + rawCode = JSON.stringify(args, null, 2) + } + }} + onDescriptionUpdate={(newDescription) => (description = newDescription)} + /> + <GitLabIntegration + resourceType={resource_type} + {args} + workspace={ws} + {onCredentialStored} + onArgsUpdate={(newArgs) => { + args = newArgs + // The raw editor is also what a workspace missing the resource type + // gets, and it holds its own copy of the value: without this the + // picker fills in a URL nothing on screen ever shows. + if (viewJsonSchema || !resourceSchema) { + rawCode = JSON.stringify(args, null, 2) + } + }} + /> + {/if} {/if} </div> <div> - {#if loadingSchema} + <ResourceValueReference + bind:this={valueReference} + reference={showReference ? reference : undefined} + disabled={!can_write} + workspace={ws} + onPick={setWholeValue} + /> + {#if showReference}{:else if loadingSchema} <Skeleton layout={[[4]]} /> {:else if !viewJsonSchema && resourceTypeInfo?.is_fileset} <div class="mt-1 flex items-center gap-2"> diff --git a/frontend/src/lib/components/ResourceValueReference.svelte b/frontend/src/lib/components/ResourceValueReference.svelte new file mode 100644 index 0000000000..198f0cad99 --- /dev/null +++ b/frontend/src/lib/components/ResourceValueReference.svelte @@ -0,0 +1,110 @@ +<script module lang="ts"> + import type { Item } from '$lib/utils' + import type { ResourceType } from '$lib/gen' + + /** The whole value of a resource can be a single `$jsonvar:`/`$var:`/`$res:` string, resolved + * at runtime. No form may render over it: a schema form replaces it with empty fields. */ + export function resourceValueReference(value: unknown): string | undefined { + return typeof value === 'string' && + ['$jsonvar:', '$var:', '$res:'].some((p) => value.startsWith(p)) + ? value + : undefined + } + + /** A file-type resource is `{ content }` and a fileset a map of files: neither is a JSON + * document a variable could hold whole. */ + export function canReferenceWholeValue(resourceTypeInfo: ResourceType | undefined): boolean { + return !resourceTypeInfo?.format_extension && !resourceTypeInfo?.is_fileset + } + + export function resourceValueMenuItems( + reference: string | undefined, + actions: { pickVariable: () => void; editFields: () => void } + ): Item[] { + return reference + ? [{ displayName: 'Edit fields instead', action: actions.editFields }] + : [ + { + displayName: 'Whole value from a variable', + description: "The variable's content is parsed as JSON", + action: actions.pickVariable + } + ] + } +</script> + +<script lang="ts"> + import { DollarSign } from 'lucide-svelte' + import { Button } from './common' + import type VariableEditor from './VariableEditor.svelte' + import VariablePicker from './VariablePicker.svelte' + + interface Props { + /** The reference to show, `undefined` when the value is not one: the picker still mounts. */ + reference: string | undefined + disabled?: boolean + workspace: string | undefined + onPick: (reference: string) => void + } + + let { reference, disabled = false, workspace, onPick }: Props = $props() + + let picker: VariablePicker | undefined = $state(undefined) + let variableEditor: VariableEditor | undefined = $state(undefined) + + let referencedResource = $derived(reference?.startsWith('$res:') ? reference.slice(5) : undefined) + let referencedVariable = $derived( + reference && !referencedResource ? reference.slice(reference.indexOf(':') + 1) : undefined + ) + + export function pickVariable() { + picker?.openDrawer() + } +</script> + +{#if reference} + <div class="flex flex-col gap-1 w-full"> + <div class="flex items-center gap-2 h-8 pl-2 pr-0.5 rounded-md bg-surface-secondary"> + <span class="grow truncate text-xs font-mono text-emphasis">{reference}</span> + {#if !disabled} + <Button + iconOnly + startIcon={{ icon: DollarSign }} + unifiedSize="sm" + onClick={pickVariable} + variant="default" + btnClasses="bg-surface-tertiary" + title="Pick another variable" + /> + {/if} + </div> + <div class="text-2xs text-hint"> + {#if referencedResource} + Linked to resource <a + target="_blank" + href="/resources{workspace + ? `?workspace=${workspace}` + : ''}#/resource/{referencedResource}" + class="text-accent underline">{referencedResource}</a + > + {:else} + Linked to variable <button + class="text-accent underline font-normal" + onclick={() => variableEditor?.editVariable?.(referencedVariable ?? '')} + >{referencedVariable}</button + >. + {reference.startsWith('$jsonvar:') + ? 'Its content is parsed as JSON and used as the whole value.' + : 'Its content is used as the whole value.'} + {/if} + </div> + </div> +{/if} + +<VariablePicker + bind:this={picker} + bind:variableEditor + {workspace} + tooltip="The variable must hold the whole value as JSON. It is parsed when the resource is used." + onPick={(path) => onPick('$jsonvar:' + path)} +/> From d0d37e04a56d96eeff440317d09659d7d1132884 Mon Sep 17 00:00:00 2001 From: Guilhem <guilhemlemouel@gmail.com> Date: Tue, 3 Nov 2026 17:21:30 +0100 Subject: [PATCH 13/14] fix: keep the session chat usable on narrow screens (#12169) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../lib/components/common/alert/Alert.svelte | 2 +- .../copilot/chat/AIChatDisplay.svelte | 10 ++- .../copilot/chat/AutonomyModePicker.svelte | 15 +++- .../(root)/(logged)/sessions/+page.svelte | 82 +++++++++++++------ 4 files changed, 76 insertions(+), 33 deletions(-) diff --git a/frontend/src/lib/components/common/alert/Alert.svelte b/frontend/src/lib/components/common/alert/Alert.svelte index b7639e1104..17aeb08ced 100644 --- a/frontend/src/lib/components/common/alert/Alert.svelte +++ b/frontend/src/lib/components/common/alert/Alert.svelte @@ -90,7 +90,7 @@ /> </div> {/if} - <div class={twMerge(!hideIcon && 'ml-1', 'w-full')}> + <div class={twMerge(!hideIcon && 'ml-1', 'w-full min-w-0')}> {#if hasTitleRow} <div class={twMerge('w-full flex flex-row items-center justify-between')}> <span diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index 2407ced07f..683a089cd5 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -784,8 +784,10 @@ variant="accent" startIcon={{ icon: KeyRound }} href="/workspace_settings?tab=ai" + wrapperClasses="min-w-0 max-w-full" + btnClasses="min-w-0" > - Add your own API key + <span class="truncate">Add your own API key</span> </Button> </div> </Alert> @@ -794,7 +796,7 @@ {#snippet freeTierUsageBanner()} <div - class="my-1 flex items-center justify-between gap-2 rounded-md border bg-surface-secondary px-2 py-1" + class="my-1 flex flex-wrap items-center justify-between gap-x-2 gap-y-1 rounded-md border bg-surface-secondary px-2 py-1" > <span class="text-xs text-secondary tabular-nums"> {freeTierUsedPct}% of your free Windmill AI used @@ -804,8 +806,10 @@ variant="default" startIcon={{ icon: KeyRound }} href="/workspace_settings?tab=ai" + wrapperClasses="min-w-0 shrink" + btnClasses="min-w-0" > - Configure your API key + <span class="truncate">Configure your API key</span> </Button> </div> {/snippet} diff --git a/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte b/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte index e236e4a4c0..8f4d004803 100644 --- a/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte +++ b/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte @@ -88,7 +88,13 @@ } </script> -<DropdownV2 {items} placement="bottom-start" fixedHeight={false} customWidth={work ? 260 : 240}> +<DropdownV2 + {items} + placement="bottom-start" + fixedHeight={false} + customWidth={work ? 260 : 240} + class="min-w-0 max-w-full" +> {#snippet buttonReplacement()} <Button nonCaptureEvent @@ -97,14 +103,17 @@ title={workOption ? (work?.lock?.reason ?? `${workOption.description} ${option.tooltip(availability)}`) : option.tooltip(availability)} - btnClasses={workOption?.triggerClass ?? ''} + wrapperClasses="min-w-0 shrink" + btnClasses="min-w-0 {workOption?.triggerClass ?? ''}" startIcon={{ icon: (workOption ?? option).icon, classes: (workOption ?? option).iconColor }} endIcon={{ icon: ChevronDown }} > - {workOption ? `${workOption.label} · ${postureLabel}` : postureLabel} + <span class="truncate" + >{workOption ? `${workOption.label} · ${postureLabel}` : postureLabel}</span + > </Button> {/snippet} </DropdownV2> diff --git a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte index e2cb9a932b..f7debed13b 100644 --- a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte @@ -10,7 +10,7 @@ <script lang="ts"> import { onDestroy, onMount, untrack } from 'svelte' - import { SvelteSet } from 'svelte/reactivity' + import { MediaQuery, SvelteSet } from 'svelte/reactivity' import { page } from '$app/state' import { Plus, @@ -438,7 +438,19 @@ // pickers at once. let emptyStateNewTabOpen = $state(false) - let fullscreen = $state(false) + // Collapse the preview panel to give the chat the full width. Per-session and + // owned by the runtime's previewTabs (restored on switch, written back on + // toggle) so it survives session switches with the rest of the tab model. + const previewCollapsed = $derived(owner?.collapsed ?? false) + + let fullscreenToggled = $state(false) + // Below `sm` the row is too narrow for both panes: the chat's 25% minimum leaves it under + // 100px, where messages wrap a character per line. An open panel is full screen there. + const narrowScreen = new MediaQuery('(max-width: 639px)') + const fullscreen = $derived(fullscreenToggled || (narrowScreen.current && !previewCollapsed)) + // The band's last breadcrumb stage alone fills a phone's width, leaving the strip and controls + // no room there, so a narrow panel keeps them in its own card. + const bandFullscreen = $derived(fullscreen && !narrowScreen.current) // Going full screen is the preview panel expanding to the left: the chat column shrinks to // nothing and the panel takes its place. Animating that is what carries the switch, so the @@ -451,7 +463,7 @@ let panesAnimating = $state(false) let panesAnimationTimer: ReturnType<typeof setTimeout> | undefined = undefined function toggleFullscreen() { - fullscreen = !fullscreen + fullscreenToggled = !fullscreenToggled if (reducedMotion.val) return panesAnimating = true clearTimeout(panesAnimationTimer) @@ -494,10 +506,6 @@ $effect(() => { owner?.setFullscreen(fullscreen) }) - // Collapse the preview panel to give the chat the full width. Per-session and - // owned by the runtime's previewTabs (restored on switch, written back on - // toggle) so it survives session switches with the rest of the tab model. - const previewCollapsed = $derived(owner?.collapsed ?? false) // Collapse works by resizing the preview pane to zero, never unmounting it: // the pane hosts every warm session's preview tabs, and unmounting would @@ -974,12 +982,12 @@ so from then on the name comes from there, with its pen and its menu. --> <PageHeaderContent barRightInset={bandInset} - section={fullscreen + section={bandFullscreen ? { label: activeSession?.summary ?? 'Untitled session', noNavPicker: true } : undefined} - actions={fullscreen ? fullscreenBand : sessionPageActions} - actionsFill={fullscreen} - separator={fullscreen ? 'always' : 'none'} + actions={bandFullscreen ? fullscreenBand : sessionPageActions} + actionsFill={bandFullscreen} + separator={bandFullscreen ? 'always' : 'none'} /> {#snippet fullscreenBand()} @@ -1002,15 +1010,27 @@ {#if previewCollapsed && !fullscreen} <!-- Collapsed preview: the way back to the side panel, in the band with the session's own controls rather than floating over the chat. --> - <Button - variant="subtle" - unifiedSize="sm" - startIcon={{ icon: PanelRightOpen }} - title="Open side panel" - onclick={() => owner?.setCollapsed(false)} - > - Open side panel - </Button> + <span class="sm:hidden"> + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + startIcon={{ icon: PanelRightOpen }} + title="Open side panel" + onclick={() => owner?.setCollapsed(false)} + /> + </span> + <span class="hidden sm:inline-flex"> + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: PanelRightOpen }} + title="Open side panel" + onclick={() => owner?.setCollapsed(false)} + > + Open side panel + </Button> + </span> {/if} {/snippet} @@ -1129,7 +1149,11 @@ panelShare = w / contentWidth } } - class="flex-1 min-h-0 flex flex-col {fullscreen ? `p-0 ${BAR_TOP_PAD}` : 'p-2 pl-0'}" + class="flex-1 min-h-0 flex flex-col {bandFullscreen + ? `p-0 ${BAR_TOP_PAD}` + : fullscreen + ? `px-2 pb-2 ${BAR_TOP_PAD}` + : 'p-2 pl-0'}" > <!-- The action controls float over the tab strip, so the strip has to reserve their width or tabs slide underneath them. Measured rather than guessed: @@ -1137,17 +1161,21 @@ page has no View|Edit toggle), so a fixed padding is either short for the widest case or wasted space for the narrowest. --> <div - class="flex flex-col flex-1 min-h-0 overflow-hidden relative bg-surface {fullscreen + class="flex flex-col flex-1 min-h-0 overflow-hidden relative bg-surface {bandFullscreen ? '' : 'rounded-md border border-light'}" style="--preview-actions-w: {previewActionsWidth + 8}px" > - {#if !fullscreen} + {#if !bandFullscreen} <!-- Collapse the preview panel — floats over the top-left corner so the tab strip keeps the full width. --> <button type="button" - onclick={() => owner?.setCollapsed(true)} + onclick={() => { + // Full screen toggled on a wide window outlives a narrowing one. + fullscreenToggled = false + owner?.setCollapsed(true) + }} title="Collapse preview" aria-label="Collapse preview" class="absolute top-1 left-1 z-30 inline-flex items-center justify-center w-6 h-6 rounded text-tertiary hover:text-primary hover:bg-surface-hover" @@ -1159,7 +1187,7 @@ <!-- In full screen the strip and these controls move into the page header band, which is empty there and has the width for them; the pane below keeps only the content. --> - {#if !fullscreen} + {#if !bandFullscreen} <!-- Open-in-full-page + full-screen toggle, floating over the top-right corner to mirror the collapse control. Its width is measured so the strip can reserve room and its tabs never scroll underneath. --> @@ -1291,7 +1319,9 @@ <ExternalLink size={14} /> </a> {/if} - {#if fullscreen} + {#if narrowScreen.current} + <!-- Full screen is automatic there; the card's collapse button leads back to the chat. --> + {:else if fullscreen} <!-- Named rather than an icon alone: full screen hid the chat, and what the user wants back is the chat, not a window size. The band has the room for the word. --> <button From 766825ed478b853d02ae8b460dd0ac5e2bab07fe Mon Sep 17 00:00:00 2001 From: Guilhem <guilhemlemouel@gmail.com> Date: Tue, 3 Nov 2026 17:41:09 +0100 Subject: [PATCH 14/14] feat: show what a member, group or service account can access (#12142) * feat: show what a member, group or service account can access Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: point the EE ref at the access view usage counters Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: name groups in the access view's permission error Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: map /access to the acls scope and list each group once A token with scopes was refused before reaching the access endpoint, and a member in a workspace group and an instance group of the same name got that group twice, which broke the drawer's keyed list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: count every registered feature usage action Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: read the operating workspace and user in the access view GroupEditorDrawer is reachable from a session editor, where the navigation workspace and user are the parent's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: cover a member reading their group's access Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: size the groups page loading rows like the loaded ones Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: open a group's access from the groups page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show access as a folder tree with links to each item Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show a group's access to superadmins who are not workspace admins Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: accept instance groups as access view principals Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to c4e610999ca0d1abab06b1660cc48e486ab870b3 This commit updates the EE repository reference after PR #939 was merged in windmill-ee-private. Previous ee-repo-ref: da6bb1965702eb57237882e5fda6179f72294a06 New ee-repo-ref: c4e610999ca0d1abab06b1660cc48e486ab870b3 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> --- ...afb8df34fb94b89e86e6216677202c6bb3011.json | 29 ++ ...4880fffdb7b2b91b678a6c315070d6fad7b41.json | 30 ++ ...8343102bb0a0195038d7fdac1e80dd45bf604.json | 23 + backend/ee-repo-ref.txt | 2 +- backend/tests/access_view.rs | 66 +++ backend/windmill-api-groups/src/access.rs | 319 ++++++++++++++ backend/windmill-api-groups/src/lib.rs | 1 + backend/windmill-api/openapi.yaml | 85 ++++ backend/windmill-api/src/lib.rs | 1 + backend/windmill-common/src/scopes.rs | 3 +- docs/feature-telemetry.md | 6 +- .../src/lib/components/AccessDrawer.svelte | 409 ++++++++++++++++++ .../lib/components/GroupEditorDrawer.svelte | 19 +- .../lib/components/access/accessTree.test.ts | 37 ++ .../src/lib/components/access/accessTree.ts | 149 +++++++ .../settings/WorkspaceUserSettings.svelte | 176 ++++---- .../components/sidebar/SettingsMenu.svelte | 18 +- .../(root)/(logged)/folders/+page.svelte | 15 + .../(root)/(logged)/groups/+page.svelte | 25 +- 19 files changed, 1319 insertions(+), 94 deletions(-) create mode 100644 backend/.sqlx/query-4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011.json create mode 100644 backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json create mode 100644 backend/.sqlx/query-fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604.json create mode 100644 backend/tests/access_view.rs create mode 100644 backend/windmill-api-groups/src/access.rs create mode 100644 frontend/src/lib/components/AccessDrawer.svelte create mode 100644 frontend/src/lib/components/access/accessTree.test.ts create mode 100644 frontend/src/lib/components/access/accessTree.ts diff --git a/backend/.sqlx/query-4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011.json b/backend/.sqlx/query-4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011.json new file mode 100644 index 0000000000..88ab46d60b --- /dev/null +++ b/backend/.sqlx/query-4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "disabled", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011" +} diff --git a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json b/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json new file mode 100644 index 0000000000..b517bb1790 --- /dev/null +++ b/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "via!", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41" +} diff --git a/backend/.sqlx/query-fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604.json b/backend/.sqlx/query-fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604.json new file mode 100644 index 0000000000..ff34d0b0fb --- /dev/null +++ b/backend/.sqlx/query-fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2)\n OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index add89eebfd..7aa161da8a 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -a9a0f4f5073d0f774fb7bd7f87b6e37e8d5356b4 +c4e610999ca0d1abab06b1660cc48e486ab870b3 diff --git a/backend/tests/access_view.rs b/backend/tests/access_view.rs new file mode 100644 index 0000000000..e3edf95494 --- /dev/null +++ b/backend/tests/access_view.rs @@ -0,0 +1,66 @@ +//! Another member's access lists paths the caller may not be able to read, so only a workspace +//! admin may ask for it. + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_member_cannot_read_another_members_access(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/w/test-workspace/access/get", + server.addr.port() + ); + let client = reqwest::Client::new(); + + sqlx::raw_sql( + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('test-workspace', 'ops', '', '{}'); + INSERT INTO usr_to_group (workspace_id, usr, group_) VALUES ('test-workspace', 'test-user-2', 'ops'); + INSERT INTO instance_group (name) VALUES ('sre'); + INSERT INTO email_to_igroup (email, igroup) VALUES ('test2@windmill.dev', 'sre')", + ) + .execute(&db) + .await?; + + // A member may read their own access and their groups', instance groups included, nobody + // else's. + for (principal, status) in [ + ("u/test-user", 403), + ("g/all", 403), + ("u/test-user-2", 200), + ("g/ops", 200), + ("g/sre", 200), + ] { + let resp = client + .get(&url) + .query(&[("principal", principal)]) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .send() + .await?; + assert_eq!(resp.status(), status, "{principal}: {}", resp.text().await?); + } + + // A scoped token reaches the route only if `/access` maps to a scope domain. + let scoped = client + .post(format!( + "http://localhost:{}/api/users/tokens/create", + server.addr.port() + )) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&serde_json::json!({ "label": "scoped", "scopes": ["acls:read"], "workspace_id": "test-workspace" })) + .send() + .await? + .text() + .await?; + let resp = client + .get(&url) + .query(&[("principal", "u/test-user-2")]) + .header("Authorization", format!("Bearer {scoped}")) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + Ok(()) +} diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs new file mode 100644 index 0000000000..6fa159c008 --- /dev/null +++ b/backend/windmill-api-groups/src/access.rs @@ -0,0 +1,319 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2026 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! What a workspace member or group can reach, and why. + +use axum::{ + extract::{Extension, Path, Query}, + routing::get, + Json, Router, +}; +use serde::{Deserialize, Serialize}; +use windmill_api_auth::ApiAuthed; +use windmill_common::{ + auth::fetch_authed_from_permissioned_as, + db::UserDB, + error::{Error, JsonResult}, + DB, +}; + +pub fn workspaced_service() -> Router { + Router::new().route("/get", get(get_access)) +} + +/// `(kind, table, extra filter)`. Captures, capture configs and eval datasets are left out on +/// purpose: they are test data attached to an item, not something access is granted to. +const ITEM_TABLES: [(&str, &str, &str); 17] = [ + ( + "script", + "script", + "AND archived = false AND deleted = false", + ), + ("flow", "flow", "AND archived = false"), + ("app", "app", ""), + ("resource", "resource", ""), + ("variable", "variable", ""), + ("schedule", "schedule", ""), + ("http_trigger", "http_trigger", ""), + ("websocket_trigger", "websocket_trigger", ""), + ("kafka_trigger", "kafka_trigger", ""), + ("nats_trigger", "nats_trigger", ""), + ("postgres_trigger", "postgres_trigger", ""), + ("mqtt_trigger", "mqtt_trigger", ""), + ("amqp_trigger", "amqp_trigger", ""), + ("gcp_trigger", "gcp_trigger", ""), + ("azure_trigger", "azure_trigger", ""), + ("sqs_trigger", "sqs_trigger", ""), + ("email_trigger", "email_trigger", ""), +]; + +#[derive(Deserialize)] +struct AccessQuery { + /// `u/<username>` or `g/<group>`. + principal: String, +} + +#[derive(Serialize)] +struct AccessReport { + principal: String, + is_admin: bool, + groups: Vec<String>, + folders: Vec<FolderAccess>, + items: Vec<ItemAccess>, +} + +#[derive(Serialize)] +struct FolderAccess { + name: String, + write: bool, + owner: bool, + /// The `extra_perms` keys (`u/<user>` or `g/<group>`) that grant the folder. + via: Vec<String>, +} + +#[derive(Serialize)] +struct ItemAccess { + kind: String, + path: String, + write: bool, + reasons: Vec<Reason>, +} + +#[derive(Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum Reason { + /// Under the principal's own `u/<user>/` path. + Own, + /// Under `g/<group>/` for a group the principal is in. + GroupPath { group: String }, + /// Shared with the principal directly. + User { write: bool }, + /// Shared with one of the principal's groups. + Group { group: String, write: bool }, + /// In a folder the principal can read. + Folder { folder: String, write: bool }, +} + +#[derive(sqlx::FromRow)] +struct ItemRow { + kind: String, + path: String, + own: bool, + path_group: Option<String>, + user_grant: Option<bool>, + group_read: Vec<String>, + group_write: Vec<String>, + folder: Option<String>, + folder_write: bool, +} + +fn items_query() -> String { + let union = ITEM_TABLES + .iter() + .map(|(kind, table, filter)| { + format!( + "SELECT '{kind}'::text AS kind, path::text AS path, extra_perms FROM {table} \ + WHERE workspace_id = $1 {filter}" + ) + }) + .collect::<Vec<_>>() + .join(" UNION ALL "); + // Rows come back through the principal's RLS session, so the set is what their jobs can read; + // the reasons below restate the same policies (see `pg_policies`) from the same session values. + format!( + "WITH s AS ( + SELECT current_setting('session.user') AS usr, + regexp_split_to_array(current_setting('session.groups'), ',') AS groups, + regexp_split_to_array(current_setting('session.pgroups'), ',') AS pgroups, + regexp_split_to_array(current_setting('session.folders_read'), ',') AS fr, + regexp_split_to_array(current_setting('session.folders_write'), ',') AS fw + ), items AS ({union}) + SELECT i.kind, i.path, + (split_part(i.path, '/', 1) = 'u' AND split_part(i.path, '/', 2) = s.usr) AS own, + CASE WHEN split_part(i.path, '/', 1) = 'g' AND split_part(i.path, '/', 2) = ANY(s.groups) + THEN split_part(i.path, '/', 2) END AS path_group, + (i.extra_perms ->> ('u/' || s.usr))::boolean AS user_grant, + ARRAY(SELECT substr(e.key, 3) FROM jsonb_each_text(i.extra_perms) e + WHERE e.key = ANY(s.pgroups) ORDER BY e.key) AS group_read, + ARRAY(SELECT substr(e.key, 3) FROM jsonb_each_text(i.extra_perms) e + WHERE e.key = ANY(s.pgroups) AND e.value::boolean ORDER BY e.key) AS group_write, + CASE WHEN split_part(i.path, '/', 1) = 'f' AND split_part(i.path, '/', 2) = ANY(s.fr) + THEN split_part(i.path, '/', 2) END AS folder, + (split_part(i.path, '/', 1) = 'f' AND split_part(i.path, '/', 2) = ANY(s.fw)) AS folder_write + FROM items i CROSS JOIN s + ORDER BY i.path, i.kind" + ) +} + +impl From<ItemRow> for ItemAccess { + fn from(r: ItemRow) -> Self { + let mut reasons = vec![]; + if r.own { + reasons.push(Reason::Own); + } + if let Some(group) = r.path_group { + reasons.push(Reason::GroupPath { group }); + } + if let Some(write) = r.user_grant { + reasons.push(Reason::User { write }); + } + for group in r.group_read { + let write = r.group_write.contains(&group); + reasons.push(Reason::Group { group, write }); + } + if let Some(folder) = r.folder { + reasons.push(Reason::Folder { folder, write: r.folder_write }); + } + let write = reasons.iter().any(|r| match r { + Reason::Own | Reason::GroupPath { .. } => true, + Reason::User { write } | Reason::Group { write, .. } | Reason::Folder { write, .. } => { + *write + } + }); + ItemAccess { kind: r.kind, path: r.path, write, reasons } + } +} + +async fn get_access( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path(w_id): Path<String>, + Query(AccessQuery { principal }): Query<AccessQuery>, +) -> JsonResult<AccessReport> { + let (prefix, name) = principal + .split_once('/') + .filter(|(_, name)| !name.is_empty()) + .ok_or_else(|| Error::BadRequest("principal must be u/<user> or g/<group>".into()))?; + + // Another principal's list names paths the caller may not be able to read. A group's reach is + // contained in each member's, so its members may see it. + let allowed = authed.is_admin + || match prefix { + "u" => name == authed.username, + "g" => authed.groups.iter().any(|g| g == name), + _ => false, + }; + if !allowed { + return Err(Error::PermissionDenied( + "only workspace admins can view the access of another member or of a group you are not in" + .into(), + )); + } + + let email = match prefix { + "u" => { + let usr = sqlx::query!( + "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2", + &w_id, + name + ) + .fetch_optional(&db) + .await? + .ok_or_else(|| Error::NotFound(format!("user {name} not found")))?; + if usr.disabled { + return Err(Error::BadRequest(format!( + "{name} is disabled, so nothing runs as them" + ))); + } + usr.email + } + "g" => { + // Instance groups are granted through the same `g/<name>` keys, and the check above + // lets their members ask, so a name from either table is a group here. + let exists = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2) + OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)", + &w_id, + name + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if !exists { + return Err(Error::NotFound(format!("group {name} not found"))); + } + String::new() + } + _ => { + return Err(Error::BadRequest( + "principal must be u/<user> or g/<group>".into(), + )) + } + }; + + let mut target = fetch_authed_from_permissioned_as(&principal, &email, &w_id, &db).await?; + // A workspace group and an instance group can share a name, and both come back. + target.groups.sort(); + target.groups.dedup(); + + if target.is_admin { + return Ok(Json(AccessReport { + principal, + is_admin: true, + groups: target.groups, + folders: vec![], + items: vec![], + })); + } + + let mut perms = target + .groups + .iter() + .map(|g| format!("g/{g}")) + .collect::<Vec<_>>(); + if prefix == "u" { + perms.insert(0, format!("u/{name}")); + } + let folder_names = target + .folders + .iter() + .map(|f| f.0.clone()) + .collect::<Vec<_>>(); + let mut via = sqlx::query!( + "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\" + FROM folder WHERE workspace_id = $1 AND name = ANY($2)", + &w_id, + &folder_names, + &perms + ) + .fetch_all(&db) + .await? + .into_iter() + .map(|r| (r.name, r.via)) + .collect::<std::collections::HashMap<_, _>>(); + let mut folders = target + .folders + .iter() + .map(|(name, write, owner)| FolderAccess { + name: name.clone(), + write: *write, + owner: *owner, + via: via.remove(name).unwrap_or_default(), + }) + .collect::<Vec<_>>(); + folders.sort_by(|a, b| a.name.cmp(&b.name)); + + let mut tx = user_db.begin(&target).await?; + let items = sqlx::query_as::<_, ItemRow>(&items_query()) + .bind(&w_id) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(ItemAccess::from) + .collect(); + tx.commit().await?; + + Ok(Json(AccessReport { + principal, + is_admin: false, + groups: target.groups, + folders, + items, + })) +} diff --git a/backend/windmill-api-groups/src/lib.rs b/backend/windmill-api-groups/src/lib.rs index 7abfa426ee..67bc1567f3 100644 --- a/backend/windmill-api-groups/src/lib.rs +++ b/backend/windmill-api-groups/src/lib.rs @@ -1,3 +1,4 @@ +pub mod access; pub mod folder_history; pub mod folders; pub mod granular_acls; diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 274bcb84ed..56217f53e1 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -25227,6 +25227,31 @@ paths: type: string description: Minimum semantic version across all workers (e.g. "1.583.0") + /w/{workspace}/access/get: + get: + summary: list what a workspace member or group can reach, and why + description: | + Workspace admins can query any principal; other members only themselves and the groups + they belong to. An admin principal reaches everything, so `items` is empty. + operationId: getPrincipalAccess + tags: + - granular_acl + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: principal + description: "`u/<username>` or `g/<group>`" + in: query + required: true + schema: + type: string + responses: + "200": + description: the principal's access + content: + application/json: + schema: + $ref: "#/components/schemas/PrincipalAccess" + /w/{workspace}/acls/get/{kind}/{path}: get: summary: get granular acls @@ -37240,6 +37265,66 @@ components: - script_path - is_flow + PrincipalAccess: + type: object + properties: + principal: + type: string + is_admin: + type: boolean + groups: + type: array + items: + type: string + folders: + type: array + items: + type: object + properties: + name: + type: string + write: + type: boolean + owner: + type: boolean + via: + description: the `u/<user>` or `g/<group>` grants on the folder that reach the principal + type: array + items: + type: string + required: [name, write, owner, via] + items: + type: array + items: + type: object + properties: + kind: + type: string + path: + type: string + write: + type: boolean + reasons: + type: array + items: + $ref: "#/components/schemas/AccessReason" + required: [kind, path, write, reasons] + required: [principal, is_admin, groups, folders, items] + + AccessReason: + type: object + properties: + type: + type: string + enum: [own, group_path, user, group, folder] + group: + type: string + folder: + type: string + write: + type: boolean + required: [type] + Group: type: object properties: diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 840e4da97b..b47a644131 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -679,6 +679,7 @@ pub async fn run_server( "/w/{workspace_id}", Router::new() // Reordered alphabetically + .nest("/access", windmill_api_groups::access::workspaced_service()) .nest("/acls", granular_acls::workspaced_service()) // CORS so the opaque-origin in-workspace app viewer (WIN-2006, // sandboxed /apps/get) can read the app definition by path diff --git a/backend/windmill-common/src/scopes.rs b/backend/windmill-common/src/scopes.rs index bf10e07e59..8549e673ba 100644 --- a/backend/windmill-common/src/scopes.rs +++ b/backend/windmill-common/src/scopes.rs @@ -424,7 +424,8 @@ impl ScopeDomain { "concurrency_groups" => Some(Self::ConcurrencyGroups), "oidc" => Some(Self::Oidc), "openapi" => Some(Self::Openapi), - "acls" => Some(Self::Acls), + // `/access` reports which grants reach a principal, so `acls` scopes cover it. + "acls" | "access" => Some(Self::Acls), "raw_apps" => Some(Self::RawApps), "agent_workers" => Some(Self::AgentWorkers), "mcp" => Some(Self::Mcp), diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index 82206dcd16..00f4406816 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,13 +4,13 @@ anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick" without any identifying data leaving the instance. -It currently carries 93 registered actions across thirty-six features (`ai_session`, `ai_chat`, +It currently carries 98 registered actions across thirty-nine features (`access_view`, `ai_session`, `ai_chat`, `ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`, `flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`, -`command_script`, `mcp`, `mcp_workspace`, `hub_script`, `usage_meter`, `sso_groups_claim`, +`command_script`, `mcp`, `mcp_workspace`, `mcp_external_client`, `hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`, `job_token_scopes`, `worker_draining`, `worker_group`, `worker_resource_stats`, `dev_workspace_isolation`, `slack_agent`, `variable_expiration`, -`anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the +`external_secret_ref`, `anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the product is uninstrumented, so new user-facing work is the opportunity to change that. ## When to instrument diff --git a/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte new file mode 100644 index 0000000000..7d6e562676 --- /dev/null +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -0,0 +1,409 @@ +<script lang="ts"> + import { Alert, Badge, Button, Drawer, DrawerContent, Section, Skeleton } from './common' + import TextInput from './text_input/TextInput.svelte' + import Select from './select/Select.svelte' + import DataTable from './table/DataTable.svelte' + import Head from './table/Head.svelte' + import Cell from './table/Cell.svelte' + import Row from './table/Row.svelte' + import RowIcon from './common/table/RowIcon.svelte' + import { Tooltip } from './meltComponents' + import { GranularAclService, type PrincipalAccess } from '$lib/gen' + import { useOperatingWorkspace } from './operatingWorkspace.svelte' + import { logFeatureUsage } from '$lib/utils/featureUsage' + import { pluralize } from '$lib/utils' + import { itemHref } from './offboarding-utils' + import { + buildAccessTree, + flattenAccessTree, + type AccessItem, + type AccessOwnerNode + } from './access/accessTree' + import { + ChevronDown, + ChevronRight, + ChevronsDownUp, + ChevronsUpDown, + ExternalLink, + Folder, + FolderTree, + User, + Users + } from 'lucide-svelte' + + const operatingWorkspace = useOperatingWorkspace() + + type Target = 'self' | 'user' | 'service_account' | 'group' + + const PAGE = 100 + // A short list opens fully, so every item shows at once. A longer one starts at its folders. + const OPEN_UP_TO = 30 + + const KIND_LABELS: Record<string, string> = { + script: 'Script', + flow: 'Flow', + app: 'App', + resource: 'Resource', + variable: 'Variable', + schedule: 'Schedule', + http_trigger: 'HTTP route', + websocket_trigger: 'WebSocket trigger', + kafka_trigger: 'Kafka trigger', + nats_trigger: 'NATS trigger', + postgres_trigger: 'Postgres trigger', + mqtt_trigger: 'MQTT trigger', + amqp_trigger: 'AMQP trigger', + gcp_trigger: 'GCP Pub/Sub trigger', + azure_trigger: 'Azure trigger', + sqs_trigger: 'SQS trigger', + email_trigger: 'Email trigger' + } + + let drawer: Drawer | undefined = $state() + let principal = $state('') + let access: PrincipalAccess | undefined = $state() + let error: string | undefined = $state() + let search = $state('') + let kind: string | undefined = $state() + let nbDisplayed = $state(PAGE) + /** Rows opened or closed by hand, by path prefix. The rest follow `expandAll`. */ + let openState: Record<string, boolean> = $state({}) + let expandAll: boolean | undefined = $state() + // Responses are not ordered: a slow answer for the previous principal must not land on this one. + let requestId = 0 + + export async function open(nextPrincipal: string, target: Target): Promise<void> { + principal = nextPrincipal + access = undefined + error = undefined + search = '' + kind = undefined + nbDisplayed = PAGE + openState = {} + expandAll = undefined + drawer?.openDrawer() + logFeatureUsage('access_view', 'opened', { key: target }) + const id = ++requestId + try { + const result = await GranularAclService.getPrincipalAccess({ + workspace: $operatingWorkspace!, + principal: nextPrincipal + }) + if (id === requestId) access = result + } catch (e) { + if (id === requestId) error = e?.body ?? String(e) + } + } + + const name = $derived(principal.slice(2)) + const isGroup = $derived(principal.startsWith('g/')) + const who = $derived(isGroup ? `members of ${principal}` : principal) + + const kindItems = $derived.by(() => { + const counts = new Map<string, number>() + for (const item of access?.items ?? []) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1) + return [...counts].map(([value, n]) => ({ + value, + label: `${KIND_LABELS[value] ?? value} (${n})` + })) + }) + + const query = $derived(search.trim().toLowerCase()) + const filtering = $derived(!!query || !!kind) + const allOpen = $derived(expandAll ?? (access?.items.length ?? 0) <= OPEN_UP_TO) + const tree = $derived(access && !access.is_admin ? buildAccessTree(access) : []) + const rows = $derived( + flattenAccessTree(tree, { + matches: (item) => + (!kind || item.kind === kind) && (!query || item.path.toLowerCase().includes(query)), + isOpen: (key) => openState[key] ?? allOpen, + filtering + }) + ) + + function toggle(key: string, open: boolean): void { + openState[key] = !open + } + + function toggleAll(): void { + expandAll = !allOpen + openState = {} + } + + function viaLabel(via: string): string { + return via === principal ? 'Shared directly' : `Through ${via}` + } + + /** Where holding the whole folder or space comes from. Empty when only some items are shared. */ + function ownerGrant(node: AccessOwnerNode): string { + if (!node.whole) return '' + if (node.key.startsWith('f/')) { + return [...(node.admin ? ['Folder admin'] : []), ...node.via.map(viaLabel)].join(', ') + } + return node.key === principal ? 'Own path' : `Through ${node.key}` + } + + function ownerExplanation(node: AccessOwnerNode): string { + const verb = node.write ? 'write' : 'read' + if (!node.whole) { + return node.key.startsWith('f/') + ? `${node.key} itself isn't shared with ${principal}. Only the items listed under it are, one by one, so items added to ${node.key} later stay out of reach.` + : `Only the items listed here are shared with ${principal}. Other items under ${node.key}/, and any added later, stay out of reach.` + } + if (node.key.startsWith('f/')) { + return node.via.length + ? `${node.key} itself is shared with ${node.via.join(' and ')}, so ${who} can ${verb} every item in it, including items added later.` + : `${principal} administers ${node.key}, so ${who} can write every item in it, including items added later.` + } + if (node.key === principal) { + return isGroup + ? `Items under ${principal}/ belong to the group, so its members can write every one of them, including items added later.` + : `Items under ${principal}/ belong to ${principal}, who can write every one of them, including items added later.` + } + return `${principal} is a member of ${node.key}, so ${principal} can write every item under ${node.key}/, including items added later.` + } + + /** Grants on the item itself. What its folder or space gives is said once, on that row. */ + function itemGrants(item: AccessItem): string[] { + return item.reasons.flatMap((r) => + r.type === 'user' ? ['Shared directly'] : r.type === 'group' ? [viaLabel(`g/${r.group}`)] : [] + ) + } + + function levelClass(item: AccessItem, grants: string[], owner: AccessOwnerNode): string { + if (!grants.length) return 'text-hint' + return item.write && owner.whole && !owner.write ? 'font-semibold text-emphasis' : '' + } + + // The drawer can report on the workspace a session editor acts in, which is not + // necessarily the one the new tab would otherwise open. + function withWorkspace(href: string): string { + const [route, hash] = href.split(/#(.*)/s) + const query = `?workspace=${encodeURIComponent($operatingWorkspace ?? '')}` + return route + query + (hash !== undefined ? `#${hash}` : '') + } + + function itemLink(kind: string, path: string): string | undefined { + const href = itemHref(kind, path) + return href ? withWorkspace(href) : undefined + } +</script> + +{#snippet chevron(key: string, open: boolean)} + <!-- Keyboard access only: its click bubbles to the row, which does the toggling. --> + <button + type="button" + class="text-secondary shrink-0" + aria-expanded={open} + aria-label={`${open ? 'Collapse' : 'Expand'} ${key}`} + > + {#if open} + <ChevronDown size={14} /> + {:else} + <ChevronRight size={14} /> + {/if} + </button> +{/snippet} + +<Drawer bind:this={drawer} size="1000px"> + <DrawerContent title={`Access of ${principal}`} on:close={() => drawer?.closeDrawer()}> + <div class="flex flex-col gap-6"> + <p class="text-xs text-secondary"> + {#if isGroup} + What members of g/{name} can read through this group alone, and which grant gives each item. + Members may reach more through their own grants and other groups. + {:else} + What {principal} can read, and which grant gives each item. Jobs that run as + {principal} read exactly this set. + {/if} + </p> + + {#if error} + <Alert type="error" title="Could not load access">{error}</Alert> + {:else if !access} + <Skeleton layout={[[2], 1, [6], 1, [12]]} /> + {:else if access.is_admin} + <Alert type="info" title="Workspace admin"> + {principal} is an admin of this workspace and can read and write every item in it. + </Alert> + {:else} + {#if !isGroup} + <Section label="Groups" small> + {#if access.groups.length} + <div class="flex flex-wrap gap-1"> + {#each access.groups as group (group)} + <Badge color="gray">g/{group}</Badge> + {/each} + </div> + {:else} + <p class="text-xs text-secondary">Not in any group.</p> + {/if} + </Section> + {/if} + + <Section label={`Items (${access.items.length})`} small> + <div class="flex flex-col gap-2"> + <div class="flex gap-2 items-center"> + <TextInput + bind:value={search} + inputProps={{ placeholder: 'Search paths' }} + size="sm" + class="grow" + /> + <div class="w-64"> + <Select + items={kindItems} + bind:value={kind} + placeholder="All kinds" + clearable + size="sm" + /> + </div> + <Button + variant="subtle" + unifiedSize="sm" + disabled={filtering} + startIcon={{ icon: allOpen ? ChevronsDownUp : ChevronsUpDown }} + on:click={toggleAll} + > + {allOpen ? 'Collapse all' : 'Expand all'} + </Button> + </div> + {#if rows.length} + <DataTable + size="xs" + shouldLoadMore={rows.length > nbDisplayed} + loadMore={PAGE} + on:loadMore={() => (nbDisplayed += PAGE)} + > + <Head> + <tr> + <Cell head first>Name</Cell> + <Cell head>Access</Cell> + <Cell head last>Granted by</Cell> + </tr> + </Head> + <tbody> + {#each rows.slice(0, nbDisplayed) as row (row.type === 'item' ? `${row.item.kind}:${row.item.path}` : row.node.key)} + {#if row.type === 'owner'} + {@const node = row.node} + {@const OwnerIcon = node.key.startsWith('f/') + ? Folder + : node.key.startsWith('g/') + ? Users + : User} + <Row + hoverable={row.count > 0} + class="group" + on:click={() => row.count > 0 && toggle(node.key, row.open)} + > + <Cell first> + <div class="flex items-center gap-1.5"> + {#if row.count > 0} + {@render chevron(node.key, row.open)} + {:else} + <span class="w-3.5 shrink-0"></span> + {/if} + <OwnerIcon size={14} class="text-secondary shrink-0" /> + <span class="font-semibold text-emphasis">{node.key}</span> + <span class="text-secondary">{pluralize(row.count, 'item')}</span> + {#if node.key.startsWith('f/')} + <a + href={withWorkspace(`/folders#${node.key}`)} + target="_blank" + class="text-secondary hover:text-emphasis opacity-0 group-hover:opacity-100 focus-visible:opacity-100" + aria-label={`Open ${node.key} in a new tab`} + title={`Open ${node.key} in a new tab`} + onclick={(e) => e.stopPropagation()} + > + <ExternalLink size={12} /> + </a> + {/if} + </div> + </Cell> + <Cell> + <!-- A badge is a level held on the folder or space itself; item rows show theirs as text. --> + <Tooltip class="-my-0.5"> + <Badge + color="gray" + class={node.whole + ? 'border border-transparent py-0' + : 'bg-transparent border border-dashed border-border-normal py-0'} + > + {node.whole ? (node.write ? 'Write' : 'Read') : 'Some items'} + </Badge> + {#snippet text()}{ownerExplanation(node)}{/snippet} + </Tooltip> + </Cell> + <Cell last>{ownerGrant(node)}</Cell> + </Row> + {:else if row.type === 'subfolder'} + <Row hoverable on:click={() => toggle(row.node.key, row.open)}> + <Cell first> + <div + class="flex items-center gap-1.5" + style="padding-left: {row.depth * 20}px" + > + {@render chevron(row.node.key, row.open)} + <FolderTree size={14} class="text-secondary shrink-0" /> + <span class="font-medium text-emphasis">{row.node.name}</span> + <span class="text-secondary">{pluralize(row.count, 'item')}</span> + </div> + </Cell> + <Cell></Cell> + <Cell last></Cell> + </Row> + {:else} + {@const item = row.item} + {@const grants = itemGrants(item)} + {@const href = itemLink(item.kind, item.path)} + <tr> + <Cell first> + <div + class="flex items-center gap-1.5" + style="padding-left: {row.depth * 20}px" + > + <span class="w-3.5 shrink-0"></span> + <span class="flex shrink-0" title={KIND_LABELS[item.kind] ?? item.kind}> + <RowIcon kind={item.kind as 'script'} size={14} /> + </span> + {#if href} + <a + {href} + target="_blank" + title={item.path} + class="group/link inline-flex items-center gap-1 text-primary hover:underline" + >{row.name}<ExternalLink + size={12} + class="opacity-0 group-hover/link:opacity-100 group-focus-visible/link:opacity-100 shrink-0" + /></a + > + {:else} + <span title={item.path}>{row.name}</span> + {/if} + </div> + </Cell> + <Cell> + <span class={levelClass(item, grants, row.owner)} + >{item.write ? 'Write' : 'Read'}</span + > + </Cell> + <Cell last>{grants.join(', ')}</Cell> + </tr> + {/if} + {/each} + </tbody> + </DataTable> + {:else} + <p class="text-xs text-secondary"> + {access.items.length || access.folders.length + ? 'No item matches.' + : `${principal} cannot read any item.`} + </p> + {/if} + </div> + </Section> + {/if} + </div> + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/GroupEditorDrawer.svelte b/frontend/src/lib/components/GroupEditorDrawer.svelte index 766fc6c4b8..230048fe6d 100644 --- a/frontend/src/lib/components/GroupEditorDrawer.svelte +++ b/frontend/src/lib/components/GroupEditorDrawer.svelte @@ -2,8 +2,10 @@ import { Button, Drawer, DrawerContent } from './common' import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte' import GroupEditor from './GroupEditor.svelte' - import { Save } from 'lucide-svelte' + import AccessDrawer from './AccessDrawer.svelte' + import { Save, ShieldCheck } from 'lucide-svelte' import { sendUserToast } from '$lib/toast' + import { useOperatingUser } from './operatingWorkspace.svelte' let { offset = 0, @@ -13,7 +15,9 @@ onSaved?: (name: string, created: boolean) => void | Promise<void> } = $props() + const operatingUser = useOperatingUser() let drawer: Drawer | undefined = $state() + let accessDrawer: AccessDrawer | undefined = $state() let mode: 'edit' | 'new' = $state('edit') let name: string = $state('') let canSave = $state(false) @@ -125,6 +129,17 @@ {/key} </div> {#snippet actions()} + {#if exists && (operatingUser.current?.is_admin || operatingUser.current?.is_super_admin || operatingUser.current?.groups.includes(name))} + <Button + variant="default" + unifiedSize="md" + startIcon={{ icon: ShieldCheck }} + title="What this group gives its members access to" + onClick={() => accessDrawer?.open(`g/${name}`, 'group')} + > + Access + </Button> + {/if} <Button variant="accent" unifiedSize="md" @@ -139,6 +154,8 @@ </DrawerContent> </Drawer> +<AccessDrawer bind:this={accessDrawer} /> + <!-- `alwaysPortal`: this drawer is opened from inside another drawer (the folder editor, itself reachable from a resource or variable form), and that outer drawer is a stacking context this dialog cannot climb out of on z-index alone. Left in place it paints under the drawer diff --git a/frontend/src/lib/components/access/accessTree.test.ts b/frontend/src/lib/components/access/accessTree.test.ts new file mode 100644 index 0000000000..301bd80ce8 --- /dev/null +++ b/frontend/src/lib/components/access/accessTree.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import type { PrincipalAccess } from '$lib/gen' +import { buildAccessTree } from './accessTree' + +const item = (path: string, reasons: PrincipalAccess['items'][number]['reasons']) => ({ + kind: 'script', + path, + write: false, + reasons +}) + +describe('buildAccessTree', () => { + it('marks a folder or space whole only when it is held itself', () => { + const tree = buildAccessTree({ + principal: 'u/alice', + is_admin: false, + groups: ['ops'], + folders: [{ name: 'reporting', write: false, owner: false, via: ['g/ops'] }], + items: [ + item('u/bob/shared_note', [{ type: 'group', group: 'ops', write: true }]), + item('g/ops/oncall_page', [{ type: 'group_path', group: 'ops' }]), + item('f/reporting/archive/q3_rollup', [{ type: 'folder', folder: 'reporting' }]), + item('f/ledger/close_month', [{ type: 'group', group: 'ops', write: false }]), + item('u/alice/scratch', [{ type: 'own' }]) + ] + }) + + expect(tree.map((n) => [n.key, n.whole])).toEqual([ + ['u/alice', true], + ['f/ledger', false], + ['f/reporting', true], + ['g/ops', true], + ['u/bob', false] + ]) + expect(tree[2].subfolders.map((s) => s.key)).toEqual(['f/reporting/archive']) + }) +}) diff --git a/frontend/src/lib/components/access/accessTree.ts b/frontend/src/lib/components/access/accessTree.ts new file mode 100644 index 0000000000..d13afe7eea --- /dev/null +++ b/frontend/src/lib/components/access/accessTree.ts @@ -0,0 +1,149 @@ +import type { PrincipalAccess } from '$lib/gen' + +export type AccessItem = PrincipalAccess['items'][number] + +/** A path segment under a folder or a space, like `archive` in `f/reporting/archive/q3_rollup`. */ +export interface AccessPathNode { + /** The full path prefix, e.g. `f/reporting/archive`. */ + key: string + name: string + subfolders: AccessPathNode[] + items: { item: AccessItem; name: string }[] +} + +/** A top-level row: a folder (`f/x`), a user's space (`u/x`) or a group's space (`g/x`). */ +export interface AccessOwnerNode extends AccessPathNode { + /** + * The folder or space itself is held, so every item in it is reachable, items added later + * included. False when only some of its items are shared with the principal, one by one. + */ + whole: boolean + /** The level that holding the whole folder or space gives. */ + write: boolean + /** The `u/` or `g/` grants on the folder that reach the principal. */ + via: string[] + /** The principal, or one of its groups, is an admin of the folder. */ + admin: boolean +} + +export type AccessTreeRow = + | { type: 'owner'; node: AccessOwnerNode; depth: number; count: number; open: boolean } + | { type: 'subfolder'; node: AccessPathNode; depth: number; count: number; open: boolean } + | { type: 'item'; item: AccessItem; name: string; owner: AccessOwnerNode; depth: number } + +/** Groups a principal's access by where each item lives, as the home page tree does. */ +export function buildAccessTree(access: PrincipalAccess): AccessOwnerNode[] { + const owners = new Map<string, AccessOwnerNode>() + const ownerNode = (key: string): AccessOwnerNode => { + let node = owners.get(key) + if (!node) { + node = { + key, + name: key, + whole: false, + write: false, + via: [], + admin: false, + subfolders: [], + items: [] + } + owners.set(key, node) + } + return node + } + + // A folder is held whole only through a grant on the folder itself. One that only shows up in + // item paths has some of its items shared one by one, and nothing added to it later is reachable. + for (const folder of access.folders) { + Object.assign(ownerNode(`f/${folder.name}`), { + whole: true, + write: folder.write, + via: folder.via, + admin: folder.owner + }) + } + for (const item of access.items) { + const segments = item.path.split('/') + const owner = ownerNode(segments.slice(0, 2).join('/')) + // The principal's own `u/` path, and the `g/` path of a group it is in, hold every item + // under them with write. Any other user's or group's space is reached item by item. + if (item.reasons.some((r) => r.type === 'own' || r.type === 'group_path')) { + owner.whole = true + owner.write = true + } + let parent: AccessPathNode = owner + for (const segment of segments.slice(2, -1)) { + let child = parent.subfolders.find((s) => s.name === segment) + if (!child) { + child = { key: `${parent.key}/${segment}`, name: segment, subfolders: [], items: [] } + parent.subfolders.push(child) + } + parent = child + } + parent.items.push({ item, name: segments[segments.length - 1] }) + } + + const rank = (node: AccessOwnerNode) => + node.key === access.principal + ? 0 + : node.key.startsWith('f/') + ? 1 + : node.key.startsWith('g/') + ? 2 + : 3 + const roots = [...owners.values()].sort((a, b) => rank(a) - rank(b) || a.key.localeCompare(b.key)) + roots.forEach(sortNode) + return roots +} + +function sortNode(node: AccessPathNode): void { + node.subfolders.sort((a, b) => a.name.localeCompare(b.name)) + node.items.sort((a, b) => a.name.localeCompare(b.name)) + node.subfolders.forEach(sortNode) +} + +export function countItems(node: AccessPathNode, matches: (item: AccessItem) => boolean): number { + return ( + node.items.filter(({ item }) => matches(item)).length + + node.subfolders.reduce((n, sub) => n + countItems(sub, matches), 0) + ) +} + +/** + * The rows to render, top to bottom. A filter opens every branch holding a match and drops the + * rest; without one, every folder and space shows, a folder held whole with no items included. + */ +export function flattenAccessTree( + roots: AccessOwnerNode[], + { + matches, + isOpen, + filtering + }: { + matches: (item: AccessItem) => boolean + isOpen: (key: string) => boolean + filtering: boolean + } +): AccessTreeRow[] { + const rows: AccessTreeRow[] = [] + const walk = (node: AccessPathNode, owner: AccessOwnerNode, depth: number) => { + for (const sub of node.subfolders) { + const count = countItems(sub, matches) + if (count === 0) continue + const open = filtering || isOpen(sub.key) + rows.push({ type: 'subfolder', node: sub, depth, count, open }) + if (open) walk(sub, owner, depth + 1) + } + for (const { item, name } of node.items) { + if (matches(item)) rows.push({ type: 'item', item, name, owner, depth }) + } + } + for (const owner of roots) { + const count = countItems(owner, matches) + if (filtering && count === 0) continue + const open = count > 0 && (filtering || isOpen(owner.key)) + rows.push({ type: 'owner', node: owner, depth: 0, count, open }) + if (open) walk(owner, owner, 1) + } + return rows +} diff --git a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte index 1215004767..99bacecdf8 100644 --- a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte +++ b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte @@ -42,8 +42,10 @@ LogIn, RefreshCw, Users, - ChevronDown + ChevronDown, + ShieldCheck } from 'lucide-svelte' + import AccessDrawer from '$lib/components/AccessDrawer.svelte' import Select from '$lib/components/select/Select.svelte' import SearchItems from '../SearchItems.svelte' import Cell from '../table/Cell.svelte' @@ -51,12 +53,14 @@ import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte' import UserOffboardingModal from '$lib/components/UserOffboardingModal.svelte' import { isCloudHosted } from '$lib/cloud' - import { truncate } from '$lib/utils' + import { truncate, type Item } from '$lib/utils' + import DropdownV2 from '$lib/components/DropdownV2.svelte' import { onDestroy, untrack } from 'svelte' import { goto } from '$lib/navigation' import { ArrowRightLeft, ExternalLink } from 'lucide-svelte' let offboardingUser: string | undefined = $state(undefined) + let accessDrawer: AccessDrawer | undefined = $state() let offboardingReassignOnly = $state(false) // `role` is the member's workspace role, which `listUsers` returns but the spec's `User` omits. @@ -365,6 +369,90 @@ let removeInstanceGroupConfirmedCallback: (() => void) | undefined = $state(undefined) let convertConfirmedCallback: (() => void) | undefined = $state(undefined) + function openAccess(user: User): void { + accessDrawer?.open( + `u/${user.username}`, + user.is_service_account + ? 'service_account' + : user.username === $userStore?.username + ? 'self' + : 'user' + ) + } + + async function impersonate(username: string): Promise<void> { + try { + // Backend sets the impersonation cookie and returns the old token + const oldToken = await UserService.impersonateServiceAccount({ + workspace: $workspaceStore ?? '', + requestBody: { username } + }) + if (oldToken) { + sessionStorage.setItem('pre_impersonation_token', oldToken) + sessionStorage.setItem('pre_impersonation_email', $userStore?.email ?? '') + } + window.location.href = '/' + } catch (e) { + sendUserToast('Failed to impersonate service account', true) + } + } + + function offboard(username: string, reassignOnly: boolean): void { + offboardingUser = username + offboardingReassignOnly = reassignOnly + } + + function confirmConvert(username: string): void { + convertConfirmedCallback = async () => { + await convertUserToGroup(username) + } + } + + const INSTANCE_GROUP_REMOVE_HINT = + 'Cannot remove users synced from instance groups. Either disable the user or remove them from the SCIM group.' + + function rowActions(user: User): Item[] { + const fromInstanceGroup = user.added_via?.source === 'instance_group' + const convertible = !fromInstanceGroup && canConvertToGroup(user) + return [ + { + displayName: 'Access', + icon: ShieldCheck, + disabled: user.disabled, + description: user.disabled ? 'Disabled: nothing runs as this user' : undefined, + action: () => openAccess(user) + }, + { + displayName: 'Impersonate', + icon: LogIn, + hide: !(user.is_service_account && $userStore?.is_admin), + disabled: !$enterpriseLicense, + description: !$enterpriseLicense ? 'Requires Enterprise Edition' : undefined, + action: () => impersonate(user.username) + }, + { + displayName: 'Reassign', + icon: ArrowRightLeft, + hide: fromInstanceGroup || convertible, + action: () => offboard(user.username, true) + }, + { + displayName: 'Convert', + hide: !convertible, + action: () => confirmConvert(user.username) + }, + { + displayName: 'Remove', + icon: UserMinus, + type: 'delete', + hide: convertible, + disabled: fromInstanceGroup, + description: fromInstanceGroup ? INSTANCE_GROUP_REMOVE_HINT : undefined, + action: () => offboard(user.username, false) + } + ] + } + // Auto-add/invite confirmation modal states let autoAddConfirmCallback: (() => void) | undefined = $state(undefined) let autoInviteDisableConfirmCallback: (() => void) | undefined = $state(undefined) @@ -962,87 +1050,7 @@ /> </Cell> <Cell last actions class={index % 2 === 0 ? 'bg-surface-tertiary' : ''}> - <div class="flex gap-1"> - {#if user.is_service_account && $userStore?.is_admin} - <Button - unifiedSize="sm" - variant="default" - startIcon={{ icon: LogIn }} - disabled={!$enterpriseLicense} - title={!$enterpriseLicense ? 'Requires Enterprise Edition' : undefined} - onClick={async () => { - try { - // Backend sets the impersonation cookie and returns the old token - const oldToken = await UserService.impersonateServiceAccount({ - workspace: $workspaceStore ?? '', - requestBody: { username } - }) - if (oldToken) { - sessionStorage.setItem('pre_impersonation_token', oldToken) - sessionStorage.setItem('pre_impersonation_email', $userStore?.email ?? '') - } - window.location.href = '/' - } catch (e) { - sendUserToast('Failed to impersonate service account', true) - } - }} - > - Impersonate - </Button> - {/if} - {#snippet removeUserButton(disabled: boolean)} - <Button - unifiedSize="sm" - variant="subtle" - destructive - {disabled} - onClick={() => { - offboardingUser = username - offboardingReassignOnly = false - }} - startIcon={{ icon: UserMinus }} - > - Remove - </Button> - {/snippet} - - {#if added_via?.source === 'instance_group'} - <div class="flex items-center gap-1"> - {@render removeUserButton(true)} - <Tooltip - >Cannot remove users synced from instance groups. Either disable the user or - remove them from the SCIM group.</Tooltip - > - </div> - {:else if canConvertToGroup(user)} - <Button - variant="accent" - unifiedSize="sm" - on:click={() => { - convertConfirmedCallback = async () => { - await convertUserToGroup(username) - } - }} - > - Convert - </Button> - {:else} - <div class="flex items-center gap-1"> - <Button - unifiedSize="sm" - variant="subtle" - onClick={() => { - offboardingUser = username - offboardingReassignOnly = true - }} - startIcon={{ icon: ArrowRightLeft }} - > - Reassign - </Button> - {@render removeUserButton(false)} - </div> - {/if} - </div> + <DropdownV2 items={rowActions(user)} /> </Cell> </tr> {/each} @@ -1176,6 +1184,8 @@ {/if} </Section> {/if} +<AccessDrawer bind:this={accessDrawer} /> + {#if offboardingUser} <UserOffboardingModal open={offboardingUser != null} diff --git a/frontend/src/lib/components/sidebar/SettingsMenu.svelte b/frontend/src/lib/components/sidebar/SettingsMenu.svelte index d4f44a7272..a2b00c508b 100644 --- a/frontend/src/lib/components/sidebar/SettingsMenu.svelte +++ b/frontend/src/lib/components/sidebar/SettingsMenu.svelte @@ -23,8 +23,10 @@ PanelLeft, Star, FolderOpen, - Users + Users, + ShieldCheck } from 'lucide-svelte' + import AccessDrawer from '../AccessDrawer.svelte' import { sidebarPrefs } from './sidebarPrefs.svelte' import { goto } from '$lib/navigation' import { type Item } from '$lib/utils' @@ -96,6 +98,7 @@ ) let deleteForkModal = $state<DeleteForkedWorkspaceModal>() + let accessDrawer = $state<AccessDrawer>() const { recent: recentChangelogs, hasNew } = readRecentChangelogs() let hasNewChangelogs = $state(hasNew) @@ -247,6 +250,17 @@ icon: Settings, action: () => goto(USER_SETTINGS_HASH) }, + // A superadmin who is not a member has no `usr` row, so there is no access to list. + ...($userStore && !$userStore.non_member + ? [ + { + displayName: 'My access', + icon: ShieldCheck, + action: () => + setTimeout(() => accessDrawer?.open(`u/${$userStore?.username}`, 'self'), 50) + } + ] + : []), ...(!$roleCapabilities.code ? [ { @@ -407,4 +421,6 @@ <DeleteForkedWorkspaceModal bind:this={deleteForkModal} /> +<AccessDrawer bind:this={accessDrawer} /> + <DarkModeObserver bind:darkMode /> diff --git a/frontend/src/routes/(root)/(logged)/folders/+page.svelte b/frontend/src/routes/(root)/(logged)/folders/+page.svelte index d114e77de1..550dad0391 100644 --- a/frontend/src/routes/(root)/(logged)/folders/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/folders/+page.svelte @@ -20,6 +20,7 @@ import Row from '$lib/components/table/Row.svelte' import Badge from '$lib/components/common/badge/Badge.svelte' import { untrack } from 'svelte' + import { page } from '$app/stores' import { DEMO_RESTRICTION_HINT, isDemoWorkspaceRestricted } from '$lib/cloud' let restricted = $derived( @@ -54,6 +55,20 @@ } }) + // Deep link: #f/<name> opens that folder's drawer. The `f/` prefix keeps it apart from + // global drawer hashes like #superadmin-settings, which a bare folder name could collide with. + let handledHash = '' + $effect(() => { + const hash = $page.url.hash + if (!hash.startsWith('#f/')) { + handledHash = '' + return + } + if (hash === handledHash || !folderEditorDrawer) return + handledHash = hash + folderEditorDrawer.initEdit(decodeURIComponent(hash.slice(3))) + }) + function computeMembers(owners: string[], extra_perms: Record<string, any>) { const members = new Set(owners) for (const [user, _] of Object.entries(extra_perms)) { diff --git a/frontend/src/routes/(root)/(logged)/groups/+page.svelte b/frontend/src/routes/(root)/(logged)/groups/+page.svelte index c5d295d00a..3615038a17 100644 --- a/frontend/src/routes/(root)/(logged)/groups/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/groups/+page.svelte @@ -7,6 +7,7 @@ import { Button, Drawer, DrawerContent, Skeleton } from '$lib/components/common' import Dropdown from '$lib/components/DropdownV2.svelte' import GroupEditorDrawer from '$lib/components/GroupEditorDrawer.svelte' + import AccessDrawer from '$lib/components/AccessDrawer.svelte' import InstanceGroupEditor from '$lib/components/InstanceGroupEditor.svelte' import GroupInfo from '$lib/components/GroupInfo.svelte' import PageHeader from '$lib/components/PageHeader.svelte' @@ -14,7 +15,7 @@ import { userStore, workspaceStore, roleCapabilities } from '$lib/stores' import { useEditRights } from '$lib/operatorWriteRights' import { latestRequest } from '$lib/utils/latestRequest' - import { Pen, Plus, Trash } from 'lucide-svelte' + import { Pen, Plus, ShieldCheck, Trash } from 'lucide-svelte' import DataTable from '$lib/components/table/DataTable.svelte' import Head from '$lib/components/table/Head.svelte' import Cell from '$lib/components/table/Cell.svelte' @@ -32,6 +33,7 @@ let groups: Group[] | undefined = $state(undefined) let instanceGroups: InstanceGroupWithWorkspaces[] | undefined = $state(undefined) let groupEditorDrawer: GroupEditorDrawer | undefined = $state() + let accessDrawer: AccessDrawer | undefined = $state() const groupLoads = latestRequest() async function loadGroups(): Promise<void> { @@ -61,6 +63,7 @@ </script> <GroupEditorDrawer bind:this={groupEditorDrawer} onSaved={loadGroups} /> +<AccessDrawer bind:this={accessDrawer} /> <Drawer bind:this={instanceGroupDrawer}> <DrawerContent @@ -122,9 +125,13 @@ {#if groups === undefined} {#each new Array(4) as _} <tr> - <td colspan="5"> - <Skeleton layout={[[2]]} /> - </td> + <Cell first> + <Skeleton layout={[[{ h: 0.75, w: 30 }], 0.25, [{ h: 0.75, w: 60 }], 0.25]} /> + </Cell> + <Cell> + <Skeleton layout={[[{ h: 0.75, w: 40 }]]} /> + </Cell> + <Cell last actions /> </tr> {/each} {:else} @@ -149,6 +156,16 @@ <Cell last actions shouldStopPropagation> <Dropdown items={[ + { + displayName: 'Access', + icon: ShieldCheck, + hide: !( + $userStore?.is_admin || + $userStore?.is_super_admin || + $userStore?.groups.includes(name) + ), + action: () => accessDrawer?.open(`g/${name}`, 'group') + }, { displayName: 'Manage group', icon: Pen,